3. Tool Use & Function Calling

Giving language models hands

A language model that can only generate text is like a brain in a jar — it can think, but it can't do anything. It can't read a file, query a database, check the weather, or run a test suite. Tool use changes that. By defining functions the model can call and wiring up the execution, you turn a text generator into something that can interact with the world.

This is the mechanism behind every modern AI coding assistant. When Claude Code edits a file, it's not printing text that looks like an edit — it's producing a structured tool call that the host application executes against the real filesystem. Understanding how this works is the foundation for building agentic systems.

The Tool-Use Loop

Tool use follows a simple request-response cycle:

  1. You define tools — each with a name, description, and input schema
  2. You send a message to the model along with the tool definitions
  3. The model responds with either text OR a tool call (structured arguments)
  4. Your code executes the tool call and returns the result
  5. The model sees the result and decides what to do next — respond to the user, or call another tool

This loop repeats until the model decides it has enough information to produce a final answer. A single user query might trigger zero tool calls (the model knows the answer) or a dozen (it needs to read files, search code, run tests).

User message + tool definitions
        │
        ▼
   ┌─────────┐
   │  Model   │──── text response ──── done
   │ decides  │
   └────┬─────┘
        │ tool call
        ▼
   ┌─────────┐
   │ Execute  │
   │  tool    │
   └────┬─────┘
        │ result
        ▼
   ┌─────────┐
   │  Model   │──── text response ──── done
   │ decides  │
   └────┬─────┘
        │ tool call
        ▼
       ...

Defining Tools

A tool definition has three parts: a name, a natural-language description, and a JSON Schema for the input parameters. The description is critical — it's how the model decides when to use the tool.

const tools = [
  {
    name: "read_file",
    description:
      "Read the contents of a file at the given path. " +
      "Use this to examine source code, configuration files, " +
      "or any text file in the project.",
    input_schema: {
      type: "object",
      properties: {
        path: {
          type: "string",
          description: "Absolute or relative path to the file"
        },
        line_start: {
          type: "integer",
          description: "Optional first line to read (1-indexed)"
        },
        line_end: {
          type: "integer",
          description: "Optional last line to read (1-indexed)"
        }
      },
      required: ["path"]
    }
  },
  {
    name: "run_command",
    description:
      "Execute a shell command and return its stdout and stderr. " +
      "Use this for running tests, checking git status, installing " +
      "packages, or any other terminal operation.",
    input_schema: {
      type: "object",
      properties: {
        command: {
          type: "string",
          description: "The shell command to execute"
        },
        timeout_ms: {
          type: "integer",
          description: "Timeout in milliseconds (default 30000)"
        }
      },
      required: ["command"]
    }
  }
];

Writing Good Tool Descriptions

The description is the single most important part of a tool definition. The model uses it to decide:

  • Whether this tool is relevant to the current task
  • When to use it versus another tool
  • What kind of input to provide

Bad description:

"Searches files"

Good description:

"Search for files matching a glob pattern (e.g. '**/*.ts', 'src/**/test.*').
Returns a list of matching file paths sorted by modification time.
Use this when you need to find files by name or extension. For searching
file *contents*, use the grep tool instead."

The good description explains what the tool does, gives examples of valid inputs, describes what it returns, and distinguishes it from similar tools. This is exactly how real coding assistants define their tools — with enough detail that the model rarely picks the wrong one.

Parameter Descriptions Matter Too

Each parameter's description field guides the model in constructing valid arguments:

{
  pattern: {
    type: "string",
    description:
      "Glob pattern to match files. Supports ** for recursive directory " +
      "matching and * for single-level wildcards. Examples: '**/*.ts', " +
      "'src/components/*.tsx', 'package.json'"
  }
}

Without this, the model might pass a regex when you expect a glob, or a full path when you expect a pattern.

The Model's Decision Process

When the model receives a message with tool definitions, it makes a decision at each generation step: should it produce text tokens, or should it produce a tool call?

This decision is influenced by:

  1. The user's request — "Read the file at src/index.ts" strongly suggests using read_file
  2. The tool descriptions — the model matches the request against available tools
  3. The conversation history — if a previous tool call returned an error, the model might try a different approach
  4. The system prompt — instructions like "always read a file before editing it" shape tool selection

The model doesn't execute tools itself — it has no access to your filesystem or network. It produces a structured message that says "I want to call this tool with these arguments," and your code handles execution. This separation is fundamental to the security model: you control what actually happens.

Executing Tool Calls

When the model returns a tool call, your code is responsible for:

  1. Validating the call — is this a known tool? Are the arguments valid?
  2. Permission checking — should this tool call be allowed? (More on this below)
  3. Executing the tool — running the actual operation
  4. Returning the result — sending output back to the model
async function handleToolCall(
  toolName: string,
  args: Record<string, unknown>
): Promise<string> {
  switch (toolName) {
    case "read_file": {
      const { path, line_start, line_end } = args as ReadFileArgs;
      const content = await fs.readFile(path, "utf-8");
      if (line_start || line_end) {
        const lines = content.split("\n");
        const start = (line_start ?? 1) - 1;
        const end = line_end ?? lines.length;
        return lines.slice(start, end).join("\n");
      }
      return content;
    }

    case "run_command": {
      const { command, timeout_ms } = args as RunCommandArgs;
      const { stdout, stderr } = await exec(command, {
        timeout: timeout_ms ?? 30000
      });
      return stderr ? `stdout:\n${stdout}\nstderr:\n${stderr}` : stdout;
    }

    default:
      return `Unknown tool: ${toolName}`;
  }
}

Multi-Tool Calls

Modern APIs allow the model to request multiple tool calls in a single response. This is important for efficiency — if the model needs to read three files, it shouldn't have to make three round trips.

[
  {
    "type": "tool_use",
    "name": "read_file",
    "input": { "path": "src/index.ts" }
  },
  {
    "type": "tool_use",
    "name": "read_file",
    "input": { "path": "src/config.ts" }
  },
  {
    "type": "tool_use",
    "name": "run_command",
    "input": { "command": "git log --oneline -5" }
  }
]

The host application executes all three in parallel and returns the results together. The model then sees all three results at once and can proceed with full context.

Parallel vs sequential tool calls is a design choice in your application:

  • Parallel — faster, but tools can't depend on each other's results
  • Sequential — slower, but each call can use previous results
  • Model-decided — let the model choose by issuing one call at a time when order matters

Most coding assistants use parallel execution for reads and sequential execution for writes, since writes may depend on what was read.

Permission Models

Giving an LLM the ability to execute arbitrary shell commands is powerful but dangerous. Every serious tool-use implementation includes a permission layer:

Auto-allow lists — safe, read-only operations execute without prompting:

  • Reading files
  • Searching code
  • Listing directories
  • Running git status or git log

Prompt-on-use — potentially dangerous operations ask the user first:

  • Writing or deleting files
  • Running arbitrary shell commands
  • Making network requests
  • Git operations that modify history

Deny lists — some operations are never allowed:

  • rm -rf /
  • Commands that modify system configuration
  • Operations outside the project directory

This is exactly the permission model Claude Code uses. When you see it ask "Allow this tool call?", that's the permission layer in action.

type Permission = "allow" | "prompt" | "deny";

function checkPermission(toolName: string, args: unknown): Permission {
  if (toolName === "read_file") return "allow";
  if (toolName === "run_command") {
    const cmd = (args as { command: string }).command;
    if (cmd.startsWith("git log") || cmd.startsWith("git status")) {
      return "allow";
    }
    if (cmd.includes("rm -rf") || cmd.includes("sudo")) {
      return "deny";
    }
    return "prompt";
  }
  return "prompt";
}

Tool Result Formatting

How you format tool results affects how well the model uses them. Some guidelines:

Include context, not just data. Instead of returning raw file contents, prefix with the file path and line numbers:

File: src/utils/parse.ts (lines 1-45)
  1 | import { Token } from './types';
  2 |
  3 | export function parse(input: string): AST {
  ...

Truncate large results. If a file is 10,000 lines, returning all of it wastes context window space. Return the first N lines with a note: "Showing lines 1-200 of 10,432. Use line_start/line_end to read specific ranges."

Structure error output. Don't just return "command failed" — include the exit code, stderr, and enough context for the model to diagnose the problem:

Command failed (exit code 1):
$ npm test -- --grep "auth"

FAIL src/auth.test.ts
  ● login() › should reject expired tokens

    Expected: "TOKEN_EXPIRED"
    Received: "INVALID_TOKEN"

Return types matter. The model performs better when tool results follow a consistent format. If one tool returns JSON and another returns plain text and a third returns markdown, the model has to adapt to each format. Consistency reduces errors.

Error Handling

Tools fail. Files don't exist, commands time out, APIs return 500s. How you surface errors to the model determines whether it recovers gracefully or spirals.

Return errors as tool results, not exceptions. The model needs to see the error to decide what to do:

case "read_file": {
  try {
    return await fs.readFile(args.path, "utf-8");
  } catch (err) {
    if (err.code === "ENOENT") {
      return `Error: File not found: ${args.path}`;
    }
    return `Error reading file: ${err.message}`;
  }
}

When the model sees "File not found: src/indx.ts", it can recognize the typo and try "src/index.ts". If instead the tool throws an unhandled exception and the conversation stops, the model never gets a chance to recover.

Rate-limit retries. If the model keeps calling the same tool with the same arguments and getting errors, cap the retries and surface the issue to the user rather than burning tokens in a loop.

Tool Design Patterns

Granular vs coarse tools

Granular: read_file, write_file, list_dir, search_files — many small tools, each doing one thing.

Coarse: file_operation(action, path, content) — one tool that takes an action parameter.

Granular tools work better in practice. The model makes cleaner decisions when each tool has a clear, singular purpose. Coarse tools lead to more argument errors and misuse.

Stateless tools

Tools should be stateless when possible. Instead of a cd tool that changes a working directory for subsequent calls, each tool should accept an absolute path. Stateful tool sequences are fragile — if the model forgets the current state, subsequent calls break.

Confirmation tools

For destructive operations, include a separate confirmation step:

{
  name: "delete_file",
  description: "Delete a file. Returns a confirmation prompt — " +
    "call confirm_delete with the returned token to actually delete.",
  input_schema: {
    properties: {
      path: { type: "string" }
    }
  }
}

This adds friction that prevents the model from accidentally deleting files in a multi-step plan.

How Real Tools Define Their Tool Sets

If you look at the tool definitions for production coding assistants, some patterns emerge:

Read-heavy tool sets. Most tools are for reading information — reading files, searching code, listing directories, checking git status. The model typically reads 5-10x more than it writes.

Edit, don't rewrite. Instead of a write_file tool that overwrites the entire file, most assistants provide an edit_file tool that takes an old string and a new string. This is safer (can't accidentally delete the rest of the file), more token-efficient (only sends the diff), and easier for users to review.

Scoped commands. Rather than a general run_command tool, some assistants provide scoped tools: run_tests, git_commit, install_package. This limits the blast radius and makes permission management simpler.

Rich tool results. The best implementations return structured, context-rich results that minimize the number of follow-up tool calls needed. A search_code tool that returns matching lines with surrounding context and file paths saves a round trip compared to one that returns only line numbers.

Putting It All Together

Here's a minimal but complete tool-use loop:

async function agentLoop(
  userMessage: string,
  tools: Tool[],
  maxTurns = 10
): Promise<string> {
  const messages: Message[] = [
    { role: "user", content: userMessage }
  ];

  for (let turn = 0; turn < maxTurns; turn++) {
    const response = await client.messages.create({
      model: "claude-sonnet-4-6-20250514",
      max_tokens: 4096,
      system: SYSTEM_PROMPT,
      tools,
      messages
    });

    // Collect text and tool-use blocks
    const textParts: string[] = [];
    const toolCalls: ToolUseBlock[] = [];

    for (const block of response.content) {
      if (block.type === "text") textParts.push(block.text);
      if (block.type === "tool_use") toolCalls.push(block);
    }

    // If no tool calls, we're done
    if (toolCalls.length === 0) {
      return textParts.join("\n");
    }

    // Add the assistant's response to history
    messages.push({ role: "assistant", content: response.content });

    // Execute all tool calls and collect results
    const toolResults = await Promise.all(
      toolCalls.map(async (call) => ({
        type: "tool_result" as const,
        tool_use_id: call.id,
        content: await handleToolCall(call.name, call.input)
      }))
    );

    // Add results to history
    messages.push({ role: "user", content: toolResults });
  }

  return "Reached maximum turns without completing.";
}

This 40-line function is the skeleton of every AI coding assistant. The rest is tool definitions, permission logic, UI, and polish — but the core loop is always this: send message → check for tool calls → execute → feed results back → repeat.

Try It — Tool-Use Loop Visualizer

Watch the full tool-use cycle play out step by step. Each scenario shows the model receiving a task, deciding which tools to call, processing results, and arriving at an answer.

What's Next

Tool use gives models the ability to act, but every action consumes tokens from a finite context window. As conversations grow and tool results accumulate, you start hitting limits. The next article covers context management — the strategies for fitting the right information into a limited window, and what to do when it's not enough.