Search IOCombats

Search challenges, guides, questions and articles

Tool Calling in TypeScript: How an AI Agent Loop Actually Works
aitool callingai agentsvercel ai sdktypescriptzod

Tool Calling in TypeScript: How an AI Agent Loop Actually Works

By Ghazi Khan | Nov 23, 2026 - 10 min read

You add a tools object to generateText, ask "find me React jobs in Pune", and get back an empty string. The model did call your tool, but nothing called the model again with the result. That gap between "the model asked for a tool" and "the task is done" is the agent loop, and once you understand tool calling in TypeScript at the protocol level, agents stop feeling like magic.

This post explains what a tool call is on the wire, how the loop works, and then builds a small job search agent with AI SDK 7: typed tools, a terminal tool, stop conditions and step logging.

The concept: the model dispatches actions, your code runs them

The model never runs your code. It cannot call fetch, read a file or query your database. What it can do is reply with a structured request: "call searchJobs with { skill: 'react', city: 'Pune' }". Your app runs the function and sends the result back as a new message. The model reads it and decides what to do next.

If you have used Redux, this should feel familiar. The model is like a component that can only dispatch({ type, payload }). It describes the side effect, it does not perform it. Your app is the middleware that runs the effect and feeds the outcome back into state. A tool is the contract for one action type:

Tool partWhat it doesReact/TS analogy
nameIdentifies the actionAction type
descriptionTells the model when and why to use itJSDoc the model actually reads
inputSchemaJSON Schema for the arguments, generated from ZodProp types, validated at runtime
executeYour function that runs the effectThe thunk or saga

On the wire, every provider follows the same shape. With Anthropic's API, for example, the response comes back with a tool_use stop reason and one or more tool_use blocks, each with an id. You reply with tool_result blocks that reference that id. The AI SDK hides these provider differences behind one API.

Diagram
100%
sequenceDiagram participant App as Your Node app participant LLM as Model participant Tool as searchJobs() App->>LLM: messages + tool definitions (name, description, schema) LLM-->>App: tool call: searchJobs { skill: "react", city: "Pune" }, id: call_1 App->>Tool: execute({ skill, city }) Tool-->>App: [ { id: "j2", title: "...", ... } ] App->>LLM: messages + tool result for call_1 LLM-->>App: final text (no tool calls), so the loop ends
visualized byIOCombats

The agent loop is a while loop

An "agent" is that exchange repeated until the model stops asking for tools. Stripped down, it is this:

// The idea, not production code
while (true) {
  const step = await callModel(messages, tools);
  messages.push(...step.responseMessages); // assistant message with tool calls
  if (step.toolCalls.length === 0) return step.text; // model is done

  const results = await Promise.all(step.toolCalls.map(runTool));
  messages.push(toolResultMessage(results)); // feed results back
  if (tooManySteps()) return 'Stopped: step limit reached';
}

Each pass is called a step: one model call plus the tools it asked for. Two things make this loop safe in production. First, the message history grows on every step, so every earlier tool result is sent again as input on the next call. Second, a model can keep calling tools forever, so you always need an exit besides "the model said it was done".

Diagram
100%
flowchart TD A["Call model with messages and tools"] --> B{"Tool calls in response?"} B -- "No" --> Z["Return final text"] B -- "Yes" --> C["Validate input against schema, run execute()"] C --> D["Append tool results to messages"] D --> E{"Stop condition met?<br/>(step limit, terminal tool, budget)"} E -- "No" --> A E -- "Yes" --> Z2["Return steps so far"]
visualized byIOCombats

In AI SDK 7 you rarely write this loop yourself. generateText and streamText run it when you pass stopWhen, and the ToolLoopAgent class wraps the same loop into a reusable object. The Claude Code case study shows the hand-written version with permission prompts.

Tool calling in TypeScript: build a job search agent

We will build an agent that searches a job list, reads details for promising roles and submits a shortlist of up to three. Set up an ESM project (top-level await needs "type": "module" in package.json):

npm i ai zod
npm i -D tsx typescript

AI SDK 7 needs Node.js 22 or later. The examples use the Vercel AI Gateway, the default provider in AI SDK 7, so put AI_GATEWAY_API_KEY in .env.local. Any provider package works the same way.

First, sample data so the example runs without a database:

// jobs.ts: sample data, replace with your API or DB
export type Job = {
  id: string;
  title: string;
  company: string;
  city: 'Bengaluru' | 'Pune' | 'Hyderabad' | 'Remote';
  skills: string[];
  description: string;
};

export const jobs: Job[] = [
  {
    id: 'j1',
    title: 'Frontend Engineer',
    company: 'Acme Pay',
    city: 'Bengaluru',
    skills: ['react', 'typescript', 'nextjs'],
    description: 'Own the checkout UI and its tests.',
  },
  {
    id: 'j2',
    title: 'React Developer',
    company: 'Shiplog',
    city: 'Pune',
    skills: ['react', 'redux', 'javascript'],
    description: 'Build dashboards for logistics teams.',
  },
  {
    id: 'j3',
    title: 'UI Engineer',
    company: 'Notewise',
    city: 'Remote',
    skills: ['react', 'typescript', 'css'],
    description: 'Design system and editor components.',
  },
];

Now the tools. Notice what the descriptions say: when to use the tool, what it returns and what to do next. They are the only documentation the model gets.

// tools.ts
import { tool } from 'ai';
import { z } from 'zod';
import { jobs, type Job } from './jobs';

const summary = ({ id, title, company, city }: Job) => ({
  id,
  title,
  company,
  city,
});

export const tools = {
  searchJobs: tool({
    description:
      'Search open frontend jobs by one skill. Returns up to 5 summaries (id, title, company, city). ' +
      'Use getJobDetails to read a job before recommending it.',
    inputSchema: z.object({
      skill: z.string().describe('One lowercase skill, for example "react"'),
      city: z
        .enum(['Bengaluru', 'Pune', 'Hyderabad', 'Remote'])
        .nullable()
        .describe('null means any city'),
    }),
    execute: async ({ skill, city }) => {
      const matches = jobs
        .filter(
          (j) =>
            j.skills.includes(skill.toLowerCase()) &&
            (!city || j.city === city),
        )
        .slice(0, 5)
        .map(summary);
      return matches.length
        ? matches
        : 'No matches. Try a related skill or set city to null.';
    },
  }),
  getJobDetails: tool({
    description:
      'Get the full description and skills for one job id returned by searchJobs.',
    inputSchema: z.object({ id: z.string() }),
    execute: async ({ id }) =>
      jobs.find((j) => j.id === id) ??
      `No job with id "${id}". Use an id from searchJobs.`,
  }),
  submitShortlist: tool({
    description:
      'Call exactly once, as the last action, with the final shortlist.',
    inputSchema: z.object({
      picks: z.array(z.object({ id: z.string(), reason: z.string() })).max(3),
    }),
    execute: async ({ picks }) => ({ saved: picks.length }), // write to your DB here
  }),
};

Two design choices matter here. Expected failures (no matches, unknown id) are returned as plain results that tell the model how to recover, instead of thrown errors. And submitShortlist is a terminal tool: its input is the structured final answer, which is more reliable than parsing free text.

Next, the agent. The stop conditions are an array, and the loop stops when any of them is true:

// agent.ts
import { ToolLoopAgent, hasToolCall, isStepCount } from 'ai';
import { tools } from './tools';

export const jobAgent = new ToolLoopAgent({
  model: 'anthropic/claude-sonnet-5.5',
  instructions: [
    'You help frontend developers in India find jobs on a job board.',
    'Search first, read details for promising jobs, then call submitShortlist once.',
    'Only use job ids returned by searchJobs. Never invent ids.',
  ].join('\n'),
  tools,
  stopWhen: [hasToolCall('submitShortlist'), isStepCount(8)],
  onStepEnd({ stepNumber, finishReason, toolCalls }) {
    const calls = toolCalls.map(
      (c) => `${c.toolName}(${JSON.stringify(c.input)})`,
    );
    console.log(
      `step ${stepNumber} [${finishReason}]`,
      calls.join(', ') || 'text only',
    );
  },
});

Finally, run it and read the shortlist from the terminal tool call:

// run.ts
import { jobAgent } from './agent';

const prompt =
  process.argv.slice(2).join(' ') ||
  'React and TypeScript roles in Bengaluru or remote';
const result = await jobAgent.generate({ prompt });

const final = result.steps
  .at(-1)
  ?.toolCalls.find((c) => c.toolName === 'submitShortlist');

if (final) console.log('Shortlist:', JSON.stringify(final.input, null, 2));
else
  console.log(`No shortlist after ${result.steps.length} steps:`, result.text);

Run it with node --env-file=.env.local --import tsx run.ts. The onStepEnd log shows the loop working: a search step, a details step (often with several getJobDetails calls in one step, which the SDK runs concurrently by default), then the submitShortlist step that triggers hasToolCall and ends the run.

Every way the loop can end

How it endsWhat triggers itUse it for
Natural finishModel replies without tool callsChat-style answers
isStepCount(n)n steps have run (ToolLoopAgent defaults to 20)A hard safety cap, always
hasToolCall('name')A step called that toolTerminal tools with a structured answer
Custom StopConditionYour function over steps returns trueToken budgets, "found the answer" checks
Tool with no executeModel calls a tool you run elsewhereClient-side tools in useChat
toolApproval: 'user-approval'A gated tool was calledHuman-in-the-loop actions

Common mistakes

  1. Passing tools without a loop. generateText and streamText default to isStepCount(1), so the model calls a tool, your execute runs, and the call returns with no final text. Fix: set stopWhen, or use ToolLoopAgent.
  2. Vague names and descriptions. getData with "gets data" forces the model to guess. Fix: say when to use the tool, what it returns and any limits, and add .describe() to each field. Use .nullable() instead of .optional() for strict providers, as covered in last week's post on structured output with Zod.
  3. Throwing for expected cases. The SDK does catch errors thrown in execute and sends them back as tool-error results, but the model only sees your error message. Fix: return a result that explains how to recover ("use an id from searchJobs") and keep throw for real bugs.
  4. Returning huge payloads. Every tool result stays in the history and is sent again on every later step, so a 200-row result costs you on each call. Fix: return summaries plus a details tool, paginate, and use prepareStep with pruneMessages for long runs.
  5. Letting side effects run unattended. A model can call applyToJob as easily as searchJobs. Fix: add toolApproval: { applyToJob: 'user-approval' }. The run then ends with a tool-approval-request, and you continue after the user responds.

Interview angle

Interviewers usually ask you to explain the loop ("what happens after the model returns a tool call?") and then push on safety: how does it stop, what happens when a tool fails, how do you keep a destructive action behind a human? Explain the step, the growing message history, at least two stop conditions and errors as results. Practise with the agents and tools interview questions.

What's next

On Thursday, the case study How Claude Code's Agent Loop Works runs this loop at full scale: a coding agent that reads files, edits code and runs tests, with every tool call passing through a permission gate and a context window that has to survive long sessions. Next week we compare the TypeScript agent frameworks built on top of this loop.

Conclusion

Tool calling is a message protocol: the model asks, your code runs, and the result goes back as the next message. The agent loop is that exchange in a while loop with good exits. Write tools like public APIs, return recoverable errors as data, always cap the steps, and an agent becomes ordinary TypeScript you can test and reason about.

Advertisement

Ready to practice?

Test your skills with our interactive UI challenges and build your portfolio.

Start Coding Challenge