> 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_05_tool_system/5.1_tool_abstraction_layer_design.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 5.1 Tool Abstraction Layer Design

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

***

Tools are the bridge between an AI Agent and the outside world. Without tools, an LLM can only generate text; with tools, an LLM can read and write files, execute commands, and search code -- becoming a true "Agent."

## 5.1.1 The `Tool.Info` Interface

All tools implement the unified `Tool.Info` interface (`tool/tool.ts`):

```typescript
export interface Info<
  Parameters extends z.ZodType = z.ZodType,
  M extends Metadata = Metadata
> {
  id: string                          // Unique identifier for the tool (e.g., "bash", "edit", "read")
  init: (ctx?: InitContext) => Promise<{
    description: string               // Description of the tool's capabilities (sent to the LLM)
    parameters: Parameters            // Zod Schema for parameters
    execute(                           // Execution function
      args: z.infer<Parameters>,
      ctx: Context,
    ): Promise<{
      title: string                   // Short title for the execution result
      metadata: M                     // Metadata (e.g., whether the output was truncated)
      output: string                  // Output text
      attachments?: MessageV2.FilePart[]  // File attachments
    }>
    formatValidationError?(error: z.ZodError): string  // Custom parameter error message
  }>
}
```

**Key Design Decisions**:

1. **Two-Phase Initialization**: `init()` is asynchronous, allowing tools to perform async operations during initialization (such as detecting the environment or loading configuration). The returned object contains `description` and `parameters` -- this information is sent to the LLM so it knows what the tool can do and what parameters it requires.
2. **`InitContext` Carries Agent Information**: Tools can adjust their behavior based on the Agent that invokes them. For example, placeholders in the `description` can be replaced with context information such as the current directory.

## 5.1.2 The `Tool.Context` Object

Each time a tool executes, it receives a `Context` object:

```typescript
export type Context<M extends Metadata = Metadata> = {
  sessionID: string          // Current session ID
  messageID: string          // Current message ID
  agent: string              // Name of the Agent invoking the tool
  abort: AbortSignal         // Abort signal (triggered when the user cancels)
  callID?: string            // Tool call ID
  extra?: Record<string, any> // Additional metadata
  messages: MessageV2.WithParts[]  // All messages in the current session
  metadata(input: {          // Update tool metadata (displayed in real time)
    title?: string
    metadata?: M
  }): void
  ask(input: ...): Promise<void>   // Initiate a permission request
}
```

**The Importance of `ctx.ask()`**: This is the interface between a tool and the permission system. Before performing sensitive operations (such as writing files or executing commands), a tool must call `ctx.ask()` to request permission. If the permission rule is `"ask"`, this pauses tool execution and waits for user confirmation.

## 5.1.3 The `Tool.define()` Factory Function

`Tool.define()` is the standard way to create a tool:

```typescript
export function define<Parameters extends z.ZodType, Result extends Metadata>(
  id: string,
  init: Info<Parameters, Result>["init"] | Awaited<ReturnType<Info["init"]>>,
): Info<Parameters, Result> {
  return {
    id,
    init: async (initCtx) => {
      const toolInfo = init instanceof Function ? await init(initCtx) : init
      const execute = toolInfo.execute

      // Wrap execute to add unified parameter validation and output truncation
      toolInfo.execute = async (args, ctx) => {
        // 1. Parameter validation
        try {
          toolInfo.parameters.parse(args)
        } catch (error) {
          if (error instanceof z.ZodError && toolInfo.formatValidationError) {
            throw new Error(toolInfo.formatValidationError(error))
          }
          throw new Error(
            `The ${id} tool was called with invalid arguments: ${error}`
          )
        }

        // 2. Execute the tool
        const result = await execute(args, ctx)

        // 3. Automatically truncate output
        if (result.metadata.truncated !== undefined) return result
        const truncated = await Truncate.output(result.output, {}, initCtx?.agent)
        return {
          ...result,
          output: truncated.content,
          metadata: { ...result.metadata, truncated: truncated.truncated },
        }
      }
      return toolInfo
    },
  }
}
```

`Tool.define()` automatically adds two layers of protection to every tool:

* **Parameter Validation**: Uses a Zod Schema to verify that the parameters passed by the LLM are valid
* **Output Truncation**: Prevents excessively large tool output from consuming the entire context window

## 5.1.4 Output Truncation Mechanism

`Truncate` (`tool/truncation.ts`) is a critical safeguard:

```typescript
export namespace Truncate {
  export const MAX_LINES = 2000      // Maximum 2000 lines
  export const MAX_BYTES = 50 * 1024 // Maximum 50KB
  export const DIR = path.join(Global.Path.data, "tool-output")
}
```

> **Extended Explanation: Why Is Truncation Necessary?**
>
> An LLM's context window is finite. If a `read` tool returns a 10,000-line file, it could consume most of the available context space, making it impossible to continue the conversation.
>
> Truncation strategy: When output exceeds 2000 lines or 50KB, the full output is written to a temporary file, and only the truncated content is returned to the LLM, along with a note: "Output has been truncated. The full content is saved at \[file path]."
>
> After receiving the truncation notice, the LLM can use the `read` tool to selectively read specific portions of the full file on demand -- this is far more efficient than loading the entire file at once.

Truncated temporary files are periodically cleaned up (expired after 7 days):

```typescript
Scheduler.register({
  id: "tool.truncation.cleanup",
  interval: HOUR_MS,
  run: cleanup,
  scope: "global",
})
```
