# Claude Code Source Code Analysis Claude Code is Anthropic's official AI-powered coding assistant CLI tool. Built on a React terminal renderer with TypeScript and Bun, it provides an interactive coding environment with 40+ tools, multi-agent orchestration, background memory consolidation ("Dream" system), and sophisticated permission management. The architecture features compile-time feature flags for internal vs. external builds, modular system prompts with caching, and a comprehensive tool registry supporting file operations, shell execution, web access, and language server protocol integration. The codebase reveals advanced capabilities including KAIROS (always-on assistant mode), ULTRAPLAN (remote planning sessions), Coordinator Mode for multi-agent task orchestration, and a Tamagotchi-style companion system called "Buddy." The permission system classifies tool actions by risk level with ML-based auto-approval, and the tool architecture uses Zod schemas for input validation with extensive error handling and user-friendly suggestions. ## Tool Interface The core Tool interface defines how all Claude Code tools are structured, with input/output schemas, permission checking, and rendering methods. ```typescript import { z } from 'zod/v4' import type { ToolUseContext, ToolResult, ToolDef } from './Tool.js' import { buildTool } from './Tool.js' // Define input schema with Zod const inputSchema = z.strictObject({ file_path: z.string().describe('The absolute path to the file'), content: z.string().describe('The content to write'), }) // Define output schema const outputSchema = z.object({ success: z.boolean(), bytesWritten: z.number(), }) // Build a tool with the buildTool helper export const MyTool = buildTool({ name: 'MyTool', maxResultSizeChars: 100_000, async description() { return 'A tool that writes files' }, async prompt() { return 'Use this tool to write content to files...' }, get inputSchema() { return inputSchema }, get outputSchema() { return outputSchema }, isConcurrencySafe() { return false }, isReadOnly() { return false }, async checkPermissions(input, context) { // Return { behavior: 'allow', updatedInput: input } to allow // Return { behavior: 'deny', message: '...' } to deny return { behavior: 'allow', updatedInput: input } }, async call(input, context, canUseTool, parentMessage) { // Implement tool logic const result = await writeFile(input.file_path, input.content) return { data: { success: true, bytesWritten: result.length } } }, mapToolResultToToolResultBlockParam(data, toolUseID) { return { tool_use_id: toolUseID, type: 'tool_result', content: `Wrote ${data.bytesWritten} bytes successfully`, } }, renderToolUseMessage(input, options) { return Writing to {input.file_path} }, }) ``` ## FileReadTool - Reading Files The FileReadTool reads files, images, PDFs, and Jupyter notebooks with token-based limits and automatic format detection. ```typescript import { FileReadTool } from './tools/FileReadTool/FileReadTool.js' // Basic file read const result = await FileReadTool.call( { file_path: '/path/to/file.ts' }, toolUseContext, canUseTool, parentMessage ) // Read with offset and limit for large files const partialResult = await FileReadTool.call( { file_path: '/path/to/large-file.ts', offset: 100, // Start at line 100 limit: 50 // Read 50 lines }, toolUseContext, canUseTool, parentMessage ) // Read PDF with page range const pdfResult = await FileReadTool.call( { file_path: '/path/to/document.pdf', pages: '1-5' // Read pages 1-5 only }, toolUseContext, canUseTool, parentMessage ) // Output types: // - type: 'text' -> { filePath, content, numLines, startLine, totalLines } // - type: 'image' -> { base64, type, originalSize, dimensions } // - type: 'notebook' -> { filePath, cells } // - type: 'pdf' -> { filePath, base64, originalSize } // - type: 'file_unchanged' -> { filePath } (deduplication) ``` ## FileEditTool - Editing Files The FileEditTool performs exact string replacements in files with validation and permission checking. ```typescript import { FileEditTool } from './tools/FileEditTool/FileEditTool.js' // Replace a specific string in a file const editResult = await FileEditTool.call( { file_path: '/path/to/file.ts', old_string: 'function oldName(', new_string: 'function newName(', replace_all: false // Only replace first occurrence }, toolUseContext, canUseTool, parentMessage ) // Replace all occurrences (e.g., rename a variable) const renameResult = await FileEditTool.call( { file_path: '/path/to/file.ts', old_string: 'oldVariable', new_string: 'newVariable', replace_all: true }, toolUseContext, canUseTool, parentMessage ) // Create a new file (empty old_string on non-existent file) const createResult = await FileEditTool.call( { file_path: '/path/to/new-file.ts', old_string: '', new_string: 'export const myFunction = () => {}\n', replace_all: false }, toolUseContext, canUseTool, parentMessage ) // Output: { filePath, oldString, newString, originalFile, structuredPatch, userModified, replaceAll } ``` ## GlobTool - Finding Files by Pattern The GlobTool finds files matching glob patterns with results sorted by modification time. ```typescript import { GlobTool } from './tools/GlobTool/GlobTool.js' // Find all TypeScript files const tsFiles = await GlobTool.call( { pattern: '**/*.ts' }, toolUseContext, canUseTool, parentMessage ) // Find files in a specific directory const srcFiles = await GlobTool.call( { pattern: '*.{ts,tsx}', path: '/project/src' }, toolUseContext, canUseTool, parentMessage ) // Find test files const testFiles = await GlobTool.call( { pattern: '**/*.test.ts' }, toolUseContext, canUseTool, parentMessage ) // Output: { durationMs, numFiles, filenames: string[], truncated: boolean } // Results limited to 100 files by default, sorted by modification time (newest first) ``` ## GrepTool - Searching File Contents The GrepTool searches file contents using ripgrep with regex support and multiple output modes. ```typescript import { GrepTool } from './tools/GrepTool/GrepTool.js' // Search for a pattern (files_with_matches mode - default) const filesWithPattern = await GrepTool.call( { pattern: 'TODO|FIXME' }, toolUseContext, canUseTool, parentMessage ) // Search with content output and context lines const contentSearch = await GrepTool.call( { pattern: 'function\\s+\\w+', output_mode: 'content', '-C': 3, // 3 lines of context before and after '-n': true // Show line numbers }, toolUseContext, canUseTool, parentMessage ) // Search specific file types with case insensitivity const jsSearch = await GrepTool.call( { pattern: 'useEffect', type: 'js', '-i': true, // Case insensitive head_limit: 50 // Limit to 50 results }, toolUseContext, canUseTool, parentMessage ) // Count occurrences per file const countSearch = await GrepTool.call( { pattern: 'import', output_mode: 'count', glob: '*.ts' }, toolUseContext, canUseTool, parentMessage ) // Multiline search (spans across lines) const multilineSearch = await GrepTool.call( { pattern: 'interface\\s+\\w+\\s*\\{[\\s\\S]*?\\}', multiline: true, output_mode: 'content' }, toolUseContext, canUseTool, parentMessage ) // Output modes: // - files_with_matches: { mode, numFiles, filenames } // - content: { mode, content, numLines, appliedLimit?, appliedOffset? } // - count: { mode, numFiles, content, numMatches } ``` ## Agent System - Multi-Agent Orchestration The Agent system enables spawning autonomous worker agents for parallel task execution. ```typescript import { runAgent } from './tools/AgentTool/runAgent.js' // Run an agent with a specific task const agentGenerator = runAgent({ agentDefinition: { agentType: 'worker', getSystemPrompt: () => 'You are a code research agent...', model: 'sonnet', permissionMode: 'default', }, promptMessages: [ createUserMessage({ content: 'Find all API endpoints in src/' }) ], toolUseContext, canUseTool, isAsync: true, // Run in background querySource: 'agent:worker', availableTools: workerTools, }) // Iterate over agent messages for await (const message of agentGenerator) { if (message.type === 'assistant') { console.log('Agent response:', message.message.content) } } // Built-in agent types available: // - 'Explore': Fast codebase exploration // - 'Plan': Implementation planning // - 'worker': General task execution (coordinator mode) // - 'general-purpose': Multi-step task handling ``` ## Coordinator Mode - Task Orchestration Coordinator mode transforms Claude Code into a multi-agent orchestrator that directs parallel workers. ```typescript import { isCoordinatorMode, getCoordinatorSystemPrompt } from './coordinator/coordinatorMode.js' // Check if coordinator mode is enabled if (isCoordinatorMode()) { // Get the coordinator system prompt const systemPrompt = getCoordinatorSystemPrompt() // Coordinator tools: // - Task (AgentTool): Spawn workers // - SendMessage: Continue existing workers // - TaskStop: Stop running workers } // Worker task-notification format (received as user messages): // // {agentId} // completed|failed|killed // {human-readable status summary} // {agent's final text response} // // N // N // N // // // Example coordinator workflow: // 1. Research phase: Launch parallel workers to investigate // 2. Synthesis: Coordinator reads findings and crafts specs // 3. Implementation: Workers make targeted changes // 4. Verification: Workers test changes work ``` ## Dream System - Memory Consolidation The Dream system performs background memory consolidation as a forked subagent. ```typescript import { buildConsolidationPrompt } from './services/autoDream/consolidationPrompt.js' // Build the consolidation prompt for the dream agent const dreamPrompt = buildConsolidationPrompt( '/path/to/memory/root', // Memory directory '/path/to/transcripts', // Session transcripts 'Additional context...' // Extra instructions ) // Dream phases: // Phase 1 - Orient: ls memory directory, read MEMORY.md, skim existing topics // Phase 2 - Gather: Find new info from daily logs, drifted memories, transcripts // Phase 3 - Consolidate: Write/update memory files, convert dates, delete contradictions // Phase 4 - Prune: Keep MEMORY.md under 200 lines/25KB, remove stale pointers // Three-gate trigger system: // 1. Time gate: 24 hours since last dream // 2. Session gate: At least 5 sessions since last dream // 3. Lock gate: Acquire consolidation lock (prevents concurrent dreams) ``` ## Buddy Companion System The Buddy system creates deterministic Tamagotchi-style companions based on user ID. ```typescript import { roll, getCompanion, companionUserId } from './buddy/companion.js' import type { Companion, Rarity, StatName } from './buddy/types.js' // Roll a companion based on user ID (deterministic - same user = same buddy) const userId = companionUserId() // Gets from config const { bones, inspirationSeed } = roll(userId) // bones contains: // - rarity: 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary' // - species: one of 18 species (Pebblecrab, Dustbunny, Mossfrog, etc.) // - eye: one of 6 eye styles // - hat: 8 options (common rarity gets 'none') // - shiny: 1% chance independent of rarity // - stats: { DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK } (0-100 each) // Rarity distribution: // Common: 60%, Uncommon: 25%, Rare: 10%, Epic: 4%, Legendary: 1% // Species by rarity: // Common: Pebblecrab, Dustbunny, Mossfrog, Twigling, Dewdrop, Puddlefish // Uncommon: Cloudferret, Gustowl, Bramblebear, Thornfox // Rare: Crystaldrake, Deepstag, Lavapup // Epic: Stormwyrm, Voidcat, Aetherling // Legendary: Cosmoshale, Nebulynx // Get full companion with stored soul const companion = getCompanion() // Returns Companion | undefined ``` ## Permission System The permission system manages tool access with risk classification and rule-based allow/deny. ```typescript import { checkWritePermissionForTool, checkReadPermissionForTool } from './utils/permissions/filesystem.js' import type { PermissionMode, PermissionResult } from './types/permissions.js' // Permission modes: // - 'default': Interactive prompts for each action // - 'auto': ML-based auto-approval via transcript classifier // - 'bypassPermissions': Skip all checks (admin) // - 'acceptEdits': Auto-accept file edits // - 'plan': Plan mode - read-only exploration // Check write permission const writePermission = await checkWritePermissionForTool( FileEditTool, { file_path: '/path/to/file.ts' }, toolPermissionContext ) // Permission result types: // { behavior: 'allow', updatedInput } - Proceed with tool // { behavior: 'deny', message } - Reject with reason // { behavior: 'ask', message } - Prompt user for permission // Tool permission context structure: const context = { mode: 'default', additionalWorkingDirectories: new Map(), alwaysAllowRules: { session: ['Bash(git *)'], cliArg: [] }, alwaysDenyRules: { session: ['Write(~/.ssh/*)'] }, alwaysAskRules: {}, isBypassPermissionsModeAvailable: false, shouldAvoidPermissionPrompts: false, // For background agents } ``` ## MCP Server Integration Model Context Protocol (MCP) integration for connecting external tool servers. ```typescript import { connectToServer, fetchToolsForClient } from './services/mcp/client.js' import type { MCPServerConnection, ScopedMcpServerConfig } from './services/mcp/types.js' // Connect to an MCP server const config: ScopedMcpServerConfig = { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem'], env: { ALLOWED_DIRECTORIES: '/project' }, scope: 'project', } const client = await connectToServer('filesystem', config) if (client.type === 'connected') { // Fetch available tools from the server const tools = await fetchToolsForClient(client) console.log(`Connected with ${tools.length} tools`) // Tools are automatically prefixed: mcp__servername__toolname // Unless CLAUDE_AGENT_SDK_MCP_NO_PREFIX is set // Cleanup when done await client.cleanup() } // Connection states: // - 'connected': Successfully connected // - 'connecting': In progress // - 'failed': Connection failed // - 'not-started': Not yet attempted ``` ## Query Engine The query engine handles conversation flow with the Claude API including tool use loops. ```typescript import { query } from './query.js' import type { Message, StreamEvent } from './types/message.js' // Run a query with tool use for await (const event of query({ messages: [ { type: 'user', message: { role: 'user', content: 'Read the README.md file' } } ], systemPrompt: asSystemPrompt(['You are Claude Code...']), userContext: { claudeMd: 'Project-specific context...' }, systemContext: { cwd: '/project', platform: 'darwin' }, canUseTool, toolUseContext, querySource: 'repl', maxTurns: 10, // Limit agentic loops })) { if (event.type === 'assistant') { // Handle assistant message (may contain tool_use blocks) console.log('Assistant:', event.message.content) } else if (event.type === 'stream_event') { // Handle streaming deltas if (event.event.type === 'content_block_delta') { process.stdout.write(event.event.delta.text || '') } } else if (event.type === 'user') { // Tool results injected as user messages } } ``` Claude Code provides a comprehensive framework for building AI-powered coding assistants with robust tool management, permission systems, and multi-agent orchestration. The architecture supports both interactive CLI usage and programmatic SDK integration through structured tool interfaces, streaming responses, and extensible MCP server connections. Key integration patterns include using the `buildTool` helper for creating new tools with proper defaults, implementing permission checks for sensitive operations, leveraging the agent system for parallelizable tasks, and connecting external capabilities via MCP. The codebase demonstrates production-grade patterns for handling file system operations, process execution, and user interaction in an AI coding assistant context.