Skip to content

Chapter 03 · 16 min read · Updated

Tool Design

A tool's description doubles as a prompt the model reads before acting. Covers granularity, schema discipline, and structured input design.

Prefer one idea per screen? Read it as 18 slides →

Tools are how an agent acts. The set of tools defines what an agent can do; the design of those tools determines whether the model uses them correctly. This chapter is about designing tools and their schemas well, arguably the highest-leverage skill in building agents, because a well-designed tool turns an unreliable model into a reliable system, and a badly-designed one does the opposite.

03.1

What a tool is

A tool is a function the model can call, exposed to it as a schema with three parts:

  • A name: the identifier the model emits to call it.
  • A description: natural-language instructions telling the model what the tool does and when/how to use it.
  • A parameter schema: typically JSON Schema, defining the arguments and their types.

When the model wants to act, it emits a tool call: the name plus arguments matching the schema. Your code runs the corresponding function and returns a result, which the model reads. The description and schema are the entire interface the model has to your capability, so they must teach, not just declare.

03.2

The description is a prompt

The single most important idea in tool design: a tool description is a mini system prompt for that capability. The model decides whether and how to call a tool almost entirely from its description. So descriptions should:

  • State when to use the tool, not just what it does. "Always call this before answering questions about a document" is far more effective than "reads a document."
  • State how to use it well. "Make minimal substitutions of specific words, not whole-line replacements" shapes the model's behaviour decisively.
  • Encode the intended workflow. If tool B should follow tool A, say so in both descriptions ("after searching, call read_X with the id from the results"). The model learns the sequence.

I would say - Time spent sharpening descriptions usually beats time spent tweaking the system prompt, because descriptions are read exactly when the decision is being made, so think wisely here.

03.3

Real code: Gemini CLI's edit tool teaches through its description

Gemini CLI is Google's open-source coding agent for the terminal, and replace is its file-editing tool. Every model except Gemini 3 receives the definition below. Gemini 3 gets the same tool with a shorter description and shorter field descriptions. Other tools in that set are rewritten too, and some of those descriptions are longer. The // [1] markers and the // ... lines inside the quoted text are added here. They are not part of the description the model receives.

replace: {
  name: EDIT_TOOL_NAME,
  description: `Replaces text within a file. By default, the tool expects to find and replace exactly ONE occurrence of \`old_string\`. If you want to replace multiple occurrences of the exact same string, set \`allow_multiple\` to true. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement. // [1]
    // ... (2 lines: the user may edit new_string; a heading)
    1. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.). // [2]
    // ... (3 lines: rules for new_string, instruction, and escaping)
    **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the instance(s) to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations and \`allow_multiple\` is not true, the tool will fail. // [3]
    // ... (2 lines: prefer small atomic calls; how allow_multiple works)
  parametersJsonSchema: {
    type: 'object',
    properties: {
      // ... (4 lines: the file_path parameter)
      [EDIT_PARAM_INSTRUCTION]: { // [4]
        description: `A clear, semantic instruction for the code change, acting as a high-quality prompt for an expert LLM assistant. It must be self-contained and explain the goal of the change.
        // ... (6 lines: answer WHY, WHERE, WHAT, the desired outcome; a GOOD example)
        **BAD Examples:**
        - "Change the text." (Too vague)
        - "Fix the bug." (Doesn't explain the bug or the fix)
        - "Replace the line with this new line." (Brittle, just repeats the other parameters)

Source: google-gemini/gemini-cli, packages/core/src/tools/definitions/model-family-sets/default-legacy.ts (Apache-2.0)

What to notice

  1. [1] Only the first sentence says what the tool does. The rest is usage: one match by default, plenty of context, and "always read the file first". READ_FILE_TOOL_NAME holds the name read_file, so this sentence chains the two tools.
  2. [2] "Exact literal text" is the rule the description gives the model. The matcher still accepts a miss that is only indentation or spacing: calculateFlexibleReplacement compares trimmed lines, and calculateRegexReplacement allows any whitespace between tokens, before a fuzzy pass and before any failure.
  3. [3] The failure rule arrives before the model can trip on it, together with the fix: three lines of context on each side, so the match is unique.
  4. [4] parametersJsonSchema is the JSON Schema for the arguments. The instruction field is a plain-English summary of the change, with its own examples, and it is what the repair model reads. edit.ts calls FixLLMEditWithInstruction only when getErrorReplaceResult still reports an error after exact, trimmed-line, regex, and fuzzy matching: no match, more than one match when allow_multiple is not set, or old and new text that are identical. The call receives the instruction, both strings, the error text, and the current file, then retries with the returned search and replace. It is skipped when LLM correction is disabled, or for a .json, .ipynb, .jsonc, or .json5 file.

A one-line "Replaces text in a file" would leave these rules for the model to learn by failing.

Read it yourself: open model-family-sets/gemini-3.ts and search for replace:. List which rules that description drops. Then read getToolFamily in modelFamilyService.ts to see which models receive which set.

03.4

Granularity: how big should a tool be?

A central design question is tool granularity: too fine and the model drowns in calls; too coarse and it can't express what it needs.

  • Too granular: open_file, read_line, close_file forces the model to orchestrate plumbing. Prefer read_document.
  • Too coarse: a single do_everything tool with a giant polymorphic schema confuses the model about what it can actually do.
  • Right-sized: each tool maps to one meaningful user-level action. "Read a document," "search case law," "generate a document," "edit a document."

A good test: each tool should correspond to a verb a user would recognise. If you can't describe the tool in one clear sentence, it's probably mis-sized (i couldn't find a better word🥲).

03.5

The cheap/expensive pairing- A way to reduce token usage in models :-P

A recurring, valuable pattern: offer a cheap, narrow variant alongside an expensive, broad one, so the model can pick the right cost for the task.

  • "Find this phrase in the document" (cheap, targeted) vs. "read the whole document" (expensive, complete).
  • "Get just the metadata" (cheap) vs. "fetch the full text" (expensive).
  • "List what's available" (cheap discovery) vs. "fetch these N items" (expensive retrieval).

Without the cheap option, the model pays full price for every lookup: more tokens, more latency, more cost. The cheap variant lets it confirm a fact or locate a needle without ingesting a haystack. Give the model economical options and it will often use them.

03.6

Real code: OpenCode's grep returns a small, capped answer

OpenCode is an open-source coding agent written in TypeScript, and it ships both halves of this pairing. Its read tool is the expensive one: a file of 50 KB or less, read with no offset or limit, comes back in one call, and a larger file is paged at 2000 lines or 50 KB, whichever comes first. Its grep tool is the cheap one, and the read tool's own description says so: "use grep to find specific content in large files." Watch how grep keeps its answer small, and how it admits when it cut something.

const limit = input.limit ?? FileSystem.DEFAULT_SEARCH_LIMIT // [1]
const matches = yield* ripgrep
  .grep({
    cwd,
    pattern: input.pattern,
    // ... (4 lines: single file, include glob, literal, case sensitivity)
    limit: limit + 1, // [2]
  })
  // ... (24 lines: timeout, rewrite paths relative to the project)
return { matches: matches.slice(0, limit), truncated: matches.length > limit } // [3]

Source: anomalyco/opencode, packages/core/src/tool/plugin/grep.ts (MIT)

/** Format raw search matches into concise model content. */
export const toModelContent = (matches: EncodedOutput, truncated = false) => {
  const lines = matches.length === 0 ? ["No matches found"] : [`Found ${matches.length} matches`] // [4]
  let current = ""
  for (const match of matches) {
    if (current !== match.entry.path) { // [5]
      if (current) lines.push("")
      current = match.entry.path
      lines.push(`${match.entry.path}:`)
    }
    lines.push(`  Line ${match.line}: ${match.text}`)
  }
  if (truncated)
    lines.push(
      "",
      `(Results are truncated: showing first ${matches.length} results. Consider using a more specific path or pattern.)`, // [6]
    )
  return lines.join("\n")
}

Source: anomalyco/opencode, packages/core/src/tool/plugin/grep.ts (MIT)

What to notice

  1. [1] DEFAULT_SEARCH_LIMIT is 100 (set in filesystem.ts). The model may pass its own limit; if it says nothing, the answer holds at most 100 matching lines. ripgrep is the fast command-line search program running underneath. yield* runs that search and unwraps the matches.
  2. [2] Grep asks ripgrep for one more row than it will show. Ripgrep's reader takes one past that request (Stream.take(input.limit + 1) in ripgrep.ts) and, if the extra row arrived, returns only the requested count. Grep still sees one spare row, slices it off, and sets truncated.
  3. [3] It keeps the first limit rows (100 if the model passed none) and sets truncated when a spare row came back.
  4. [4] toModelContent builds the text the model reads. EncodedOutput is the plain list of matches: each has a path, a line number, and a text preview. Before this function is called, each path is resolved against the project directory, so the model sees absolute paths. The matches value in the return above stays relative. The text leads with the count, and "No matches found" is an explicit answer, not an empty string to interpret.
  5. [5] Matches are grouped under their file path, so each path appears once, and each match is one line: a line number and a preview (ripgrep.ts cuts any preview past 2,000 characters).
  6. [6] When results were cut, the model is told so, and told what to do next.

One grep call costs about one line per match and points at the file and line to read next. A grep that dumped every match in a big repository could cost more than the read it was meant to replace.

Read it yourself: open packages/core/src/tool/plugin/read.ts, the expensive half. Read the tool's description, then find toModelContent near the bottom and answer: what does the model see when a file is longer than one page? Expect a note naming the exact offset to continue from. One notice tells the model where to continue; grep's tells it to search more narrowly.

03.7

Batching

When the model commonly needs N of something, give it a tool that does N at once rather than forcing N separate calls. "Fetch these documents" (a list) beats N× "fetch this document." Batching cuts round-trips, which cuts latency and loop iterations. Cap the batch size in the schema to prevent abuse.

03.8

Real code: pi's edit tool takes many edits in one call

pi is a minimal coding agent written in TypeScript. The edit tool's schema and execution live in edit.ts. The matching rules live next to it in edit-diff.ts. The schema the model sees has no way to send a single replacement except as a list of one. Watch how it decides what each edit is matched against.

const replaceEditSchema = Type.Object(
  {
    oldText: Type.String({
      description:
        "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.", // [1]
    }),
    newText: Type.String({ description: "Replacement text for this targeted edit." }),
  },
  {},
);

const editSchema = Type.Object(
  {
    path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
    edits: Type.Array(replaceEditSchema, { // [2]
      description:
        "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.", // [3]
    }),
  },
  {},
);

export const editToolSystemPromptContribution = {
  snippet: "Make precise file edits with exact text replacement, including multiple disjoint edits in one call",
  guidelines: [
    "Use edit for precise changes (edits[].oldText must match exactly)",
    "When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls", // [4]
    // ... (2 lines: match against the original; keep oldText small)
  ],
} as const;

Source: earendil-works/pi, packages/coding-agent/src/core/tools/edit.ts (MIT)

What to notice

  1. [1] Type.Object and Type.String come from TypeBox, a library that builds JSON Schema from TypeScript code. Each edit is an oldText (the exact text to find) and a newText (what to put there), and the matching rule lives in the field description.
  2. [2] edits is an array, so one call can carry any number of replacements to one file.
  3. [3] Every edit is matched against the original file, so the model never has to predict the file halfway through its own batch. Exact indexOf runs first. A miss is retried after trailing whitespace, smart quotes, Unicode dashes, and special spaces are normalized. Only if that also fails does it throw. Duplicates are counted in that same normalized text, so two regions that differ only by a trailing space count as duplicates. Overlaps are rejected next. Replacements run only after every edit is accepted, and a throw happens before writeFile, so a batch lands completely or not at all. For more than one edit the duplicate error reads Found 2 occurrences of edits[1] in src/app.ts. Each oldText must be unique. Please provide more context to make it unique. (the path, the count, and the 0-based index are examples). A one-edit call uses a shorter sentence that does not say edits[1].
  4. [4] editToolSystemPromptContribution feeds pi's system prompt: buildRules in system-prompt.ts turns each active tool's guidelines into bullet rules. A schema that allows batching does not make the model batch; this guideline tells it when to.

One recommendation from the section is missing: nothing caps the length of edits. Here the file itself bounds the batch, since every oldText must be unique and disjoint within it.

Read it yourself: in edit.ts, scroll to prepareEditArguments. List the four inputs it repairs: a JSON string of an array, a JSON string of one {oldText, newText} object, that object already parsed, and a legacy top-level oldText plus newText appended onto edits. The AgentTool type in packages/agent/src/types.ts says prepareArguments runs before schema validation. Then open edit-diff.ts, find the overlap check, and write two edits that would trigger it. Predict the error message before you read it.

03.9

Schema discipline

The parameter schema is your guardrail against malformed calls. Tighten it:

  • Use enums for fields with a fixed set of values. The model can't send an invalid option.
  • Use bounds (minimum/maximum) for numbers. "Create up to 20 copies," not unbounded.
  • Mark required fields explicitly, and keep optional fields genuinely optional.
  • Describe each field, not just the tool. A field description like "~40 characters immediately preceding the target text, used to disambiguate" teaches the model how to fill it.
  • Keep schemas flat where possible. Deeply nested schemas are harder for models to fill correctly.

A tight schema reduces the rate of malformed calls, which reduces error-recovery loops, which improves latency and reliability.

03.10

Real code: Codex's update_plan schema leaves little to guess

Codex is OpenAI's open-source coding agent, written in Rust. update_plan is the tool the model calls to keep a short checklist for its current task. The schema is small, yet it uses almost every rule from the section above: an enum, required fields, field descriptions, and a ban on extra keys. Watch also for the one rule a schema cannot express. The // [4] inside the description string is added here. It is not part of the text the model receives.

pub fn create_update_plan_tool() -> ToolSpec {
    let plan_item_properties = BTreeMap::from([
        // ... (4 lines: "step", a string described as "Task step text.")
        (
            "status".to_string(),
            JsonSchema::string_enum( // [1]
                vec![json!("pending"), json!("in_progress"), json!("completed")],
                Some("Step status.".to_string()),
            ),
        ),
    ]);
    // ... (7 lines: the top-level properties, starting with an optional "explanation" string)
        (
            "plan".to_string(),
            JsonSchema::array(
                JsonSchema::object(
                    plan_item_properties,
                    Some(vec!["step".to_string(), "status".to_string()]), // [2]
                    Some(false.into()), // [3]
                ),
                Some("The list of steps".to_string()),
            ),
        ),
    ]);
    ToolSpec::Function(ResponsesApiTool {
        name: "update_plan".to_string(),
        description: r#"Updates the task plan.
Provide an optional explanation and a list of plan items, each with a step and status.
At most one step can be in_progress at a time. // [4]
"#
        .to_string(),
        strict: false, // [5]

Source: openai/codex, codex-rs/core/src/tools/handlers/plan_spec.rs (Apache-2.0)

What to notice

  1. [1] JsonSchema::string_enum builds a string field limited to the listed values. json! is a macro from the serde_json crate, the JSON library Rust projects usually use. It writes a JSON value inline. Some wraps an optional value and vec! builds a list. The schema lists exactly three statuses: pending, in_progress, and completed. Because strict is false, a model can still emit "done". Parsing then fails, and the model gets that error back.
  2. [2] ToolSpec::Function and ResponsesApiTool are the structs Codex uses to register one function tool. JsonSchema::object takes three things: the properties, the list of required keys, and whether extra keys are allowed. Every plan item must carry both a step and a status. BTreeMap is Rust's sorted map, so the properties come out in the same order every time.
  3. [3] Some(false.into()) sets additionalProperties to false: no surprise keys such as "priority". A few lines below this excerpt, the top-level object does the same and lists only plan as required, which is how explanation stays optional.
  4. [4] JSON Schema has no simple way to say "at most one item in this array may have this value", so that rule goes in the description. The handler in plan.rs does not check it either; the description is its only guard.
  5. [5] strict asks OpenAI's API to hold the arguments to the schema exactly. The comment on that field in codex-rs/tools/src/responses_api.rs says strict mode needs every property listed in required; explanation is optional, so this tool runs non-strict. Codex validates on its own side: plan.rs parses the arguments into Rust types, and a failure becomes FunctionCallError::RespondToModel("failed to parse function arguments: ..."), an error the model reads and can correct.

Read it yourself: open codex-rs/protocol/src/plan_tool.rs, the same shape as Rust types. For each rule in the hand-written schema, find the line that enforces it during parsing: #[serde(rename_all = "snake_case")] is how InProgress becomes "in_progress", and #[serde(deny_unknown_fields)] mirrors additionalProperties: false. Then open plan.rs and answer two questions: what text does the model get back on success, and what happens if it marks two steps in_progress?

03.11

Structured input for deterministic output

When a tool produces formatted output (a document, a spreadsheet), prefer structured input over free text. Instead of "generate a contract" taking a blob of prose, have it take an array of sections with headings, levels, and tables. Then your code applies the formatting deterministically. This:

  • moves formatting from the unreliable model to reliable code,
  • lets you enforce house style/numbering/branding,
  • and makes the model responsible only for content.

Tell the model what not to do (don't type the numbers, don't repeat the title) because your generator handles those. This division, model decides content, code decides format, is one of the most reliable patterns for producing polished artifacts.

03.12

Tool results are also an interface

The result you return is read by the model, so design it too:

  • Return useful errors, not exceptions. If a tool can't do the thing, return a message the model can act on: "No edits applied; refine your context anchors and retry." The model will adapt. A thrown exception just crashes the turn.
  • Reinforce instructions at the point of use. Returning a document? Prepend a short reminder of how to cite it. Instructions delivered alongside the data are obeyed more reliably than ones only in the system prompt.
  • Distill, don't dump. If a tool calls an external API with a huge response, return the decision-relevant fields and cap long ones, rather than flooding the context. Leave a separate tool for "get more detail" when needed. (See Chapters 5 and 7.)
  • Keep results stable and parseable if your code will read them too.

03.13

Real code: pi's read tool tells the model how to continue

Back to pi. For text, every read result is capped at 2000 lines or 50 KB, whichever comes first. Images skip that cap and are sent as image attachments. A cap alone would leave the model holding half a file with no idea that it is half. Watch how every branch in the excerpt that cuts text ends with a note written for the model.

// Apply truncation, respecting both line and byte limits.
const truncation = truncateHead(selectedContent); // [1]
let outputText: string;
if (truncation.firstLineExceedsLimit) {
  // First line alone exceeds the byte limit. Point the model at a bash fallback.
  const firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], "utf-8"));
  outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`; // [2]
  details = { truncation };
} else if (truncation.truncated) {
  // Truncation occurred. Build an actionable continuation notice.
  const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
  const nextOffset = endLineDisplay + 1;
  outputText = truncation.content;
  if (truncation.truncatedBy === "lines") {
    outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`; // [3]
  } else {
    outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;
  }
  details = { truncation }; // [4]
} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {
  // User-specified limit stopped early, but the file still has more content.
  const remaining = allLines.length - (startLine + userLimitedLines);
  const nextOffset = startLine + userLimitedLines + 1;
  outputText = `${truncation.content}\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`; // [5]
} else {
  // No truncation and no remaining user-limited content.
  outputText = truncation.content;
}
content = [{ type: "text", text: outputText }];

Source: earendil-works/pi, packages/coding-agent/src/core/tools/read.ts (MIT)

What to notice

  1. [1] selectedContent is the file from the requested offset (a 1-based line number) onward, or only limit lines if the model passed one. truncateHead, in truncate.ts, keeps lines from the top until either cap is hit, and never cuts a line in half.
  2. [2] The edge case: one line bigger than 50 KB, such as a minified bundle. Returning nothing would be useless, so the note hands the model a ready-made command for a different tool, bash: sed -n prints that one line and head -c caps it at 50 KB.
  3. [3] The normal cut. Suppose the model reads a 5,000-line file with no offset, and its first 2000 lines fit in 50 KB (made-up numbers). It gets lines 1 to 2000, then [Showing lines 1-2000 of 5000. Use offset=2001 to continue.]. The model does not have to work out the next argument; the note contains it.
  4. [4] details holds the truncation record, which the read renderer shows in the UI. pi's AgentToolResult type sends only content to the model.
  5. [5] Even when the model chose its own limit, it hears how many lines remain and where to resume.

The description says "Use offset/limit for large files." The note does not repeat that sentence. It attaches the next argument to the data, as in Use offset=2001 to continue. A read tool that silently returned the first 2000 lines would let the model reason about a file it has only partly seen.

Read it yourself: in read.ts, find the description string in createReadToolDefinition and match each instruction in it to the branch above that reinforces it. Then open truncate.ts and read truncateTail, the mirror image of truncateHead. Search the repo for where it is called (bash-executor.ts is one place) and work out why command output keeps its last lines instead of its first.

03.14

Scoping tools to the surface

Not every tool belongs in every context. A tool to "list documents in this folder" makes no sense in a chat with no folder. Offer each tool only where it's meaningful. This keeps the model focused on the relevant capabilities and avoids it attempting actions that can't succeed. Compose the active tool set per surface (general chat, project chat, bulk-extraction chat) from a shared base plus surface-specific extras.

03.15

Tools and the provider abstraction

If you support multiple model providers (Chapter 4), define your tools once in a single canonical schema format and convert to each provider's dialect at the boundary. Then adding a tool is purely additive: one schema, one executor branch, and it works across every model. Don't let provider-specific tool formats leak into your tool definitions.

03.16

A checklist for a well-designed tool

  • Does its name map to a recognisable user-level action?
  • Does its description say when and how to use it, not just what it does?
  • Does it chain to related tools where relevant?
  • Is there a cheaper variant for the common case?
  • Can the model batch when it needs many?
  • Is the schema tight (enums, bounds, required, field descriptions)?
  • For formatted output, does it take structured input?
  • Does its result return useful errors and distilled (not dumped) data?
  • Is it offered only on surfaces where it makes sense?

03.17

Read the source yourself

Four stops, in order. Each one shows an idea from this chapter in code the slides above did not quote.

  1. Scoping tools to the surface. Gemini CLI, packages/core/src/tools/tool-registry.ts, method isActiveTool. Find each check that hides a registered tool from the model. Two to look for: the MCP resource tools disappear when no connected server offers resources (MCP, the Model Context Protocol, is a standard way to plug outside tool servers into an agent), and of the enter and exit plan-mode pair, only the one that makes sense right now is offered. Then read getFunctionDeclarations, the next method in that file, and see how Plan Mode rewrites the description of the write and edit tools ("ONLY FOR PLANS") instead of hiding them.
  2. Errors the model should see, and errors it should not. Codex, codex-rs/core/src/tools/registry.rs, function dispatch_any_with_state. A call to a tool name Codex does not know becomes FunctionCallError::RespondToModel with the message unsupported call: <name>. A known tool called with the wrong kind of payload becomes FunctionCallError::Fatal. Now search parallel.rs for FunctionCallError::Fatal: a fatal error turns into CodexErr::Fatal and propagates up, while every other error is turned into a tool result for the model. Ask yourself which failures a model could fix by trying again, and which it could not.
  3. Workflow encoded in a description. Gemini CLI, model-family-sets/gemini-3.ts, entry google_web_search. The description ends by telling the model to follow up with web_fetch when a result needs deeper analysis: tool B follows tool A, in the same repo, on the Gemini 3 tool set.
  4. How tool guidelines reach the prompt. pi, packages/coding-agent/src/core/system-prompt.ts, function buildRules. Each selected tool's guidelines become bullet rules with duplicates removed, and there is a fallback for when bash or PowerShell is present and grep, find, and ls are not: use the shell for listing and searching.

Exercise: rewrite Codex's update_plan as a pi-style TypeBox schema. pi's read.ts already uses Type.Union and Type.Literal, which is enough to express the three statuses. Decide where "at most one step in progress" should live and how you would reject extra keys. Then compare your version with the Rust types in codex-rs/protocol/src/plan_tool.rs, and note every rule that your schema enforces and theirs does not, or the other way round.

0 of 18 slides completed

Your learning progress stays in this browser.

Self-check · 10 questions

01 / 10

According to the chapter, the single most important idea in tool design is:

Related chapters