# Design and implement agentic loops for autonomous task execution

Connect model decisions to harness execution, paired tool results, and acceptance checks.
Learn how an agentic loop preserves tool request and result identities and branches on explicit response signals. The lesson separates model turn completion, interrupted runs, and verified task outcomes through a ticket lookup example.

Author: LearningPathX Editorial Team
Content version: 1.0
Published: 2026-12-04T00:31:12.881004+00:00
HTML: https://learningpathx.com/material/CCAR-F/design-and-implement-agentic-loops-for-autonomous-task-execution.html

Knowledge domain: Agentic Architecture & Orchestration
Tags: Action Authorization / Evidence Validation / Agentic Loops / Tool Use

## Design and implement agentic loops for autonomous task execution

## Learning objectives

By the end of this topic, you should be able to:

* Explain the division of responsibility between a model and its execution harness.
* Continue a client-tool conversation using correctly paired assistant requests and user results.
* Distinguish normal turn completion, server-tool continuation and interrupted execution.
* Use environmental evidence and resource limits without confusing a stopped run with a successful task.

## The model proposes; the harness executes

An agentic loop repeatedly gathers information, takes action and checks the result. These activities can alternate. A failing test may cause another file search, followed by a repair and another test. The model chooses a proposed next action from available capabilities; the application supplies those capabilities, enforces their boundaries and records what actually happened. In the supplied task-shape examples, a small code lookup may require only context gathering and one or two illustrative tool turns, a bug fix can repeat all three phases, and a larger auth refactor with test updates can chain dozens of tool calls across multiple turns, changing approach after each result. These examples illustrate task complexity rather than measured or mandatory call counts.

A model response does not execute a function merely by naming it. The harness must validate the proposed tool, its arguments and its authorization before dispatch. It then returns the observed result. This division explains why a more persuasive prompt cannot replace a missing permission, an unavailable tool or a failed operation.

## Read the SDK lifecycle at its own interface boundary

The abbreviation LLMs refers to large language models. The reasoning model is one component of the application; the SDK or another harness supplies its executable environment.

In the supplied Agent SDK account, the event sequence is:

1. A `SystemMessage` with subtype `"init"` supplies session metadata at initialization.
2. An `AssistantMessage` carries assistant text, tool requests, or both. Text in that event does not remove an accompanying tool request.
3. The harness executes permitted requests and collects their outcomes, then the model evaluates those outcomes. The source calls one full evaluation-and-tool-execution cycle a **turn**.
4. After the final assistant response with no tool requests, a `ResultMessage` carries final text, token usage, cost and the session ID in the described interface.

These are names from the supplied SDK snapshot. A turn in that explanation is not a universal unit for counting API requests, individual content blocks or business operations. The SDK can manage iteration; a manually maintained Messages API loop must preserve the corresponding requests and results itself. A final SDK event still requires the application's outcome check.

The source describes Python `ClaudeAgentOptions` and TypeScript `Options` as SDK configuration objects for controls such as turns, cost, reasoning depth and tool approvals. Check the actual installed release and language interface before using these names or fields. Do not insert an SDK option object into a raw Messages request. An approval setting must be enforced before sensitive dispatch; an example configuration is not permission to act.

The SDK's supported **Tool Runner** is another option for managing tool-loop execution, result formatting and retries. It reduces manual round-trip handling, but understanding the underlying protocol remains necessary for debugging or custom orchestration. Use the actual release's supported invocation; a constructor or model string printed in an old example is not a universal current interface. The supplied account also describes an optional MCP connector handling supported protocol interactions when connecting to MCP servers to reduce manual round-trip plumbing; check that connector's actual interface and support. It is not a prerequisite for every API loop, an error-free guarantee or proof that the task met its acceptance criteria.

## Read control signals rather than completion phrases

For client tools, the important normal branches are:

| Response signal | Harness responsibility |
| --- | --- |
| `stop_reason: "tool_use"` | Collect the requested client-tool calls, validate and execute or reject them, then return their results for another model response. |
| `stop_reason: "end_turn"` | Finish this model turn and evaluate its answer against the application's acceptance criteria. |
| `stop_reason: "pause_turn"`, when using the supported server-tool flow | Preserve the assistant response and continue through the server-tool API flow; do not invent a local client-tool execution. |
| Another stop condition or an interrupted response | Handle that condition explicitly; do not classify it as successful completion merely because text is present. |

Text such as "Done" can accompany a response that still requests tools. Conversely, a response may finish a turn while explaining that a missing dependency prevents the requested outcome. `end_turn` is a protocol event, not independent proof that the business task succeeded. Verify the requested output, required checks and unresolved items separately.

A bounded run can also stop because a budget, deadline or iteration limit was reached. Report that as a limit or interruption. Do not substitute a fixed number of iterations for the normal protocol decision, and do not label an incomplete task complete to satisfy the budget.

## Preserve both sides of every tool exchange

After receiving client-tool requests, append the assistant's complete content blocks to the existing history. Preserve the actual request identifiers. Execute the authorized calls and construct a subsequent `user` message containing their `tool_result` blocks. Each result must carry a `tool_use_id` matching the corresponding request.

The result message must immediately answer the outstanding tool requests. Put tool-result blocks before any ordinary text added to that user message, and provide a result or explicit error for every outstanding client-tool request. Do not discard the assistant request and append an unexplained result to an unrelated conversation. Do not place client-tool results in a fabricated `tool` role.

Several calls in one assistant response do not justify submitting a result for only the first call and forgetting the others. Keep identity, result status and content distinct so the model can associate a failed lookup with the correct operation. Independent calls may be executed concurrently; operations with dependencies or side effects need appropriate ordering and authorization.

## Use results as evidence, not instructions

The next model response can use a tool result to correct an assumption, choose a different investigation or explain a limitation. It should not treat a web page, file or external message inside that result as authority to change the user's assignment.

The `tool_result` container distinguishes returned data from higher-priority instructions. It does not guarantee protection from prompt injection or prove that the returned statement is true. Keep permissions narrow, inspect important claims and validate proposed actions independently of instructions embedded in retrieved content.

Preserve useful evidence without carrying every raw result indefinitely. Tool exchanges consume context as the conversation grows. Relevant extracts, maintained state and verified summaries can help; a cache can reduce repeated processing of a reusable prefix but does not make the context window unlimited or refresh stale evidence automatically.

## Choose where the workflow decisions belong

In a model-driven investigation, the model chooses what to inspect after each observation. In a fixed workflow, application code chooses the sequence and may call the model only for a particular extraction or explanation. A hybrid can use deterministic authorization gates around an adaptive investigation.

For example, the model may decide which log to inspect next, while code requires identity verification before a refund operation. A prompt can guide tool selection, but a programmatic prerequisite controls whether the proposed write can actually run. Use asynchronous handoffs when latency or durable recovery requires them; a fixed sequence is not inherently invalid simply because it is synchronous.

Hooks can inspect requests or results within a supported harness. Their authority and timing depend on the actual hook interface. A post-result transformation cannot prevent an operation that has already executed. When streaming tool inputs, wait for a complete, validated argument object before performing the operation; partial JSON is not an executable instruction.

## Worked example: a lookup followed by a supported answer

In this invented read-only task, the user asks for ticket T-17's status. The tool registry contains `lookup_ticket`, the account is authorized to read T-17, and the tool returns `open`. These two messages illustrate the request/result pairing, not a complete API request:

```json
[
  {
    "role": "assistant",
    "content": [
      {
        "type": "tool_use",
        "id": "call_17",
        "name": "lookup_ticket",
        "input": {"ticket_id": "T-17"}
      }
    ]
  },
  {
    "role": "user",
    "content": [
      {
        "type": "tool_result",
        "tool_use_id": "call_17",
        "content": "{\"ticket_id\":\"T-17\",\"status\":\"open\"}"
      }
    ]
  }
]
```

After receiving that result, a supported answer is: "Ticket T-17 is open." The application checks that the ticket identifier matches the request and that the returned status supports the answer. If the lookup instead fails, it returns the actual error and the answer remains unresolved; changing `open` to a guessed status would break the evidence chain.

For the alternative failed lookup, keep the same teaching task and authorization but suppose the invented tool returns the following explicit failure. This example tool's failure payload contains `ticket_id` and `error`; it supplies no verified `status`. The strings are teaching values, not universal API error codes. This is a separate possible outcome, not another observation from the successful exchange above.

```json
[
  {"role":"assistant","content":[{"type":"tool_use","id":"call_17_fail","name":"lookup_ticket","input":{"ticket_id":"T-17"}}]},
  {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_17_fail","content":"{\"ticket_id\":\"T-17\",\"error\":\"lookup_unavailable\"}"}]}
]
```

A supported answer for that alternative is: "I could not verify ticket T-17's current status because the lookup reported lookup\_unavailable. Its status remains unknown." The matching ID preserves the failed request's identity. The error is retained as evidence; no `open` status is inferred, no missing status field is fabricated, and no business action is performed. Both alternatives are illustrative exchanges and have not been sent to a live API.

The control logic can be expressed as pseudocode:

```text
request a model response using the maintained conversation
preserve the assistant response
if the signal is tool_use:
    validate every client-tool request and its authorization
    collect one matched result or explicit failure per request
    append the user tool-result message, then request another response
else if the signal is end_turn:
    finish the model turn and check application acceptance criteria
else if the signal is a supported server-tool pause:
    continue the documented server-tool flow
else:
    preserve the observed stop condition and recover or escalate
```

This example does not call a live API. It makes the message identifiers, evidence and expected branches inspectable. A real integration also needs its configured model, supported tool definitions, credentials, failure policy and resource controls.

## Keep invocation choice separate from structural validation

In the supplied tool-use interface, `tool_choice` with `{"type": "auto"}` is the described default. It allows either a tool request or a direct answer. A relevant described capability and a need for information absent from context can justify a request; an already supported answer need not trigger another lookup.

Prompt guidance can change the tendency to use tools. For example, “Use the tools to investigate before responding” encourages investigation; “Use your judgment about whether a tool is needed” permits conservative triggering. If the actual requirement removes that discretion for a turn, use a supported forced `tool_choice` setting. Stronger prose alone does not provide deterministic enforcement, and forcing selection still does not authorize execution.

For a custom definition in an interface supporting strict tools, enabling the applicable `strict: true` setting constrains arguments to the supported schema. That guarantee is about structure. It does not prove that the selected customer is correct, that an operation is timely, that a result is true, or that the actor may perform a write. The glossary's broad wording about JSON does not expand the primary knowledge file's strict-mode conditions.

Consider an invented ticket tool whose schema accepts a string `ticket_id` and an optional string `as_of`. For this teaching example, the caller is authorized for T-17, and the tool's documented convention is to omit `as_of` for current status; a historical lookup requires a supported explicit date. These are example application rules, not built-in API behavior.

| Request | Structural and usage judgment |
| --- | --- |
| `{"ticket_id":"T-17"}` for current status | The arguments match the example convention; the harness still checks authorization and the actual result. |
| `{"ticket_id":"T-99"}` when only T-17 is authorized | A string ID can satisfy the schema while failing authorization. Reject dispatch. |
| `{"ticket_id":"T-17","as_of":"yesterday-ish"}` for a tool accepting only supported explicit dates | A string-only schema can accept the shape while the value violates the example date convention. Ask for a supported date or omit the field when current status was requested. |
| `{"ticket_id":"T-17","as_of":"2026-11-01"}` when the user requested current status | The strings can be valid while the combination answers a different question. Use the documented current-status convention. |

Descriptions and examples should explain these conventions, optional arguments and meaningful combinations. Where possible, encode constraints in the actual validation contract too. Schema conformance alone cannot establish that a validly shaped call is appropriate for the task.

The supplied example for **at most one tool request** uses the following configuration fragment in an interface that supports it:

```json
{"type":"auto","disable_parallel_tool_use":true}
```

This is the value of `tool_choice`, not a complete request. Together the settings allow zero or one requested tool; `auto` can still produce a direct answer. They do not promise exactly one request, one completed operation or task success. A setting valid in this source interface must not be assumed valid in every SDK.

## Make ordering and typed-block checks inspectable

For a preceding client-tool request with ID `call_17`, these two fragments contrast the user-result ordering rule. They are teaching payload fragments, not live API observations.

Incorrect ordering:

```json
{"role":"user","content":[{"type":"text","text":"Here is the result."},{"type":"tool_result","tool_use_id":"call_17","content":"open"}]}
```

Correct ordering:

```json
{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_17","content":"open"},{"type":"text","text":"Explain this status."}]}
```

In the source-described client-tool flow, the first fragment violates the required ordering and can produce a validation error; the second puts the result first. Both still need the preceding assistant request with the matching ID. For several outstanding requests, include every corresponding result before the optional text. Fix a missing, mismatched or misplaced result by checking the actual payload, rather than inventing an unrelated result.

A supported `tool_result` can contain text, images or other supported media. For example, a screenshot returned by a compatible computer-use flow still belongs in its tool-result container with the matching request identity. Non-text content does not become a new message role. Check which media the actual interface accepts.

When continuing the conversation, retain the relevant supported tool definitions on the subsequent API request so the model can request them again. Where the environment supports discovery, load capabilities on demand for the current task. Loading fewer relevant definitions saves context; it does not make an unavailable tool callable on a later turn.

Inspect content blocks by their actual types. A list may contain text, tool requests or supported non-text content. Collect all client `tool_use` blocks when the signal requires client tools. Handle an absent expected block explicitly: a bare `next(...)` without a fallback can raise an exception when nothing matches. Likewise, finding a text block only retrieves text; it does not prove that the answer used the evidence correctly or that the requested task succeeded.

An unexpected stop such as `max_tokens` should preserve the actual reason and useful diagnostics, including completed calls and unresolved work. Do not turn truncated output into an accepted final answer. A supported server `pause_turn` instead preserves the assistant response and makes the documented continuation request; it does not ask the application to fabricate local client-tool results.

## Provide enough context without retaining every raw observation

A hybrid can place stable project instructions in context up front and allow additional exploration just in time. In the supplied example, `CLAUDE.md` is an instruction **file**, not the name of the reasoning model. The harness supplies that context, while the model can search or read further task-relevant files when needed. A fixed workflow can instead retain intermediate state externally and inject the particular input required for each step.

Across separate sessions, do not assume that discoveries in an earlier conversation automatically become available. Persist relevant checked summaries and evidence locations, then explicitly reinject what the new session needs. Preserve request/result relationships required by the protocol when managing history. Prefix caching reduces repeated processing of reusable context; it neither increases the physical window nor replaces this continuity work.

Repeated identical calls or repeated exhaustion of a turn limit warrant investigation. Inspect whether the last result was missing, malformed, stale, ambiguous or insufficient for the acceptance question. Check that the model actually received it and that the tools describe meaningful next steps. Correct the identified feedback or progress problem, preserve any blocker and seek the permitted next action. Raising a cap without that diagnosis can prolong the same failure.

## Preserve user control and delegated capability boundaries

A loop remains responsive to interruption and new user steering. An application can check cancellation or new input between iterations, preserve completed work and pending outcomes, then follow the updated permitted scope. It must not continue canceled writes or label unexecuted work completed. A checkpoint is useful when the next action depends on missing user information or authorization.

Delegating a role should narrow executable capabilities. In an invented read-only inspection, a worker may read the designated repository files but has neither write nor network capability. Telling a worker to avoid edits while leaving an unrestricted write tool available does not enforce that boundary. Child access must stay within the parent's permitted delegation and the worker's actual role.

A coordinator also needs structured outcomes. For example, a read-only worker might return:

```json
{"status":"blocked","artifact":"inspection-note-17","checks_completed":["read permitted configuration"],"unresolved":["required log was not provided"],"writes_performed":false}
```

This invented handoff is not task success. The coordinator checks the referenced output and unresolved dependency before deciding whether to continue or request the missing input. A worker's sentence “Done” cannot replace those checks. Asynchronous handoffs can support durable recovery when a step outlasts a caller's waiting period; their value depends on the coordination requirements, rather than a blanket ban on synchronous workflows.

## Apply hook and streaming safeguards at the correct time

For the source-described fine-grained streaming mechanism, enable request streaming and the applicable user-defined tool's supported `eager_input_streaming` setting. Confirm support in the actual interface. Even with those options enabled, streamed JSON remains partial input until the full object arrives and validates. Only then may the harness make the authorized dispatch decision.

The supplied knowledge snapshot also describes a specific **Stop-hook** safeguard. It states that eight consecutive blocks **without progress** can cause the harness to override further blocking. In that described script flow, check `stop_hook_active` in the hook's JSON input and exit early when it is true to avoid unproductive recursive blocking. The snapshot names `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP` for an explicit cap override. A changed setting is a configuration choice, not the unchanged source-described cap.

Those exact names and the eight-block value are claims in the supplied local snapshot; the original referenced hook attachment and current product behavior were not independently verified here. Apply them only after checking the supported deployed harness. Reaching a no-progress safeguard is diagnostic evidence of interruption, not evidence that the business task passed. Inspect hook recursion and progress before changing the cap.

`stop_reason` is response metadata from the applicable API. **MCP** means **Model Context Protocol**, a tool integration protocol; optional MCP integration is not the origin of every API stop signal. Read the actual response and follow the interface's supported continuation rules.

## Verify the integration and retain the limits of the evidence

Treat returned external data as potentially adversarial throughout operation. In addition to keeping it in the result container, validate relevant content, maintain configured guardrails and monitor logs for unexpected requests or behavior after new external material is ingested. Encapsulation does not make injection impossible.

For an actual integration, use bounded checks in an appropriate sandbox with inspectable tool contracts. Useful checks include a correct request/result pair, an unmatched ID, a missing result among parallel calls, a failed lookup, a missing expected block, an interrupted response, a resource limit and the supported server-pause continuation. Check both the observed protocol branch and the task outcome; expected output alone is not a test pass.

The JSON and control-flow examples in this topic are illustrative and statically inspectable. They do not report a live Claude API, SDK, hook or MCP execution. The lesson uses the supplied local knowledge files; original anchor attachments and current external product behavior have not been independently checked. Keep these evidence limits when applying version-sensitive options.

## Summary

A reliable loop combines model-selected actions with harness-enforced execution. Preserve complete request/result pairs, branch on explicit protocol signals and use actual observations to guide continuation. Resource limits control exposure; they do not certify completion, and a finished model turn still needs the application's acceptance check.
