PREP WITH PROOF
Menu
AI & AUTOMATION / PRACTICAL GUIDE

Validate AI Agent Tool Calls: Arguments, Dispatch and Authorization

Build a server-side boundary for AI agent tool calls. Test strict arguments, fixed dispatch and tenant-scoped authorization with a runnable Python fixture.

THE QUICK ANSWER

An AI agent tool call is a proposed operation. Before executing it, the application must validate its shape, restrict the available operation and check the authenticated caller’s access to the specific resource. A correctly formatted order ID can still identify an order the caller cannot read. This guide builds that boundary with a small, executable Python example: the same valid call returns different invented records under two server-owned tenant identities, while rejected calls never reach the record read.

Start with the boundary you actually control

A document assistant might discover an order number in a retrieved page and ask a tool for its status. The page could be outdated, malicious or simply refer to another customer. The model can produce a perfectly plausible lookup request in all three cases. Checking whether that request resembles JSON does not establish who owns the order.

In this example, the model chooses one operation and one order ID. The application owns the authenticated principal, the permitted operation and the data access policy. There is no model-provided tenant, administrator flag, database query or destination URL. This deliberately small interface makes the enforcement points visible.

OWASP describes excessive agency in terms of unnecessary functionality, permissions and autonomy. Here we apply that concern to a concrete read-only boundary. A read can still disclose another customer’s information; avoiding writes does not remove the need for authorization.

Source: OWASP Gen AI: LLM06 Excessive Agency ↗

Define one narrow contract before connecting the model

The accepted envelope has exactly two keys: name and arguments. The name must be lookup_order. Arguments must contain exactly one order_id string, consisting of ORD- followed by four ASCII digits. This is an invented identifier format for the lab, not a recommendation to redesign an existing order system.

JSON Schema can describe the structural part of this contract. Its properties keyword alone does not require fields or reject unknown fields; use required and additionalProperties deliberately. The schema below documents the intended shape. It does not express whether a particular caller can access a particular order.

We use a short purpose-built Python validator for this fixed contract in the executable program, so the lab needs no dependency installation. It is not a JSON Schema engine. If your application already uses a schema library, validate the instance with a compatible draft and retain the separate authorization checks. Do not grow this example into a home-made implementation of the specification.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": [
    "name",
    "arguments"
  ],
  "additionalProperties": false,
  "properties": {
    "name": {
      "const": "lookup_order"
    },
    "arguments": {
      "type": "object",
      "required": [
        "order_id"
      ],
      "additionalProperties": false,
      "properties": {
        "order_id": {
          "type": "string",
          "minLength": 8,
          "maxLength": 8,
          "pattern": "^ORD-[0-9]{4}$"
        }
      }
    }
  }
}

Source: JSON Schema: Object properties, required fields and additional properties ↗

Keep identity out of generated arguments

The fixture has two tenants, alpha and beta. Both have a record called ORD-1001, but their statuses differ. The data key is the pair of tenant and order ID. A call containing only ORD-1001 therefore cannot select the tenant by itself.

The Principal object represents already authenticated server context. Its readable_orders set is an intentionally simplified permission snapshot. In a real request handler, construct this context from verified authentication and your authorization service. Never deserialize a Principal supplied alongside the model response and treat it as trusted.

The lookup checks both the caller’s readable IDs and the tenant-scoped record key. An alpha principal allowed to read ORD-1001 sees packed; a beta principal with the equivalent grant sees cancelled. The alpha principal cannot read ORD-1002 even though that record exists in alpha. These are two different checks: belonging to a tenant does not imply access to every record in it.

OWASP recommends checking permissions on every request and denying access by default. For this implementation, that means every execution reaches the policy check with server-owned context, including repeated calls within the same agent conversation. A prior successful lookup is not a grant for the next ID.

Source: OWASP Authorization Cheat Sheet ↗

Run the complete local fixture

Save the following program as agent_tool_boundary.py and run python3 agent_tool_boundary.py using Python 3.12 or later. The published program was executed with Python 3.12.14. It uses only the standard library and invented in-memory records. No LLM, credentials, network connection, database or external service is involved.

The program parses a bounded byte string, validates the fixed contract, then invokes a single read function. READS is test instrumentation: it records only successful access to the fixture data. It is not a production audit log. The tests snapshot it before each rejection and fail if that snapshot changes.

Python’s JSON decoder supports hooks for object pairs and nonstandard numeric constants. The parser uses these hooks to reject duplicate keys and NaN rather than silently accepting an ambiguous call. The 1,024-byte limit is a lab policy, not a general safe size for every agent. An HTTP or SDK adapter must also impose a limit before it buffers the response.

"""Local read-only fixture. Python 3.12+, no external packages."""
import json
from dataclasses import dataclass

class Rejected(ValueError):
    pass

@dataclass(frozen=True)
class Principal:
    tenant: str
    readable_orders: frozenset[str]

# Invented records; this program never calls a real service.
ORDERS = {
    ('alpha', 'ORD-1001'): 'packed',
    ('alpha', 'ORD-1002'): 'shipped',
    ('beta', 'ORD-1001'): 'cancelled',
}
READS = []

def reject_constant(value):
    raise Rejected('invalid_json')

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise Rejected('duplicate_key')
        result[key] = value
    return result

def parse_call(raw):
    # The HTTP/SDK adapter must also bound input before buffering it.
    if type(raw) is not bytes or len(raw) > 1024:
        raise Rejected('input_limit')
    try:
        return json.loads(raw.decode('utf-8'),
                          object_pairs_hook=unique_object,
                          parse_constant=reject_constant)
    except Rejected:
        raise
    except (UnicodeDecodeError, ValueError, RecursionError):
        raise Rejected('invalid_json') from None

def validate_call(call):
    # A validator for this one contract, NOT a JSON Schema implementation.
    if type(call) is not dict or set(call) != {'name', 'arguments'}:
        raise Rejected('envelope')
    if type(call['name']) is not str or call['name'] != 'lookup_order':
        raise Rejected('unknown_tool')
    args = call['arguments']
    if type(args) is not dict or set(args) != {'order_id'}:
        raise Rejected('arguments')
    order_id = args['order_id']
    if (type(order_id) is not str or len(order_id) != 8
            or order_id[:4] != 'ORD-'
            or any(c not in '0123456789' for c in order_id[4:])):
        raise Rejected('order_id')
    return order_id

def lookup_order(principal, order_id):
    # In a real database: scope the query by authenticated tenant AND order ID.
    if order_id not in principal.readable_orders:
        raise Rejected('not_available')
    key = (principal.tenant, order_id)
    if key not in ORDERS:
        raise Rejected('not_available')
    READS.append(key)
    return {'order_id': order_id, 'status': ORDERS[key]}

def execute(raw, principal):
    order_id = validate_call(parse_call(raw))
    # Fixed dispatch: no eval, imports, shell, or arbitrary URL from the model.
    return lookup_order(principal, order_id)

def encode(arguments, name='lookup_order'):
    return json.dumps({'name': name, 'arguments': arguments}).encode()

def self_test():
    alpha = Principal('alpha', frozenset({'ORD-1001'}))
    beta = Principal('beta', frozenset({'ORD-1001'}))
    allowed = encode({'order_id': 'ORD-1001'})
    assert execute(allowed, alpha)['status'] == 'packed'
    assert execute(allowed, beta)['status'] == 'cancelled'
    assert READS == [('alpha', 'ORD-1001'), ('beta', 'ORD-1001')]
    cases = [
        (encode({'order_id': 'ORD-1002'}), alpha, 'not_available'),
        (allowed, Principal('alpha', frozenset()), 'not_available'),
        (allowed, Principal('missing', frozenset({'ORD-1001'})), 'not_available'),
        (encode({'order_id': 'ORD-1001', 'tenant': 'beta'}), alpha, 'arguments'),
        (encode({'order_id': 'ORD-1001'}, 'delete_order'), alpha, 'unknown_tool'),
        (encode({}), alpha, 'arguments'),
        (encode([]), alpha, 'arguments'),
        (b'[]', alpha, 'envelope'),
        (b'null', alpha, 'envelope'),
        (b'{"name":"lookup_order","arguments":{},"admin":true}', alpha, 'envelope'),
        (b'{"name":"lookup_order","arguments":{"order_id":"ORD-1001","order_id":"ORD-1002"}}', alpha, 'duplicate_key'),
        (b'{"name":"lookup_order","arguments":{"order_id":NaN}}', alpha, 'invalid_json'),
        (b'\xff', alpha, 'invalid_json'),
        (b'{', alpha, 'invalid_json'),
        (allowed.decode(), alpha, 'input_limit'),
        (b' ' * 1025, alpha, 'input_limit'),
    ]
    for value in [None, True, 1001, '1001', 'ORD-123', 'ORD-12345',
                  'ORD-1001\n', 'ORD-\u0661\u0660\u0660\u0661', 'ORD-1A01',
                  '../../x', 'ignore previous instructions']:
        cases.append((encode({'order_id': value}), alpha, 'order_id'))
    before = list(READS)
    for raw, principal, expected in cases:
        try:
            execute(raw, principal)
        except Rejected as error:
            assert str(error) == expected, (raw, str(error), expected)
        else:
            raise AssertionError(('unexpected acceptance', raw))
        assert READS == before, 'Rejected input reached the read operation'
    # Exact byte boundary: harmless JSON whitespace counts toward the budget.
    padded = allowed + b' ' * (1024 - len(allowed))
    assert execute(padded, alpha)['status'] == 'packed'
    assert READS[-1] == ('alpha', 'ORD-1001')
    print(f'PASS: 3 allowed calls, {len(cases)} rejections; rejected calls made no reads')

if __name__ == '__main__':
    self_test()

Source: Python standard library: JSON decoding and decoder hooks ↗

Read the test results as boundary evidence

The expected final line is PASS: 3 allowed calls, 27 rejections; rejected calls made no reads. The three allowed executions are the alpha lookup, the beta lookup and an alpha lookup padded with harmless JSON whitespace to exactly 1,024 bytes. They exercise the chosen contract and boundary, not the security of a deployed agent.

The rejection set includes malformed input, a duplicate order_id, a non-object envelope, missing or extra fields, an unrecognized tool and invalid identifier types. It also includes three authorization failures that have structurally valid arguments. Those failures are the essential counterexample to treating successful validation as permission.

The Unicode digit fixture is intentional. Human readers can perceive several Unicode characters as digits, but this contract accepts only the ASCII characters 0 through 9. The identifier is not trimmed, case-folded or otherwise repaired. If an existing API normalizes identifiers, make that policy explicit and test the normalized identifier against the same resource authorization rules.

No fixture proves that the model will choose the correct customer order in an actual conversation. A permitted but semantically wrong order remains possible. The boundary limits what can be read; task correctness still needs evaluation with realistic user requests and retrieved material.

CaseStageExpected outcome
ORD-1001 under alpha versus betaResource accessDifferent tenant-scoped statuses
Existing ORD-1002 without a grantAuthorizationnot_available; no read
Forged tenant argumentContract validationarguments; no read
delete_order tool nameDispatch allowlistunknown_tool; no read
Duplicate order_idParsingduplicate_key; no read
1,025 input bytesInput budgetinput_limit; no read

Adapt the boundary without erasing it

Provider SDKs use different tool-call envelopes. Some expose arguments as a JSON string; others provide a parsed value. Write a small adapter for the exact format you receive. Do not assume the envelope in this tutorial is a provider API contract, and do not blindly parse a value twice. If the SDK has already discarded duplicate keys, this downstream validator cannot recover that evidence.

Keep the selected tool name in an explicit allowlist. The lab has only one entry, so dispatch is a direct function call. A larger application can use a fixed dictionary of tool names to reviewed handlers. Never convert a generated name into an import path, executable expression, shell command or arbitrary network destination.

At the data layer, scope the actual query by the authenticated tenant and resource identifier, with parameterized inputs and the required permission constraints. Do not fetch a global record first and accidentally return part of it before checking ownership. The in-memory pair lookup demonstrates the intended scope but does not test your database’s query, connection identity or row-level policies.

Enforce independent budgets for call count, execution duration and output size. The byte limit in this program bounds its input only. It does not stop an agent from issuing thousands of valid requests. A read-only backend should also use credentials that cannot write, so a routing mistake does not automatically gain write privileges.

Handle rejection without creating a new permission path

The lab distinguishes parser, contract and access failures for local tests. A production response can use a less revealing not_available result for both absent and unauthorized resources. Keep detailed diagnostics in appropriately restricted server logs, with redaction, a request correlation ID and a policy version. Avoid recording raw prompts or sensitive tool arguments by default.

If a model receives a validation error, it may propose a corrected call. Run that new proposal through the entire boundary again. Do not let a retry bypass identity checks, expand the tool allowlist or inherit an authorization decision made for another order. Limit repair attempts so a malformed interaction cannot consume an unbounded execution budget.

For a future write tool, design its policy separately. Define the exact operation, permitted resource transitions and retry behavior before adding execution. An order-status read provides no evidence that a cancellation, payment or deletion would be safe. Where a product requires approval, bind it to the specific operation and validated arguments rather than to a vague conversation-level instruction.

What this lab leaves for your application

This program does not implement authentication, credential verification, revocation, concurrent permission updates or database transactions. The immutable Principal prevents accidental field assignment in this fixture; it does not make arbitrary Python objects trustworthy. The server must decide where identity comes from and when its permission snapshot expires.

It also does not provide a prompt-injection defense for the entire agent. Retrieved content and tool results remain untrusted information. This example has no general-purpose text argument or outbound URL, which removes several execution paths from the demo, but a real assistant may still reveal sensitive information through another tool or an overly broad response.

Test the service boundary with its real dependencies before deployment: verify that the query contains tenant scope, the backend identity has the intended rights, denied requests expose no record data and every alternate route enforces the same policy. Repeat the same-ID/different-tenant fixture against your integration because it catches mistakes that ordinary happy-path tests miss.

The practical result is a small separation of responsibilities: the model proposes an operation, the contract validator checks what was proposed, and the server decides whether that caller may perform it. Keep those decisions visible in code and tests as the agent gains more tools.

KEEP THESE THREE THINGS

Your next steps

  1. Treat tool calls as untrusted proposals and validate them before dispatch.
  2. Keep tenant identity and permissions in authenticated server context.
  3. Test structurally valid but unauthorized requests, including identical IDs in different tenants.
  4. The runnable fixture verifies one read-only contract; production authentication and data-layer enforcement require separate integration tests.

Sources & official resources

Linked resources checked on 2026-11-01. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →