Module 4 of 7 · 60 min

Build Bounded Claude Tool and Agent Loops

Connect Claude to client and server tools through narrow contracts, enforced authority, explicit loop states, bounded budgets, postcondition checks, and safe recovery.

Anthropic

By the end

You will be able to

  • Distinguish user-defined client tools, Anthropic-schema client tools, and server-executed tools.
  • Define narrow schemas and enforce authorization, validation, idempotency, and postconditions outside the model.
  • Drive the tool-use loop from explicit stop reasons, budgets, approvals, and terminal states.
  • Choose a deterministic workflow or a bounded agent according to task uncertainty and operational risk.
01

Tool use is an execution contract

A tool definition tells Claude which operation exists and what inputs it accepts. For a client tool, Claude emits a structured tool request, the application validates and executes it, and the application returns a matching result. The model does not secretly run your business logic.

Server-executed tools run through Anthropic's infrastructure, while user-defined and Anthropic-schema client tools run through your application. Identify the execution owner because it determines authentication, data handling, error recovery, logging, and who verifies the side effect.

02

Design narrow, legible tools

Give each tool a clear purpose, precise name, complete description, strict input shape, constrained values, and unambiguous result. A tool such as update_record with a defined record identifier and allowed fields is safer to authorize and evaluate than execute_arbitrary_request.

Treat tool arguments as untrusted proposals. Validate schema and business rules, resolve the acting identity, authorize the exact resource and operation, and reject unknown or excess fields before execution.

Narrow tool definition
json
{
  "name": "set_training_status",
  "description": "Set one learner module to an allowed status after authorization.",
  "input_schema": {
    "type": "object",
    "properties": {
      "learnerId": { "type": "string" },
      "moduleId": { "type": "string" },
      "status": { "enum": ["not-started", "in-progress", "completed"] },
      "operationId": { "type": "string" }
    },
    "required": ["learnerId", "moduleId", "status", "operationId"],
    "additionalProperties": false
  }
}
03

Drive an explicit loop

For client tools, preserve the assistant's tool-use blocks, execute each authorized call, and return results matched to the correct tool-use identifier. Continue only while the stop reason and workflow state allow it. Handle parallel requests, tool errors, pauses, refusals, output limits, and final turns deliberately.

Define maximum turns, tool calls, elapsed time, tokens, cost, and consecutive failures. Add a cancellation signal and terminal states such as completed, needs approval, refused, budget exceeded, failed safely, and outcome unknown.

04

Enforce side-effect safety around the model

Separate read operations, reversible writes, external communication, privileged changes, and destructive actions. Require stronger evidence and human approval as consequence and irreversibility increase. The prompt can describe these rules, but the application must enforce them.

Use operation identifiers and idempotent handlers where possible. After an execution error or timeout, record whether the outcome is confirmed success, confirmed failure, or unknown. Reconcile the target system and verify the postcondition before retry, compensation, rollback, or completion.

05

Choose workflow or agent deliberately

Use a deterministic workflow when the steps and branches are known and repeatability matters. Use a bounded agent when the path depends on observations, tool results, and intermediate decisions that cannot be enumerated economically.

Start with the simplest composable pattern that meets the requirement. Add routing, parallelism, evaluators, memory, or multiple agents only when evaluation evidence shows the simpler design is insufficient. Greater autonomy requires stronger containment, observability, recovery, and human escalation.

Practice activity

Implement a bounded Claude tool loop

  1. Define one read tool and one reversible write tool with strict schemas, explicit identities, resource authorization, operation identifiers, and documented error results.
  2. Draw or implement loop states for request, model response, validation, approval, execution, result return, postcondition verification, terminal success, safe failure, budget exceeded, and unknown outcome.
  3. Create tests for invalid arguments, unauthorized scope, duplicate operation identifier, rejected approval, tool timeout after a possible write, mismatched result identifier, and maximum-turn exhaustion.
  4. Compare the bounded agent with a deterministic workflow and justify which design you would release using quality, risk, latency, cost, and recovery evidence.

What to produce

  • Two secret-free tool contracts plus policy, idempotency, approval, loop-state, budget, postcondition, and recovery implementation or design evidence.
  • A passing adversarial test report and a documented workflow-versus-agent release decision tied to measurable requirements.

Reflect before continuing

Which control in your design remains trustworthy if the model selects the wrong tool with plausible arguments?

Evidence

Sources and verification

Knowledge check

Make it stick.

Pass at 80%

Choose the strongest answer for each question. Your attempts become part of your device-local transcript.

01Who executes a user-defined client tool requested by Claude?
02What should happen before a tool handler changes a record?
03A write tool times out after the target may have accepted it. What is the next state?
04When is a deterministic workflow preferable to an agent?
05Which set makes an agent loop bounded?