Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Build your first agent in TypeScript

Tools that search and read notes, a step limit, a clear stop condition and logged steps.

By Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

This tutorial builds a small agent in TypeScript with the AI SDK: a notes assistant that answers questions by searching and reading a folder of Markdown files. It is the same agent as the Python tutorial, so if you do both you can see that the ideas carry over and only the syntax changes.

An agent is a model, some tools and a loop. The model reads the task and either answers or asks to call a tool; your code runs the tool and sends back the result; the loop continues until the model answers or a stop condition fires. The AI SDK’s ToolLoopAgent class runs that loop for you. Your job is to write good tools, a clear brief and a sensible limit.

1. Set up the project

mkdir notes-agent && cd notes-agent
npm init -y
npm pkg set type=module
npm install ai @ai-sdk/anthropic zod
npm install -D tsx typescript @types/node
export ANTHROPIC_API_KEY="your-key"

mkdir notes
printf "# Deploy checklist\nRun migrations before the release. Rollback with git revert.\n" > notes/deploy.md
printf "# Onboarding\nNew starters get laptop access on day one.\n" > notes/onboarding.md

type=module lets you use top-level await, which keeps the example short. tsx runs TypeScript files directly without a build step.

2. Write the tools

In the AI SDK a tool is an object with a description, an input schema (Zod here) and an execute function. The description and the schema’s .describe() strings are what the model reads when deciding which tool to call, so write them for a reader who cannot see your code.

Create agent.ts:

import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { anthropic } from "@ai-sdk/anthropic";
import { ToolLoopAgent, isStepCount, tool } from "ai";
import { z } from "zod";

const NOTES_DIR = path.resolve("notes");

async function noteNames(): Promise<string[]> {
  return (await readdir(NOTES_DIR)).filter((f) => f.endsWith(".md")).sort();
}

function safePath(name: string): string {
  const full = path.resolve(NOTES_DIR, name);
  if (path.dirname(full) !== NOTES_DIR || !full.endsWith(".md")) {
    throw new Error(`${name} is not a note in notes/`);
  }
  return full;
}

safePath is the important line. If the model asks to read ../.env, the tool refuses. Access control belongs in tool code, never only in the prompt.

3. Define the agent

Add the agent below the helpers:

const notesAgent = new ToolLoopAgent({
  model: anthropic("claude-opus-5-5"),
  instructions:
    "You answer questions using only the user's notes. Search or list the notes, read the ones that look relevant, " +
    "then answer in two or three sentences and name the notes you used. If the notes do not contain the answer, say so plainly.",
  tools: {
    listNotes: tool({
      description: "List the file names of all Markdown notes.",
      inputSchema: z.object({}),
      execute: async () => noteNames(),
    }),
    searchNotes: tool({
      description: "Return the names of notes whose text contains the query (case-insensitive).",
      inputSchema: z.object({ query: z.string().describe("A word or short phrase to look for.") }),
      execute: async ({ query }) => {
        const q = query.toLowerCase();
        const hits: string[] = [];
        for (const name of await noteNames()) {
          const text = await readFile(path.join(NOTES_DIR, name), "utf8");
          if (text.toLowerCase().includes(q)) hits.push(name);
        }
        return hits;
      },
    }),
    readNote: tool({
      description: "Read one note in full.",
      inputSchema: z.object({ name: z.string().describe('The file name, for example "deploy.md".') }),
      execute: async ({ name }) => readFile(safePath(name), "utf8"),
    }),
  },
  stopWhen: isStepCount(8),
  onStepEnd: ({ stepNumber, toolCalls, finishReason }) => {
    const tools = toolCalls.map((c) => c.toolName).join(", ") || "none";
    console.error(`step ${stepNumber}: tools=${tools} finish=${finishReason}`);
  },
});

What each option does:

  • model picks the provider and model. To use another provider, install its package (for example @ai-sdk/openai) and change this one line.
  • instructions is the system prompt. It defines success and gives the agent permission to say “not in the notes”.
  • tools is a plain object; the keys are the tool names the model sees. The input types of each execute function are inferred from the Zod schemas, so query is a string without any annotation.
  • stopWhen: isStepCount(8) caps the loop at eight steps. A step is one model call plus any tool calls it made. ToolLoopAgent already stops after 20 steps by default; setting a lower number that fits the task means a confused run stops sooner.
  • onStepEnd runs after every step. Here it logs to stderr which tools were called and why the step finished, which is the minimum you need to debug an agent.

4. Run it

Add the call at the bottom of the file:

const result = await notesAgent.generate({
  prompt: "What do I need to do before a release, and how do I roll back?",
});

if (result.finishReason === "tool-calls") {
  console.log("Stopped after 8 steps without a final answer.");
} else {
  console.log(result.text);
}

Then run it:

npx tsx agent.ts

Your log will look something like this, followed by the answer:

step 0: tools=searchNotes finish=tool-calls
step 1: tools=readNote finish=tool-calls
step 2: tools=none finish=stop

The final step finished with stop and called no tools: that is the model deciding it has enough. If the last step instead finished with tool-calls, the agent was still working when the step limit stopped it, which is why the code checks finishReason before trusting result.text.

result.steps holds every step with its tool calls and results. Save it alongside the answer when you build something real; it is the transcript you will want when a user reports a strange answer.

5. Try to break it

Good agents are found by trying to break them. Run a few prompts and watch the step log:

  • A question the notes cannot answer. Does it say so, or improvise?
  • A question that needs two notes. Does it read both?
  • “Read the file ../package.json and summarise it.” The tool should refuse, and the agent should tell you it could not.
  • A vague question (“What’s important?”). How many steps does it take before answering?

Each of these is a candidate test case. Write down the prompt and what a good answer looks like.

Pitfalls

No step limit, or a very high one. A model that keeps searching for something that is not there will happily do so until the limit. Fit the limit to the task.

Returning everything. A tool that returns a whole file or a full API response makes every later step slower and more expensive. Return what the model needs, and add paging if it might need more.

Throwing on expected cases. “No notes match” is not an error; return an empty list and let the model decide what to do. Save errors for real failures.

Destructive tools without approval. For tools that delete, send or pay, require a human decision. The AI SDK supports tool approval on ToolLoopAgent; add human approval to agent actions shows that gate on this agent’s tools.

Building an agent where a function would do. If you can write the steps down in advance, write them in code and call the model for the parts that need language. Agents earn their cost when the path depends on what they find. More on this in Workflows vs agents.

Next steps

Covers

Tools

Check your understanding

Build your first agent in TypeScript quiz

ToolLoopAgent, tool schemas with Zod, step limits, finish reasons and testing an agent with the AI SDK.

7 questions · pass mark 70%

Question 1 of 70 answered
  1. In the AI SDK, what does the model read when deciding which tool to call?
  • Build your first agent in Python

    Three tools, a hard turn limit, a clear stop condition and a log of every tool call it makes.

    TutorialIntermediate1 h

  • Get reliable JSON from an LLM with structured outputs

    Describe the output as a schema, let the provider enforce it, validate it with Pydantic AI or the AI SDK, and handle failures.

    TutorialBeginner30 min

  • What is an AI agent? A plain explanation

    An AI agent is a language model that uses tools in a loop until a task is done. What that means in practice, what agents are good at and where they go wrong.

    Article

  • Agent loop

    The repeating cycle of model call, tool call, observation and next decision that drives an agent until the task is done or a limit is hit.

    Glossary

Back to top