Claude Code: Tool System Architecture

🇬🇧 English claude-codetoolsarchitectureanalysisenglish
📋 Table of Contents (12 sections)
  1. Tools System
  2. Overview
  3. Tool Catalog (~40 tools)
  4. Tool Factory Pattern
  5. Tool Directory Structure
  6. Permission System
  7. Tool Execution Flow
  8. Key Tool Categories
  9. Tool Best Practices
  10. Tool Discovery
  11. MCP Tool Integration
  12. Security Considerations

Tools System

Overview

The tools system is the core abstraction of claude-code-leaked. Every capability (file operations, shell execution, MCP integration, agent orchestration) is exposed as a self-contained tool.

Tool Catalog (~40 tools)

File I/O Tools

  • FileReadTool - Read file contents
  • FileWriteTool - Write new files
  • FileEditTool - Edit existing files
  • FileSearchTool - Search files by pattern
  • GlobTool - Glob pattern matching

Shell Execution Tools

  • BashTool - Execute bash commands
  • PowerShellTool - Execute PowerShell commands
  • REPLTool - Interactive REPL execution

Agent Orchestration Tools

  • AgentTool - Spawn and manage sub-agents
  • TeamCreateTool - Create agent teams
  • SendMessageTool - Send messages to agents

MCP Integration Tools

  • MCPTool - Model Context Protocol operations
  • ListMcpResourcesTool - List MCP resources
  • ReadMcpResourceTool - Read MCP resource content

System Tools

  • WebSearchTool - Web search capabilities
  • TaskTool - Task management
  • MemoryTool - Memory management

Tool Factory Pattern

All tools are created using a consistent factory function:

buildTool({
  name: 'ToolName',
  description: 'Description of what the tool does',
  inputSchema: z.object({
    // Input validation schema using Zod
    param1: z.string(),
    param2: z.number(),
  }),
  async call(args, context) {
    // Tool execution logic
    return result;
  },
  async checkPermissions(input, context) {
    // Permission checks before execution
    return true; // or false with error message
  },
  async toMessage(args, result, context) {
    // Convert tool result to message format
    return message;
  },
});

Tool Directory Structure

Each tool lives in its own directory:

src/tools/<ToolName>/
├── <ToolName>Tool.ts - Tool implementation
├── UI.tsx - UI rendering component
├── prompt.ts - System prompt contribution
└── [optional: test files, helpers]

Example: BashTool

// src/tools/BashTool/BashTool.ts
import { buildTool } from '../../Tool.js';
import { z } from 'zod/v4';
import { executeCommand } from './executor.js';

export const BashTool = buildTool({
  name: 'BashTool',
  description: 'Execute bash commands in the terminal',
  inputSchema: z.object({
    command: z.string().describe('The bash command to execute'),
    timeout: z.number().optional().describe('Timeout in milliseconds'),
    workdir: z.string().optional().describe('Working directory'),
  }),
  async call(args, context) {
    const result = await executeCommand(args.command, {
      timeout: args.timeout,
      workdir: args.workdir,
    });
    return result;
  },
  async checkPermissions(input, context) {
    // Check if command is allowed in current working directory
    return true;
  },
});

Permission System

Tools can define custom permission checks:

async checkPermissions(input, context) {
  // Check working directory restrictions
  // Check tool-specific rules
  // Return { result: true } or { result: false, message: '...', errorCode: 403 }
}

Permission modes:

  • default: Standard permission checks
  • plan: Planning mode (model-initiated)
  • auto: Automated permission handling
  • bypassPermissions: Skip permission prompts

Tool Execution Flow

1. User invokes tool via natural language or command
2. QueryEngine validates tool input schema
3. checkPermissions() runs (if enabled)
4. call() executes the tool logic
5. toMessage() formats result for display
6. Result added to message history
7. UI renders tool output

Key Tool Categories

Core Tools (Always Available)

  • File operations (read, write, edit)
  • Shell execution (bash, powershell)
  • Search and glob patterns

Conditional Tools (Feature-Gated)

  • Agent tools (COORDINATOR_MODE)
  • MCP tools (MCP_ENABLED)
  • Web search (WEB_SEARCH)

Special Tools

  • SyntheticOutputTool: Handles structured output
  • SkillTool: Loads and executes skills
  • AgentTool: Manages sub-agent spawning

Tool Best Practices

  1. Self-Contained: Each tool has its own logic, UI, and prompt
  2. Schema Validation: Zod schemas for strict input validation
  3. Permission Gates: Configurable access control
  4. Lazy Loading: Heavy tools loaded on demand
  5. Error Handling: Consistent error codes and messages
  6. UI Integration: Dedicated UI component per tool

Tool Discovery

Tools are discovered and registered via:

// src/tools.ts
export function getTools(): Tools {
  const tools: Tools = [];
  tools.push(BashTool);
  tools.push(FileReadTool);
  tools.push(FileWriteTool);
  // ... all other tools
  return tools;
}

MCP Tool Integration

MCP (Model Context Protocol) tools extend capabilities:

// src/services/mcp/client.ts
export async function getMcpToolsCommandsAndResources(
  servers: MCPServerConnection[]
): Promise<Tools> {
  // Fetch tools from connected MCP servers
  // Return aggregated tool list
}

Security Considerations

  1. Working Directory Restrictions: Tools check if paths are within allowed directories
  2. Permission Modes: Different modes control tool access
  3. Lazy Loading: Reduces memory footprint
  4. Feature Flags: Conditional tool availability
  5. Error Handling: Graceful degradation on failures
← Back to claudecodeanalysis