"Agent" has become one of the most overloaded words in tech. Strip away the marketing and the definition is refreshingly small:

An agent is a model that decides which tools to call, in a loop, until the task is done.

That's it. The model reads the goal, picks an action, sees the result, and picks the next action. Everything hard about agents lives in the details of that loop: which tools exist, what the model can see, and what stops it from doing something expensive or dangerous.

First: do you actually need an agent?

Agents trade predictability for flexibility. Before building one, check that the task is genuinely open-ended (you can't write the steps in advance), valuable enough to justify extra cost and latency, and recoverable — mistakes can be caught by tests, review or rollback.

If you can write the steps down, write a workflow instead: fixed code that calls the model at specific points. Classify → route → draft → check is a workflow, and it'll be cheaper, faster and easier to debug than an agent doing the same thing.

The loop in ~40 lines

Here's a complete agent loop with the Anthropic TypeScript SDK. The model asks for tools; your code runs them and sends the results back; repeat until the model says it's done.

agent.ts
import Anthropic from "@anthropic-ai/sdk";
import { tools, executeTool } from "./tools";

const client = new Anthropic();
const MAX_STEPS = 20; // hard stop, no matter what

export async function runAgent(goal: string) {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: goal }];

  for (let step = 0; step < MAX_STEPS; step++) {
    const res = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      system: "You are an ops assistant. Use tools to investigate before answering. If a tool fails, explain what you tried.",
      tools,
      messages,
    });

    // Always append the full content, not just the text.
    messages.push({ role: "assistant", content: res.content });

    if (res.stop_reason === "end_turn") {
      return res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
    }
    if (res.stop_reason !== "tool_use") {
      throw new Error(`Stopped early: ${res.stop_reason}`);
    }

    // Run every requested tool, then return ALL results in one message.
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of res.content) {
      if (block.type !== "tool_use") continue;
      try {
        const output = await executeTool(block.name, block.input);
        results.push({ type: "tool_result", tool_use_id: block.id, content: output });
      } catch (err) {
        results.push({ type: "tool_result", tool_use_id: block.id, content: String(err), is_error: true });
      }
    }
    messages.push({ role: "user", content: results });
  }
  throw new Error("Step limit reached");
}

Three details in there matter more than they look:

  • Append the full response content, not just the text — tool calls and other blocks must round-trip.
  • Return every tool result in a single message. Models can request several tools at once; splitting the results across messages teaches them to stop doing that.
  • Errors are results, not exceptions. Send failures back with is_error: true so the model can adapt instead of the whole run crashing.

Tools are your agent's API — design them like one

The model only knows what your tool definitions tell it. Vague tools produce vague behaviour. A good definition has a precise name, a description that says when to use it, and a strict schema:

tools.ts
import type Anthropic from "@anthropic-ai/sdk";

export const tools: Anthropic.Tool[] = [
  {
    name: "search_orders",
    description:
      "Find customer orders by email or order ID. Use this before answering any question about an order's status. Returns at most 10 orders, newest first.",
    strict: true, // arguments are guaranteed to match the schema
    input_schema: {
      type: "object",
      properties: {
        email: { type: "string", description: "Customer email, exact match" },
        order_id: { type: "string", description: "Order ID like ORD-12345" },
      },
      required: [],
      additionalProperties: false,
    },
  },
];

export async function executeTool(name: string, input: unknown): Promise<string> {
  switch (name) {
    case "search_orders":
      return JSON.stringify(await db.searchOrders(input as { email?: string; order_id?: string }));
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
}
  • Fewer, sharper tools beat dozens of overlapping ones.
  • Return compact, structured results. Don't dump a 5 MB API response into the context — summarise or paginate.
  • Make errors actionable: "No order found for that email — try the order ID" lets the model recover.
  • Separate read from write. Reading is cheap to get wrong; writing is not.

Guardrails: what stops it going wrong

An agent with tools can do real damage — send emails, delete rows, spend money. Build the brakes before the engine:

  • Step and token budgets — a hard cap on iterations and spend per run.
  • Human approval for side effects — pause before any irreversible action and show the human exactly what will happen.
  • Least privilege — the agent's credentials should only allow what its tools need. Never give it production admin keys.
  • Treat tool output as untrusted — web pages and documents can contain text that tries to give the model instructions. Instructions come from your system prompt and your users, never from data.
  • Log every step — inputs, tool calls, results and tokens. You'll need the trace the first time something surprising happens.

Context: the agent's working memory

Long-running agents accumulate history fast — every tool result stays in the conversation. Plan for it: keep tool outputs small, clear old tool results you no longer need, and for very long tasks use compaction (summarising earlier context) or an external memory the agent can write notes to and read back.

Connecting tools with MCP

Hand-writing a tool for every service gets old. The Model Context Protocol (MCP) is an open standard for exposing tools and data to models: write an MCP server once and any MCP-capable client — including Claude Code — can use it. It's become the default way to plug agents into GitHub, databases, design tools and internal systems.

Build it yourself, or use a harness?

  • Your own loop (like above) — maximum control, you host everything. Great for learning and for narrow, well-defined agents.
  • An SDK tool runner — the SDK runs the loop; you just write tool functions.
  • The Claude Agent SDK — Claude Code's harness as a library, with file editing, shell, search and subagents built in, running on your infrastructure.
  • Managed agents — the provider runs the loop and the sandbox; you configure the agent and start sessions.

Start with your own loop once, so you understand what the frameworks are doing for you. Then pick the highest-level option that still gives you the control you need.

Evaluating agents

Agents need evals even more than single calls do, because errors compound across steps. Score the outcome (was the task actually done?), not just the final message, and track steps, tokens and wall-clock time per run. A run that succeeds in 40 steps when 6 would do is a bug, not a success.

Building effective agents — AnthropicWorkflows vs. agents, and the patterns that work in production.anthropic.comModel Context ProtocolThe open standard for connecting models to tools and data.modelcontextprotocol.ioClaude Developer Platform docsTool use, structured outputs, compaction and the Agent SDK.platform.claude.com

Build the smallest agent that solves a real problem, give it sharp tools and firm brakes, and measure everything. That's the whole craft — the rest is iteration.