02 est. 35 min

Your first agent in 30 minutes

Module 02 · est. 35 min · You’ll build: a real, running agent that does one job in your business — triggered, model-driven, taking an actual action — by copying my starter repo.

TL;DR: You’re going to ship a working agent today by cloning a repo, dropping in an API key, writing one prompt file, and running one command. No framework, no Python, no vector database. The whole thing is one TypeScript file that runs the loop, a prompt that tells Claude what to do, and two tools that let it act. Thirty minutes from git clone to “it actually did the thing.”

[Operator’s read] Every agent I run started exactly like this — small, ugly, and working. I didn’t architect them. I copied the last one, changed the prompt, swapped a tool, and shipped. This module is me handing you the “last one” so you can start at copy-paste instead of blank-page.


What we’re building

The agent from your Module 01 lab. If you skipped the lab, do it now — you need one yes/yes task (real action, runs unattended). For this walkthrough I’ll use a simple, universal one so you can follow exactly: a “daily digest” agent that reads a source (your calendar, a feed, a file), has Claude summarize what matters, and emails or Slacks it to you every morning. It’s the skeleton of my actual morning-brief agent. Once you can build this, you can build anything in the course — they’re all this shape with different organs.

You’ll build it the first way from Module 01: your own loop on the Messages API. Near the end you’ll see the same agent with the SDK running the loop for you, so you can compare the two side by side.

Step 0 — What you need (5 minutes)

  • Node 22+ and git. Check: node -v and git --version.
  • An Anthropic API key. Go to platform.claude.com/settings/keys, create a key, and put $5 of credit on the account.
  • Claude Code installed (optional but recommended): curl -fsSL https://claude.ai/install.sh | bash on macOS or Linux. We’ll use it as our cockpit.

What a run costs, so the $5 makes sense: a digest run is about three model calls. Call it 6,000 input tokens and 1,500 output tokens in total (thinking included). On claude-opus-5-5 at $4 in / $20 out per million tokens, that’s $0.024 + $0.03 ≈ $0.05 a run, or about $1.60 a month at one run a day. The same run on claude-haiku-5-5 ($0.10 / $0.50) is about $0.0014. Those token counts are an estimate for a small source file; Module 06 shows you how to log the real ones.

That’s the entire toolchain. No Docker, no Python virtualenv, no cloud account yet.

Step 1 — Copy the repo

bash
git clone https://github.com/alerioja/agent-starter.git my-first-agent
cd my-first-agent
npm install
cp .env.example .env

Open .env and paste your key:

code
ANTHROPIC_API_KEY=sk-ant-...

The repo is deliberately tiny. Here’s the whole structure:

code
my-first-agent/
  .env
  package.json
  source.txt              ← fake input to start with
  src/
    run.ts                ← the loop. you barely touch this.
    prompt.md             ← the agent's job description. you OWN this.
    tools.ts              ← the things the agent can DO. you add to this.
    run-with-runner.ts    ← the same agent, with the SDK running the loop
  README.md

Three files matter. run.ts is the engine — copy it forever, rarely edit it. prompt.md is where the agent’s brain lives. tools.ts is its hands. That split is the whole philosophy: the loop is boilerplate, the prompt is the product, the tools are the leverage.

Step 2 — Understand the loop (don’t skip this)

Here’s src/run.ts, the entire engine. Read every line once so the magic stops being magic:

typescript
import Anthropic from '@anthropic-ai/sdk';
import { readFileSync } from 'fs';
import { tools, runTool } from './tools';

const client = new Anthropic(); // reads ANTHROPIC_API_KEY from env
const systemPrompt = readFileSync('./src/prompt.md', 'utf-8');

async function main() {
  const messages: Anthropic.MessageParam[] = [{ role: 'user', content: 'Run your job now.' }];

  // The agent loop: keep going until the model says it's finished.
  while (true) {
    const res = await client.messages.create({
      model: 'claude-opus-5-5',
      max_tokens: 16000,
      output_config: { effort: 'medium' }, // the depth-vs-cost dial (Module 05)
      cache_control: { type: 'ephemeral' }, // cache the repeated prefix (Module 06)
      system: systemPrompt,
      tools, // what the agent is allowed to DO
      messages,
    });

    // Keep the model's whole turn in the history: text, thinking and tool calls.
    messages.push({ role: 'assistant', content: res.content });

    // Always check WHY the model stopped before you read what it said.
    switch (res.stop_reason) {
      case 'tool_use': {
        // Run every tool it asked for, then send ALL the results back in ONE message.
        const toolUses = res.content.filter((c) => c.type === 'tool_use');
        const results = await Promise.all(
          toolUses.map(async (t): Promise<Anthropic.ToolResultBlockParam> => {
            try {
              return {
                type: 'tool_result',
                tool_use_id: t.id,
                content: await runTool(t.name, t.input),
              };
            } catch (err) {
              // A failed tool is a message to the model, not a crash.
              return {
                type: 'tool_result',
                tool_use_id: t.id,
                content: String(err),
                is_error: true,
              };
            }
          }),
        );
        messages.push({ role: 'user', content: results });
        continue;
      }

      case 'pause_turn':
        // A long server-side step paused. Sending the turn back resumes it.
        continue;

      case 'end_turn': {
        // Done. Print its final word.
        const text = res.content.find((c) => c.type === 'text');
        console.log(text?.text ?? '(done)');
        return;
      }

      case 'max_tokens':
        throw new Error('Ran out of max_tokens mid-answer. Raise it, or stream (Module 07).');

      case 'refusal':
        throw new Error(
          `The model declined this run (category: ${res.stop_details?.category ?? 'none'}).`,
        );

      default:
        throw new Error(`Unexpected stop_reason: ${res.stop_reason}`);
    }
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1); // fail loudly, so a scheduler marks the run red
});

That’s an agent loop. Trigger (you run the file), context + decide (the model reads its prompt and the conversation), act (it calls tools), check (results go back in), repeat (the while loop) until done. Six details in it are the difference between a loop that works in a demo and one that survives a year of 6am runs:

  • It checks stop_reason before reading anything. The model tells you why it stopped. tool_use means “run these and come back.” end_turn means finished. max_tokens means it ran out of room mid-answer, and that half-answer should never ship. refusal means the model declined, and stop_details.category says why. pause_turn only shows up with Anthropic’s server-side tools (Module 04): you send the turn back and it picks up where it left off. Older tutorials only checked “were there tool calls?” and treated everything else as success. That’s how a truncated digest gets sent.
  • All tool results go back in one message. The model can ask for several tools at once. Run them, then return every tool_result together. Splitting them across messages teaches the model to stop asking for tools in parallel.
  • A failed tool becomes is_error: true, not a crash. If Slack is down, the model gets told so and can retry or report it. Module 04 builds on this.
  • max_tokens: 16000. That’s room for the model’s thinking plus the answer. A low cap truncates mid-thought. Past this size, stream the response (Module 07).
  • output_config: { effort: 'medium' } is the dial for how hard the model thinks. Current models decide on their own how much to reason; effort sets how much they’re allowed to spend doing it. Module 05 covers when to turn it up or down.
  • cache_control tells the API to cache the part of the request that repeats on every turn: the tools, the prompt, the conversation so far. On a prompt this small it may not kick in yet. Module 06 shows when it starts saving real money.

Notice what isn’t in there: no temperature, no thinking budget, no pre-filled start to the answer. Older tutorials have all three, and current models reject each of them with an error. If you copy agent code off a 2024 blog post, that’s the first thing that breaks.

Everything else in this course is a more sophisticated version of these lines. Stare at it until it’s obvious. It will pay off in every later module.

Step 3 — Give it hands (tools.ts)

A model with no tools can only talk. Tools are what make it an agent. Here’s src/tools.ts with two tools — one to read a source, one to send the result:

typescript
import Anthropic from '@anthropic-ai/sdk';
import { readFileSync } from 'fs';

export const tools: Anthropic.Tool[] = [
  {
    name: 'read_source',
    description:
      "Read today's raw input the agent should summarize. Returns plain text, which may be empty.",
    strict: true, // the API guarantees the model's input matches the schema
    input_schema: { type: 'object', properties: {}, required: [], additionalProperties: false },
  },
  {
    name: 'send_digest',
    description:
      'Send the finished digest to the operator. Call it once, after the digest is written.',
    strict: true,
    input_schema: {
      type: 'object',
      properties: {
        subject: { type: 'string', description: 'Short subject line' },
        body: { type: 'string', description: 'The digest, in plain text' },
      },
      required: ['subject', 'body'],
      additionalProperties: false,
    },
  },
];

// Return a string the model will read. Throw when something fails: run.ts
// turns the error into a tool_result with is_error: true so the model can adapt.
export async function runTool(name: string, input: unknown): Promise<string> {
  switch (name) {
    case 'read_source':
      // Swap this for your real source: a calendar API, an RSS feed, a DB query.
      // To start, just read a local file you drop notes into.
      return readFileSync('./source.txt', 'utf-8');

    case 'send_digest': {
      const { subject, body } = input as { subject: string; body: string }; // strict: true guarantees this shape
      // Start by printing. Swap for real email/Slack once it works on screen.
      console.log(`\n=== ${subject} ===\n${body}\n`);
      return 'Digest sent successfully.';
    }

    default:
      throw new Error(`Unknown tool: ${name}`);
  }
}

Two things to see here.

strict: true with additionalProperties: false. This makes the API guarantee the model’s tool input matches your schema exactly: subject and body will be there, they’ll be strings, and nothing extra rides along. You still validate the values (Module 04), but you stop writing defensive code for missing fields.

Start with the action faked. The send_digest tool prints instead of sending. Get the loop working end-to-end, THEN swap in the real integration. This is the single biggest time-saver for beginners. Don’t debug “is my agent thinking right” and “is my Slack webhook configured” at the same time. Get the brain right against fake hands, then bolt on real hands. I still build every new agent this way.

Step 4 — Write the prompt (prompt.md) — this is the real work

The loop and tools are copy-paste. The prompt is where your agent becomes yours. Here’s src/prompt.md, a production-shaped one. Read the structure, because Module 05 is entirely about why it’s shaped like this:

markdown
You are a daily digest agent for {your name / business}. You run once
every morning on a schedule, and nobody reads your output before it is
delivered. There is no one to answer a clarifying question, so make the
call yourself. If you can't do the job properly, say so in the digest.

## Your job

1. Call read_source to get today's raw input.
2. Pull out what matters to the operator and cut the filler.
3. Write a short digest: 3-6 bullets, plain language, most important first.
4. Call send_digest once, with a clear subject and the digest as the body.

## Rules

- If read_source returns nothing useful, send a digest that says so. An
  empty day is a valid result; don't fill it with invented items.
- Only include what the source supports. The operator acts on this digest,
  so a plausible guess does more damage than a gap.
- Lead with the single most important item. The operator may only read line one.
- Plain text, because it lands in a chat message. No markdown headers and no
  opening line like "Here's your digest."

## Done means

You have called send_digest once. Then stop, and reply with one line saying
what you sent.

Look at what that prompt does that a ChatGPT prompt doesn’t:

  • It tells the agent it’s running unattended. The model stops asking clarifying questions nobody will answer and makes the call itself.
  • It defines “done” explicitly. Agents loop. Without a clear stop condition they ramble or re-run tools. “You have called send_digest once” is a hard finish line.
  • It handles the empty case (“an empty day is a valid result”). This one line prevents the #1 production failure: the agent inventing content because it assumes there must be some.
  • It forbids invention, and says why. “The operator acts on this digest, so a plausible guess does more damage than a gap.” Current models follow instructions literally and do better when they know the reason. You’ll write a version of this clause into every agent you ship.

Notice there are no ALL-CAPS warnings and no “you MUST.” Prompts written for 2023 models were full of them. On current models they make the agent over-cautious. Module 05 explains why.

Step 5 — Run it

source.txt already has a few lines in it (pretend they’re today’s calendar). Run:

bash
npm start

You should watch the agent call read_source, think, then call send_digest, and print your digest. That’s a complete agent. It triggered, gathered context, decided what mattered, took an action, and stopped.

Run it again with source.txt empty. Watch it say “nothing notable today” instead of inventing events. That’s the difference between a demo and a production agent, and you just built it on try one.

Step 6 — Make it real (the 5-minute swap)

Now swap the fakes for reality, one at a time:

Real source. Replace the read_source case with an actual fetch. Reading a feed:

typescript
case 'read_source': {
  const res = await fetch('https://your-source.example/feed.json');
  if (!res.ok) throw new Error(`Feed returned ${res.status}`);
  const data = await res.json();
  return JSON.stringify(data.items?.slice(0, 20) ?? []);
}

Real delivery. Replace the send_digest case with a Slack webhook (free, 2 minutes to set up at api.slack.com → Incoming Webhooks):

typescript
case 'send_digest': {
  const { subject, body } = input as { subject: string; body: string };
  const res = await fetch(process.env.SLACK_WEBHOOK_URL!, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text: `*${subject}*\n${body}` }),
  });
  if (!res.ok) throw new Error(`Slack returned ${res.status}`);
  return 'Posted to Slack.';
}

The throw lines matter. When the feed or Slack fails, run.ts hands the model an is_error result and it can tell you what went wrong instead of claiming success.

Run it once more. Now it reads your real source and posts to your real Slack. You have a production agent. The only thing missing is the trigger — making it run at 6am without you — and that’s Module 07. For now, you’re the trigger, and that’s fine. You shipped.

The shortcut: let the SDK run the loop

Now that you’ve seen the loop, here’s the same agent with the SDK’s Tool Runner doing the looping. It’s src/run-with-runner.ts in the starter:

typescript
import Anthropic from '@anthropic-ai/sdk';
import { betaZodTool } from '@anthropic-ai/sdk/helpers/beta/zod';
import { z } from 'zod';
import { readFileSync } from 'fs';

const client = new Anthropic();
const systemPrompt = readFileSync('./src/prompt.md', 'utf-8');

// Same two tools as tools.ts, but each one carries its own `run` function.
const readSource = betaZodTool({
  name: 'read_source',
  description:
    "Read today's raw input the agent should summarize. Returns plain text, which may be empty.",
  inputSchema: z.object({}),
  run: async () => readFileSync('./source.txt', 'utf-8'),
});

const sendDigest = betaZodTool({
  name: 'send_digest',
  description:
    'Send the finished digest to the operator. Call it once, after the digest is written.',
  inputSchema: z.object({
    subject: z.string().describe('Short subject line'),
    body: z.string().describe('The digest, in plain text'),
  }),
  run: async ({ subject, body }) => {
    console.log(`\n=== ${subject} ===\n${body}\n`);
    return 'Digest sent successfully.';
  },
});

async function main() {
  // The SDK runs the loop: call the model, run tools, send results, repeat.
  const final = await client.beta.messages.toolRunner({
    model: 'claude-opus-5-5',
    max_tokens: 16000,
    max_iterations: 10, // the loop cap from Module 06, built in
    output_config: { effort: 'medium' },
    system: systemPrompt,
    tools: [readSource, sendDigest],
    messages: [{ role: 'user', content: 'Run your job now.' }],
  });

  // You still check why it stopped.
  if (final.stop_reason !== 'end_turn') {
    throw new Error(`Run ended early: ${final.stop_reason}`);
  }
  const text = final.content.find((c) => c.type === 'text');
  console.log(text?.text ?? '(done)');
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

Run it with npm run start:runner. Same tools, same prompt, same digest. Each tool carries its own run function and a Zod schema, and client.beta.messages.toolRunner handles the call-tools-send-results cycle, including turning a thrown error into an is_error result. You still check stop_reason at the end.

Which one should you use? Learn on run.ts, because when something goes wrong you need to know what the loop is doing. Once you’ve shipped a couple of agents, the Tool Runner is less code to maintain. It’s a beta feature of the SDK, so pin your SDK version and read the changelog before you upgrade. Drop back to the hand-written loop when you need control the runner doesn’t give you.

The other two ways from Module 01, Managed Agents and the Claude Agent SDK, come back in Modules 03 and 07, once you have a reason to want them.

Building it with Claude Code instead

If you’d rather not hand-edit files, this whole thing is faster inside Claude Code or Cowork. Open the repo and just say:

“This is an agent starter. I want it to read my Google Calendar each morning and Slack me a digest of today’s meetings, flagging anything that looks like it needs prep. Wire up the calendar read and the Slack send, keep the loop in run.ts as-is, keep strict: true on the tools, and update prompt.md.”

Claude Code will edit tools.ts and prompt.md for you. That’s the operator’s move — you stay at the level of what the agent should do, and let the copilot handle the typing. I build most new agents this way now: I describe the job to Claude Code, it scaffolds, I review and run. But you should hand-build this first one so you understand what it’s writing.

Hands-on lab

Build your agent — the yes/yes task you spec’d in Module 01. Not my digest example. Yours.

Step 1. Clone the starter again into a fresh folder named for your task (event-promo, review-replies, whatever it is).

Step 2. Rewrite prompt.md for your job. Keep the four production clauses: “you run unattended,” an explicit “done means,” an empty-case handler, and a “never invent” rule with its reason.

Step 3. Define your real tools in tools.ts, with strict: true and additionalProperties: false on each one — but fake the actions first (console.log). Get the loop working against fakes before you touch any real API.

Step 4. Run it until the brain is right. Feed it weird input on purpose — empty source, malformed data — and make sure it fails loudly instead of hallucinating.

Step 5. Swap one fake for the real thing (start with the read, it’s safer than the write). Make it throw on failure. Run again.

Deliverable: an agent that, when you run one command, reads something real about your business and produces a correct, useful action — even if that action is still “print it to my terminal.” That’s your first agent. In Module 03 we’ll figure out what shape it should be so it survives contact with the real world.

↵ ↵ to see all results esc esc to close