Agents from scratch (TypeScript) · Chapter 2 of 18
Tools as functions
By the end of this chapter you can describe a tool's arguments once, as a zod schema, and get from it the JSON Schema the model reads, the TypeScript type your code uses and a check on what comes back. You can define tools whose code is typed from their schema, keep them in a registry that both describes and runs them, and write descriptions that make the model pick the right tool. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The loop
- 4 tasks
- TypeScript
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
In chapter 1 you wrote a tool description by hand: an object with a name, a sentence and a JSON Schema. GharFix's booking system has eight functions, and Vikram wants the agent to grow: warranty lookups, AC gas checks, invoice copies. Writing every schema by hand means writing everything twice. The function says technician_id: string; the schema says technician_id: { type: 'string' }. Change one, forget the other, and the model is told about a parameter the function no longer takes. Nothing checks the two against each other: to TypeScript, parameters is just an object.
There is a second problem. Meenakshi tried the bot on a test number and it answered "You can cancel for free up to 1 hour before the technician arrives", which is not GharFix's policy, while a perfectly good cancel tool sat in its list. The tool was there. Its description said nothing a customer would say. The model chooses tools by reading them, so a description is not documentation for you: it is the only thing the model knows about your function.
The lesson
Types are gone when the program runs
Python agents often build a tool description from the function itself: Python keeps a function's parameter names, type hints and docstring at run time, and a few lines read them. TypeScript cannot do that, and it is worth seeing why. Here is what Node has of two of GharFix's functions while your program runs:
import { findTechnicians, getQuote } from '../../shared/gharfix.ts';
console.log(findTechnicians.length);
console.log(String(getQuote).split('\n')[0]);
console.log(String(findTechnicians).split('\n')[0]);
1
function getQuote(args ) {
function findTechnicians(args ) {
getQuote(args: { job: string }) became getQuote(args and a row of spaces. Node strips the types before it runs a file: it blanks them out, which is why the spaces are there, and nothing of { job: string } is left. Each function takes one parameter, args; what it holds was only ever known to typecheck. TypeScript's types are checked before the program runs and erased when it does, so there is nothing to read them from, and the model's request arrives while it runs.
So the description has to start from a value: something that exists at run time and says, in data, what the arguments are. That is what a schema library is for. This lab uses zod.
One zod schema, three jobs
Here is a zod schema for reschedule_booking's arguments:
import { z } from 'zod';
const RescheduleArgs = z.strictObject({
booking_id: z.string().describe('The booking ID: GF and 6 digits'),
date: z.string().describe('The new date, YYYY-MM-DD'),
slot: z.enum(['morning', 'afternoon', 'evening']),
});
Job one: the JSON Schema for the model. z.toJSONSchema() writes it:
console.log(JSON.stringify(z.toJSONSchema(RescheduleArgs)));
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"booking_id":{"type":"string","description":"The booking ID: GF and 6 digits"},"date":{"type":"string","description":"The new date, YYYY-MM-DD"},"slot":{"type":"string","enum":["morning","afternoon","evening"]}},"required":["booking_id","date","slot"],"additionalProperties":false}
z.enum([...])becomes anenum: the model is told the only values it may write..describe('...')becomes the property'sdescription, which the model reads to fill it.z.strictObjectbecomesadditionalProperties: false, and every field without.optional()is required.$schemanames the JSON Schema version. A tool'sparametersdoes not need it, and GharFix's ownTOOLSdo not have it, so a tool description built from zod usually leaves it out. (The lab model accepts it either way.)
Put that schema in parameters, and the description and the arguments can no longer drift apart: there is only one of them.
Job two: the type for your code. z.infer gives the TypeScript type of the values the schema accepts, so you write the arguments once and typecheck knows them:
type RescheduleArgs = z.infer<typeof RescheduleArgs>;
const move: RescheduleArgs = { booking_id: 'GF318075', date: '2026-10-25', slot: 'night' };
error TS2322: Type '"night"' is not assignable to type '"afternoon" | "evening" | "morning"'.
(A type and a value may share a name in TypeScript; zod code often does.)
Job three: a check on what comes back. The model's arguments are JSON text, and JSON.parse gives them no type at all. The schema can check them at run time, which a type never can:
const result = RescheduleArgs.safeParse({ booking_id: 'GF318075', date: '2026-10-25', slot: 'night' });
if (!result.success) console.log(z.prettifyError(result.error));
✖ Invalid option: expected one of "morning"|"afternoon"|"evening"
→ at slot
With an extra key, { ..., "slot": "evening", "fee": 0 }, it says ✖ Unrecognized key: "fee". A good object passes, and .parse() returns it typed as RescheduleArgs: after parse, your code knows the arguments' shape, and it is true. That is the only place in an agent where the model's arguments get a type honestly; chapter 7 builds the whole validator on it.
One thing to know: plain z.object writes the same JSON Schema, but its parse quietly drops keys it does not know, where z.strictObject refuses them. z.object({ booking_id: z.string() }).parse({ booking_id: 'GF318075', notes: 'ring twice' }) returns { booking_id: 'GF318075' }, and nobody is told that a note was lost.
Task 1 writes the schema for book_slot, GharFix's biggest tool, and toolSchema, which turns a name, a sentence and a zod object into a tool description, then uses both for a real booking.
defineTool: the type follows the schema
An agent needs four things for every tool: its name, its description, its arguments' schema, and its code. Keep them in one object and they cannot drift apart. A small helper, defineTool, takes those four and adds the fifth thing the API needs, the tool's description built from the schema:
const lookup = defineTool({
name: 'get_booking',
description: 'Look up a booking by its ID.',
args: z.strictObject({ booking_id: z.string() }),
run: (args) => getBooking({ booking_id: args.bookingId }),
});
error TS2551: Property 'bookingId' does not exist on type '{ booking_id: string; }'. Did you mean 'booking_id'?
Nobody wrote a type for run's args. defineTool is generic: its type parameter is the zod object you pass as args, and run's parameter is z.infer of that same type, so typecheck reads the arguments' shape from the schema and catches the misspelt key before anything runs. Writing that signature is task 2.
Two notes:
- Python agents often use a decorator,
@toolabove a function, for this. TypeScript's decorators only decorate classes and their members, not plain functions, so here the tool is a function call instead; it reads just as well. - The
openaipackage has helpers that do something like this for you (zodFunctioninopenai/helpers/zod). Here you write it, so you know exactly what goes to the model.
A registry: describe and run in one place
In chapter 1, the descriptions and the functions were two separate things, TOOLS and FUNCTIONS, kept in step by hand. A registry keeps both: you add a tool once, and it answers the two questions the loop asks. What do I send? The descriptions of every tool, in order. What do I run? Given the name and the arguments text the model wrote, it finds the tool, runs it and returns the result as JSON text, ready for a tool message.
Your own tool is also where you choose what the model sees. GharFix's findTechnicians takes a date and a slot as well; a tool whose schema has only service and area offers the model only those two, and its run passes them on.
Where a registry keeps its tools matters. Here is a short version with a mistake that hides well:
const tools: string[] = [];
class Registry {
add(name: string) {
tools.push(name);
}
schemas() {
return tools;
}
}
const customers = new Registry();
customers.add('get_booking');
const staff = new Registry();
staff.add('request_refund');
console.log(customers.schemas());
[ 'get_booking', 'request_refund' ]
The list sits outside the class, so every registry shares it: the customers' agent is now offered the staff's refund tool. No error, no warning. Keep a registry's tools in a field of the class, so each object has its own (chapter 11 gives each role its own registry, and this is why it must work). Task 3 writes the Registry.
Descriptions steer the model
The model never sees your code. It sees a name, a sentence and the parameters, and picks the tool whose description best matches what the customer wrote. Two tools with lazy descriptions, rates ("Rates.") and people ("People."), and the same two with descriptions written for a reader (temperature: 0):
rates / people
How much does a tap repair cost? -> Most repairs start at ₹199, and AC service is ₹399.
Who can come to Whitefield to fix a leaking pipe? -> Our technician reaches you within 60 minutes of booking, any time of the day.
get_quote: "Get the price of a job from the rate card."
find_technicians: "Find technicians who do a service in an area."
How much does a tap repair cost? -> get_quote({"job":"tap-repair"})
Who can come to Whitefield to fix a leaking pipe? -> find_technicians({"service":"plumbing","area":"Whitefield"})
With lazy descriptions the model found no tool that fit, so it answered from training: both answers are wrong for GharFix (a tap repair is ₹249, and nobody promises 60 minutes). Nothing crashed, which is what makes it dangerous. The lab model matches the words of a description against the customer's message. Real models understand meaning far better, but they fail the same way when two descriptions are vague or alike: they guess. So write descriptions the way you would brief a new colleague:
- Start with a verb and say what the tool does: "Find", "Cancel", "Get the price of".
- Use the customer's words for what it is for: "how much", "price", "who can come".
- Make two tools different: if a person could not tell them apart from the descriptions, neither can a model.
- Describe each parameter: "GF and 6 digits", "YYYY-MM-DD".
Your turn
Task 1 writes BookSlotArgs and toolSchema and books Kavya's door lock change with them. Task 2 is defineTool, whose real test is typecheck; task 3 the registry, with two tools of your own. The interview question hands you two tools whose descriptions say almost nothing, and six customers they fail.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
schema.ts: a tool description from a zod schema
Vikram wants every tool's parameters written once. In schema.ts, export BookSlotArgs, a zod object for book_slot's seven arguments: technician_id, date, slot, job, area, customer_name and phone, all text and all required. slot may only be morning, afternoon or evening; give every field a description; and refuse keys the schema does not have.
Also export toolSchema(name, description, args). It returns a tool description in the shape of one item of TOOLS: type function, and a function with that name, that description, and as its parameters the JSON Schema of the zod object args, without the $schema key zod adds. The check compares toolSchema('book_slot', ..., BookSlotArgs) with TOOLS' own book_slot, then runs toolSchema on zod objects of its own.
When the file is run (node schema.ts), and only then, send lab-chat a system message saying it is GharFix's booking assistant and that today is 2026-10-22, the user's message, exactly:
Book T29 for a door lock change in Indiranagar on 27 Oct, afternoon. I am Kavya Iyer, phone 9900112233.
and one tool: book_slot made with toolSchema and BookSlotArgs. Parse the call's arguments with BookSlotArgs, book with GharFix's bookSlot and those arguments, and print one line: the new booking's ID, a space, and its status.
- Task 2
define-tool.ts: the type follows the schema
In define-tool.ts, export defineTool(spec). spec is one object with a tool's name, its description (one sentence for the model), args (a zod object for its arguments) and run (the function that does the work). defineTool returns the same object with one more key, schema: the tool's description for the API, made with toolSchema from schema.ts.
The point is the types: run's arguments must be typed from args, so that inside run, a key args does not have is a typecheck error. The check calls defineTool, then type-checks a small file of its own that uses it twice: once reading args.rating (it must pass with no errors) and once reading args.ratting (it must be an error).
Importing define-tool.ts must send nothing to the model.
- Task 3
registry.ts: a registry of tools
In registry.ts, export a class Registry that keeps tools made with defineTool. add(tool) keeps the tool under its name and returns that same tool. schemas() returns the tools' descriptions for the API, in the order they were added. run(name, argumentsJson) parses the arguments text, runs that tool with it, and returns the result as JSON text. Each registry has its own tools: a new Registry is empty.
Export a registry, made with new Registry(), holding two tools made with defineTool: get_quote (args: job) running GharFix's getQuote, and find_technicians (args: service and area only) running GharFix's findTechnicians, each with a description written for the model.
When the file is run (and only then), send lab-chat the same system message as task 1 and the user's message, exactly:
How much is a geyser repair, and who can come to Hebbal?
with registry.schemas() as the tools. Run every call the model asks for with registry.run, send the results back, and print only the text of the model's final answer.
- Task 4 · interview question
Interview: pick-right.ts, two tools the model confuses
pick-right.ts offers lab-chat two tools, gf_lookup (it will run GharFix's getBooking) and gf_close (it will run GharFix's cancelBooking), and prints which tool the model picks for each of six customer messages. Their descriptions say almost nothing, and the model gets five of the six wrong: it picks the wrong tool, or answers from its training.
Rewrite the two tools' descriptions (and their parameter's description) so that lab-chat picks gf_lookup for the three questions about a booking's status, and gf_close for the three cancellations. Keep the names, the one required parameter booking_id, the six messages and what the program prints.
What you will learn
- Why a TypeScript type cannot become a tool description, and what can.
- One zod schema, three jobs: the JSON Schema for the model, the type for your code, and a check on the model's arguments.
- defineTool: a tool whose code is typed from its schema.
- A registry: one object that knows each tool's description and runs it by name.
- Descriptions that steer the model to the right tool.
More in The loop
Build "Tools as functions" yourself
GharFix, a Bengaluru home-services company, needs an assistant that books, reschedules and refunds safely. You build it in TypeScript. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.