> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_17_hands-on_labs/17.2_lab2_tool_use_capability.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 17.2 Lab 2: Adding Tool Use Capability to the CLI Tool

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-18

***

In the previous section, we implemented a CLI tool capable of streaming conversations with an LLM. However, pure conversation alone cannot accomplish real programming tasks — the AI needs the ability to **read files**, **edit code**, and **execute commands**. This is where Tool Use comes in.

This section adds three core tools to the CLI tool: file reading (Read), file writing (Write), and command execution (Bash), directly corresponding to `tool/read.ts`, `tool/write.ts`, and `tool/bash.ts` analyzed in Chapter 5 of OpenCode.

## 17.2.1 Objective

Implement three tools and integrate them into the conversation flow, enabling the AI to:

1. Read local file contents
2. Create or overwrite files
3. Execute Shell commands

More importantly, implement an **Agentic Loop** — the AI calls a tool, we execute it, return the result to the AI, and the AI continues reasoning — until the AI determines the task is complete.

> **Extended Explanation — Function Calling / Tool Use**
>
> Function Calling is one of the core capabilities of modern LLMs. It allows an LLM to "decide" to invoke a predefined function during text generation, rather than directly outputting text. The flow is as follows:
>
> 1. The developer describes available tools to the LLM (name, parameters, purpose)
> 2. The user sends a request; the LLM determines which tool to call and outputs the tool name and arguments
> 3. The developer receives the tool call request and executes the tool locally
> 4. The execution result is returned to the LLM
> 5. The LLM continues generating a response based on the result (and may call tools again)
>
> This mechanism evolves the LLM from "only able to talk" into an Agent that "can take action."

## 17.2.2 Implementation Steps

### Step 1: Define Tool Schemas

Use Zod to define the parameter structures for each tool. This is consistent with the `Tool.define()` mechanism in OpenCode's `tool/tool.ts`:

```typescript
import { z } from "zod"
import { tool } from "ai"
import * as fs from "fs"
import { execSync } from "child_process"

// Tool 1: File reading
const readFileTool = tool({
  description: "Read the contents of a file at a specified path. Used for viewing code, configuration files, etc.",
  parameters: z.object({
    filePath: z.string().describe("Absolute or relative path of the file to read"),
  }),
  execute: async ({ filePath }) => {
    try {
      const content = fs.readFileSync(filePath, "utf-8")
      return `File contents (${filePath}):\n${content}`
    } catch (e: any) {
      return `Error: Unable to read file ${filePath}: ${e.message}`
    }
  },
})

// Tool 2: File writing
const writeFileTool = tool({
  description: "Write content to a file at a specified path. Creates the file if it does not exist; overwrites it if it does.",
  parameters: z.object({
    filePath: z.string().describe("Path of the file to write"),
    content: z.string().describe("Content to write to the file"),
  }),
  execute: async ({ filePath, content }) => {
    try {
      fs.writeFileSync(filePath, content, "utf-8")
      return `Successfully wrote file: ${filePath} (${content.length} characters)`
    } catch (e: any) {
      return `Error: Unable to write file ${filePath}: ${e.message}`
    }
  },
})

// Tool 3: Command execution
const bashTool = tool({
  description: "Execute a command in the Shell. Used for running code, installing dependencies, listing directories, etc.",
  parameters: z.object({
    command: z.string().describe("The Shell command to execute"),
  }),
  execute: async ({ command }) => {
    try {
      const output = execSync(command, {
        encoding: "utf-8",
        timeout: 30000,  // 30 second timeout
        maxBuffer: 1024 * 1024,  // 1MB output limit
      })
      return `Command output:\n${output}`
    } catch (e: any) {
      return `Command execution failed:\n${e.stderr || e.message}`
    }
  },
})
```

Note the importance of the `description` field — the LLM reads these descriptions to decide when and which tool to use. The clearer and more accurate the description, the better the LLM's tool selection. This is entirely consistent with the role of the `.txt` description files for each tool in OpenCode (e.g., `tool/read.txt`).

### Step 2: Integrate with streamText

Pass the tools to the `tools` parameter of `streamText`:

```typescript
const result = streamText({
  model,
  system: `You are an AI programming assistant capable of reading files, writing files, and executing commands.
Rules:
1. When you need to view file contents, use the readFile tool
2. When you need to create or modify files, use the writeFile tool
3. When you need to execute commands, use the bash tool
4. Before modifying a file, first read it to understand the current contents
5. When the task is complete, simply inform the user of the result`,
  messages,
  tools: {
    readFile: readFileTool,
    writeFile: writeFileTool,
    bash: bashTool,
  },
  maxSteps: 10,  // Allow up to 10 rounds of tool calls
})
```

The `maxSteps` parameter is the Vercel AI SDK's built-in support for the Agentic Loop — it allows the LLM to call tools multiple times within a single `streamText` invocation, with the SDK automatically handling the "call tool -> get result -> continue generating" loop.

### Step 3: Implement the Agentic Loop

The complete chat function needs to handle tool call events:

```typescript
async function chat(userInput: string) {
  messages.push({ role: "user", content: userInput })

  const result = streamText({
    model,
    system: `You are an AI programming assistant...(same as above)`,
    messages,
    tools: {
      readFile: readFileTool,
      writeFile: writeFileTool,
      bash: bashTool,
    },
    maxSteps: 10,
  })

  let fullResponse = ""
  process.stdout.write("\nAssistant: ")

  // Handle streaming output — including both text and tool calls
  for await (const part of result.fullStream) {
    switch (part.type) {
      case "text-delta":
        // Text chunk
        process.stdout.write(part.textDelta)
        fullResponse += part.textDelta
        break

      case "tool-call":
        // LLM decided to call a tool
        console.log(`\n  [Tool Call] ${part.toolName}(${
          JSON.stringify(part.args)
        })`)
        break

      case "tool-result":
        // Tool execution complete
        const preview = String(part.result).slice(0, 200)
        console.log(`  [Tool Result] ${preview}${
          String(part.result).length > 200 ? "..." : ""
        }`)
        break

      case "step-finish":
        // One round of tool calls complete, LLM continues reasoning
        break
    }
  }

  console.log("\n")
  messages.push({ role: "assistant", content: fullResponse })
}
```

### Step 4: Test

```bash
bun run index.ts
```

```
You: Help me create a hello.py file with a simple Flask server
```
