Skip to content
Index Ai Academy
Phase 10 · Tools & environment

A tool registry for agents

Schemas from functions, validation, output limits and helpful errors.

About 40 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers10

First principles

Why validate tool arguments before running the registered function?

The schema tells the model and harness which inputs the tool accepts. Validation at dispatch turns malformed input into recoverable feedback before the application performs work.

  1. Starting point

    Model supplies a named tool and arguments

  2. What changes

    Registry matches the tool and checks its input schema

  3. Result

    Valid calls run and output is capped for the model

Compare all three steps
  1. Starting point

    Model supplies a named tool and arguments

  2. What changes

    Registry matches the tool and checks its input schema

  3. Result

    Valid calls run and output is capped for the model

Complete and reverse the trace

Given Model supplies a named tool and arguments and Valid calls run and output is capped for the model, write down the missing step that connects them.

Compare with the worked step

Registry matches the tool and checks its input schema

Now take Registry matches the tool and checks its input schema and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Model supplies a named tool and arguments. Check that your implementation produces the result shown above.

Try it on a new case

A tool expects a numeric limit, but the model passes an object. What should the registry return?

Show worked reasoning

Return a schema error that identifies the limit argument and its expected type. The tool should remain uncalled so the model can correct the request safely.

Run, change, and build

Check this when debugging. Assuming the schema guarantees correct input.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. A tool expects a numeric limit, but the model passes an object. What should the registry return?

Why it matters

Tools are the agent's hands, and the registry is where the harness keeps them. A registry does four jobs: describe each tool to the model, check what the model sends, run the tool, and shape what comes back. Each job has a classic failure. A vague description gets the wrong tool picked. A missing check runs a call with a bad argument. A huge output pushes everything else out of context. This lesson builds a registry that avoids all three.

What you'll be able to do

  • Write tool definitions whose names, descriptions and schemas a model can use well
  • Generate input schemas from Python function signatures
  • Validate tool inputs before running them, with errors the model can act on
  • Cap tool output so one call can't flood the context window
Quick check
A new hire gets a cabinet of labeled drawers and must use only the labels to find things. What decides how well a model uses your tools?
  1. How fast each tool's code runs
  2. The names and descriptions you write for each tool
  3. How many tools there are in total
  4. The programming language the tools are written in
Show the answer

The names and descriptions you write for each tool

A model only sees each tool's name, description and input schema, so those decide when it reaches for a tool and what it sends. The registry also checks inputs, runs the tool and shapes its result.

The idea: a signature becomes a schema, a call becomes a result

Recall: The core loop, built properly answered every tool_use with a tool_result, and Build a server: tools described tools with an inputSchema. The registry is where a harness keeps all of them.

Quick check
From the lesson on the core loop: every tool_use gets a tool_result that carries its id, and all of them go back in the next user message. What does this print?
tool_uses = [{"id": "tu_1", "name": "search"}, {"id": "tu_2", "name": "read"}]

def run_tool(use):
    return {"type": "tool_result", "tool_use_id": use["id"],
            "content": use["name"] + " ok"}

results = [run_tool(use) for use in tool_uses]
print(len(results), [r["tool_use_id"] for r in results])
  1. 1 ['tu_1']
  2. 2 ['tu_2', 'tu_2']
  3. 2 ['tu_1', 'tu_2']
  4. 2 ['search', 'read']
Show the answer

2 ['tu_1', 'tu_2']

The model asked for two tools in one reply, so two results go back, each carrying the id of the request it answers. run_tool here is a stub. The registry in this lesson is what stands behind it: the table that finds the right function for each name and checks its input before it runs.

What the model sees

Picture a new hire handed a cabinet of labeled drawers, who isn't allowed to open any until they've picked one. All they have is the labels. For each tool, the model gets three things: a name, a description and an input schema (JSON Schema). That is all it knows. It never sees your code. So the description must say:

  • what the tool does and when to use it (and when not to);
  • what each parameter means, with formats ("ISO date, like 2026-03-01");
  • what comes back, and any limits ("returns at most 50 lines").

Compare these two:

weakstrong
search: "Searches."search_code: "Find lines matching a regular expression in the project. Use it to find where a name is defined or used. Returns up to 50 matches as path:line: text. Searches only inside the project folder."

Names matter too. Use clear verbs, snake_case, and a prefix when several areas share a word (github_search, wiki_search).

Schemas from functions

Writing JSON Schema by hand for every tool gets tedious and drifts from the code. Most SDKs build it from the function itself: the parameter names, their type hints, which ones have defaults, and the docstring. Python's inspect module gives you all of that.

Try it now

Seven steps. The model sees labels; the registry owns everything else.

Quick check
Which description will help a model choose this tool correctly?
  1. "The best search tool available. Always call this tool first, before any other tool, whatever the user asks for."
  2. "Find lines matching a regex in the project. Use it to locate where a name is defined or used. Returns up to 50 path:line matches."
  3. "grep wrapper v2. Wraps the grep command with extra flags and options; see the source code for full details."
  4. "Searches files. A fast, powerful and flexible search tool that handles all of your project's searching needs."
Show the answer

"Find lines matching a regex in the project. Use it to locate where a name is defined or used. Returns up to 50 path:line matches."

Say what it does, when to use it, and what it returns. The model sees nothing but the name, description and schema.

Quick check
Why validate tool inputs if the model was given the schema?
  1. It isn't needed: the schema guarantees the model's input is always correct
  2. Models sometimes send wrong or missing arguments, and a clear error lets them correct the call
  3. The API refuses to send tool calls back unless the inputs have been validated
  4. Validation makes the model faster, since it can skip checking its own arguments
Show the answer

Models sometimes send wrong or missing arguments, and a clear error lets them correct the call

A schema guides the model but doesn't always bind it. Checking first turns a crash into a helpful message.

In your own words
What does the model know about a tool, and what follows for how you write its description?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: a schema, a validator and a cap

Worked example

A schema from a signature

Type hints become JSON types, and parameters without defaults become required.

import inspect, json

JSON_TYPES = {int: "integer", float: "number", str: "string", bool: "boolean",
              list: "array", dict: "object"}

def schema_for(fn):
    props, required = {}, []
    for name, p in inspect.signature(fn).parameters.items():
        props[name] = {"type": JSON_TYPES[p.annotation]}
        if p.default is inspect.Parameter.empty:
            required.append(name)
    doc = inspect.getdoc(fn) or ""
    return {"name": fn.__name__, "description": doc.split("\n")[0],
            "input_schema": {"type": "object", "properties": props,
                             "required": required}}

def read_file(path: str, offset: int = 0, limit: int = 200):
    """Read lines from a text file in the project, starting at offset."""

print(json.dumps(schema_for(read_file), indent=2))
It runs right here in your browser, with nothing to install.

This is the idea behind decorators like the Python SDK's @beta_tool. Real versions also read per-parameter descriptions from the docstring and handle optional and list types.

Worked example

The error a model would get

Send three calls: one good, one missing a field, one with the wrong type. The validator's message is what the model reads.

def validate(args, schema):
    for name in schema["required"]:
        if name not in args:
            return f"Missing required parameter: {name}"
    for name, value in args.items():
        want = schema["properties"][name]["type"]
        ok = {"integer": int, "string": str}[want]
        if not isinstance(value, ok):
            return f"{name} must be {want}, got {value!r}"
    return None

schema = {"properties": {"path": {"type": "string"}, "offset": {"type": "integer"}},
          "required": ["path"]}
for call in [{"path": "a.py"}, {"offset": 3}, {"path": "a.py", "offset": "ten"}]:
    print(call, "->", validate(call, schema))
In the lesson you can change this and run it.

Errors are messages to the model

When a call is wrong, the error goes back as a tool_result with is_error: true, and the model reads it. So write errors the way you'd write them for a colleague: say what was wrong and what to do instead.

unhelpfulhelpful
KeyError: 'sku'Missing required parameter: sku (the product code, like TENT-2).
Invalid inputParameter limit should be integer, got string "fifty".
File not foundNo file src/util.py. Did you mean src/utils.py? Use glob to list files.

Don't leak internals in errors: no stack traces, secrets or file paths outside the project.

In plain words: an error is the model's only clue about what to try next, so make it a useful clue.

Output budgets

Asking for one fact and getting a whole filing cabinet doesn't help anyone. A tool that returns a 2 MB log would fill the context window in one call. The registry should cap every result, say a few thousand characters, and tell the model it was cut:

...first 4000 characters...
[Output truncated: showing 4000 of 182,311 characters.
Narrow the search or use offset to read more.]

The note matters. It's like a book with pages torn out: without a note saying so, the model thinks it saw everything. Good tools also offer ways to ask for less: offset and limit for reads, a match cap for searches, filters for lists.

Worked example

Keep the head and the tail

A test run can print thousands of lines, and the failure is usually near the end. Cutting from the middle keeps both the start and the part you need.

def cap(text, limit=120):
    if len(text) <= limit:
        return text
    keep = limit // 2
    cut = len(text) - 2 * keep
    return f"{text[:keep]}\n[... {cut} characters cut ...]\n{text[-keep:]}"

log = "\n".join(f"test_{n} passed" for n in range(500))
log += "\ntest_500 FAILED: expected 3, got 4"

print("before:", len(log), "characters")
capped = cap(log)
print(capped)
print("kept the failure:", "FAILED" in capped)
In the lesson you can change this and run it.

Telling the model how much was cut matters too. It can then ask for more, instead of believing it has seen everything. A cap that only keeps the first part would have lost the one line that mattered.

Quick check
What does this print?
output = "x" * 5000
limit = 2000
print(len(output[:limit]))
  1. 5000
  2. 3000
  3. 7000
  4. 2000
Show the answer

2000

output[:limit] keeps the first 2000 characters, so len gives 2000. Capping tool output protects the context window from one huge result.

Drill

Cap output by lines

Write cap_lines(text, max_lines): if the text has more than max_lines lines, keep the first max_lines and add a final line ... (N more lines not shown); otherwise return it unchanged. The note tells the model the output was cut, so it doesn't assume it saw everything.

def cap_lines(text, max_lines):
    return "\n".join(text.splitlines()[:max_lines])


log = "\n".join(f"line {i}" for i in range(1, 8))
print(cap_lines(log, 3))
In the lesson, your code is checked as you write it.

When there are many tools

Every definition costs input tokens on every call, and long tool lists make choosing harder. Keep the set small and task-shaped.

If you need hundreds, think of a book's index: you look something up when you need it, instead of reading every page first. The Claude API's tool search tool lets you mark rarely used tools defer_loading: true. The model then searches for them when it needs them, and only those definitions load. Keep the common tools loaded; deferring everything would hide them all.

Worked example

Searching tools instead of sending them all

Every tool definition is sent on every call. With many tools that's a real cost, so a harness can send a short list and let the model search for the rest.

tools = [{"name": f"tool_{n}", "description": f"Does job number {n} for the shop.",
          "tokens": 300} for n in range(60)]
tools[41] = {"name": "refund_order", "description": "Refund a customer's order.",
             "tokens": 300}

def search(query, tools):
    return [t for t in tools if query in t["description"].lower()]

everything = sum(t["tokens"] for t in tools)
found = search("refund", tools)
print("send all 60:", everything, "tokens on every call")
print("search first:", [t["name"] for t in found],
      "for", sum(t["tokens"] for t in found), "tokens")
In the lesson you can change this and run it.

That's the difference between 18,000 tokens on every turn and a few hundred. A long list also makes the model choose worse, so fewer tools can help quality as well as cost.

Quick check
A tool cut its output at 4,000 characters. Why add a note saying it was cut?
  1. It stops the model from calling the tool again on the same input
  2. The API requires a note on any tool result longer than 4,000 characters
  3. The note makes the output shorter, so it fits in the model's context
  4. Otherwise the model assumes it saw everything and may miss what it needs
Show the answer

Otherwise the model assumes it saw everything and may miss what it needs

The note tells the model to narrow its request or page through the rest.

Drill

An error message the model can act on

Write tool_error(tool, exc): return TOOL failed: TYPE: MESSAGE (the exception's class name and text), followed by Check the arguments and try again. for a ValueError, KeyError or TypeError, or This may be temporary; try once more. for anything else.

def tool_error(tool, exc):
    return str(exc)


print(tool_error("get_campaign", KeyError("cmp_9")))
In the lesson, your code is checked as you write it.
In your own words
Why cap a tool's output, and how?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: real schemas and MCP

A schema is not a guarantee

A form can say "numbers only", and people still write letters in the box. It's easy to assume that if you gave the model a schema, its input will match. Usually it will. But the schema is guidance for the model, and your code must still check what it receives. A model can send a string where you asked for a number, leave out a required field, or invent one you never mentioned. Validate every call before you run it, and send problems back as tool errors. The API's strict mode (strict: true on the tool, with additionalProperties: false in the schema) does make the input match the schema's shape, but it can't check what a schema can't say, such as whether a path exists or is yours to change. So the check stays.

Quick check
Your schema says limit is an integer, and strict mode is off. What must your tool code still do?
  1. Ask the model to confirm each argument in a second request
  2. Nothing: a schema guarantees that the input will always match it
  3. Check the input it receives: the schema is guidance for the model
  4. Convert every input to a string before the tool function runs
Show the answer

Check the input it receives: the schema is guidance for the model

Usually the input matches, and sometimes it doesn't: a string where a number belongs, a missing field. Validate it, and return an error the model can read and fix.

Don't hide what you cut

If a tool's output is truncated with no notice, the model believes it saw everything. It may then say "there are no failing tests" because the failures were on the part you cut. Always say what was removed and how to get more: "showing lines 1 to 200 of 4,180, use offset to read further."

What strict mode does guarantee. With strict: true the API constrains the model so its input matches the schema: right types, every required field, and no extra keys when additionalProperties is false. It still does not guarantee that a path exists, that a value makes sense or that the call is allowed. Those checks stay in your code.

Quick check
You gave the model a schema for a tool's input. What must your code still do?
  1. Send the schema again each turn
  2. Nothing: the input will match
  3. Check every call before running it
  4. Turn every value into a string
Show the answer

Check every call before running it

A schema is guidance for the model. It can still send the wrong type, leave out a field or invent one, so validate and send problems back as tool errors.

One tool per task, not per endpoint

A good office has one help desk, so you don't have to visit three windows to get one answer. Wrapping each API endpoint as a tool is quick, and it's rarely the best design. The model has to learn your API's structure, make several calls to do one thing, and hold all the intermediate data in its context. A single tool built around the task, such as find_order_status(email), does the joining in code, which is cheaper and more reliable. As a rule, if you find the model always calling the same three tools in a row, make them one.

In your own words
What do you do when there are many tools, and why one tool per task rather than one per endpoint?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

What does a model know about a tool?

  1. Its name, description and input schema
  2. Its source code
  3. Its unit tests
  4. Everything in the harness's memory

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write