Tutorial
Build your first agent in TypeScript
Tools that search and read notes, a step limit, a clear stop condition and logged steps.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn 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:
modelpicks the provider and model. To use another provider, install its package (for example@ai-sdk/openai) and change this one line.instructionsis the system prompt. It defines success and gives the agent permission to say “not in the notes”.toolsis a plain object; the keys are the tool names the model sees. The input types of eachexecutefunction are inferred from the Zod schemas, soqueryis astringwithout any annotation.stopWhen: isStepCount(8)caps the loop at eight steps. A step is one model call plus any tool calls it made.ToolLoopAgentalready stops after 20 steps by default; setting a lower number that fits the task means a confused run stops sooner.onStepEndruns 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
- Compare with the Python version built on the OpenAI Agents SDK.
- Return typed data from the agent with structured outputs.
- Make the notes tools available to Claude Code, Cursor and other agents by wrapping them in an MCP server in TypeScript.
- Add code-level human sign-off for mutating tools in Add human approval to agent actions.
- Read Prompt injection basics before you let an agent read web pages or email.
- Get the definitions straight in what is an AI agent?
- When you outgrow one SDK, compare the options in agent frameworks compared.
Covers
- Skills
- 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%
Review
Related
- 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.
- 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.
- 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.
- 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.