In-depth Analysis of Alibaba Cloud's Claude Code: The Core Architecture of a Top AI Programming Tool

Wallstreetcn
2025.08.29 02:35
portai
I'm PortAI, I can summarize articles.

Claude Code is an AI programming tool developed by Anthropic, designed to help developers efficiently complete coding, debugging, and project management through natural language instructions. It is integrated into the developer's work environment without the need for additional servers or complex configurations. The article provides a detailed introduction to the design patterns, system architecture, and interaction layers of Claude Code, including components such as the REPL interface, input processor, and output renderer

1. Introduction to Claude Code

Claude Code is a new terminal AI programming tool developed by Anthropic, designed to help developers efficiently complete coding, debugging, and project management tasks through natural language instructions. It is directly integrated into the developer's work environment (such as the terminal) and can run without relying on additional servers or complex configurations.

In practical use, Claude Code is a relatively general-purpose agent, and the code it outputs is much more concise than that of cursor, resembling a senior programmer familiar with the entire project. Studying and learning this framework is crucial for developing one's own Agent. This article will detail the design patterns and core code of Claude Code.

2. Detailed Introduction

2.1 System Architecture

2.2 Execution Process

2.3 Interaction Layer

The interaction layer is the point of contact between the user and Claude Code, typically including:

  • REPL interface: Provides a command-line interaction experience;
  • Input processor: Parses user instructions and supports multiple input modes (natural language, commands, code, etc.);
  • Output renderer: Formats and displays AI responses and tool execution results;

In ClaudeX, this layer is mainly implemented by components such as REPL.tsx and PromptInput.tsx, which are responsible for receiving user input and displaying results.

2.3.1 Input Logic Processing

Input Logic Processing

2.3.2 Rendering

  • Stages

  • Tool Invocation Stage (Assistant Side): Displays tool name, parameters, and execution status;

  • Tool Result Stage (User Side): Displays execution results;

  • Components

  • AssistantToolUseMessage: Renders messages when the assistant calls a tool;

  • Displays tool name (via tool.userFacingName());

  • Displays parameters (via tool.renderToolUseMessage());

  • Uses ToolUseLoader to show execution status animation;

  • UserToolSuccessMessage:

  • The result after the rendering tool executes successfully;

  • Call tool.renderToolResultMessage() to render specific content;

  • Tool Interface Definition

  • userFacingName() The name of the tool displayed to the user;

  • renderToolUseMessage(input, options) Render tool parameters;

  • renderToolResultMessage(output, options) Render tool results;

  • renderToolUseRejectedMessage() Render rejection message;

  • UI Rendering Features

  • Build terminal UI using Box and Text components from the Ink framework;

  • Support for a theme system (via getTheme());

  • Responsive layout (flexDirection, justifyContent);

  • Detailed/concise mode switching (verbose parameter);

  • Display of execution cost and time (Cost component);

2.4 Core Engine

The core engine is the "brain" of Claude Code, responsible for coordinating the work of various components:

  • Messaging System: Manages the flow of messages for user input, AI responses, and tool results;
  • Query Engine: Interacts with the AI model, sends requests, and processes responses;
  • Tool Scheduler: Coordinates the invocation of tools and result processing;

In ClaudeX, query.ts is a key component of the core engine, implementing the logic for interacting with the AI model:

query.ts

2.5 Tools

The tool system is the "hands and feet" of Claude Code, enabling it to interact with the external environment:

  • File Tools: Read, write, and search files;
  • Execution Tools: Run shell commands, execute code;
  • Analysis Tools: Code analysis, dependency checks, etc.;
  • Meta Tools: Composite tools that can perform more complex tasks;

Each tool follows a unified interface, including name, description, parameter patterns, and execution logic:

Tools are also the core assets of the entire Claude Code. The effectiveness of this CLI is not only due to the powerful model but also because of the strong tools available, such as a particularly powerful bash tool that can invoke all commands in the shell, as well as an agent tool that can exert even greater capabilities. We will conduct a separate analysis of the tools in subsequent articles.

2.6 Context Management

Context management is the "memory" of Claude Code, responsible for collecting and organizing code-related information:

  • Project structure: directory and file structure
  • Code content: content of key files
  • Version control: Git history and status
  • Configuration information: project configuration and dependencies

The challenge of context management lies in how to provide the most relevant information within a limited context window:

  • LRU caching mechanism: caching information such as file encoding and line ending types to reduce repetitive operations.

File caching

  • On-demand loading strategy: not loading the entire codebase at once, but intelligently loading relevant files based on query needs.

GlobTool.tsx

  • Result truncation handling: intelligently truncating a large number of search results to avoid context overflow while providing clear truncation prompts.

lsTool.tsx

  • Assembling context

Context assembly

2.7 Security

Security and permissions are the "guardrails" of Claude Code, ensuring the safety of tool usage:

  • Permission verification: permission checks before tool execution;
  • User confirmation: user confirmation mechanism for critical operations. Using the principle of least privilege, only requesting the minimum permissions necessary to complete the task;
  • Security boundaries: restrictions on file operations and command execution;

permission.ts

3. Some Insights

3.1 Binary Feedback Mechanism for Programmer Testing Prompts

query.ts

Using the exact same request twice may be to observe whether the same input to the model yields two outputs. If the AI returns two answers, it indicates that the model is hesitant about this request and is unclear, requiring the user to make a choice.

Here, the detection of outputs is not about checking the text but rather about verifying whether the generated tool use is the same. The stability of structured data output is far greater than that of text output. Text comparison is only done when there is no tool use.

It is also noted that this code only takes effect when the programmer tests it themselves, indicating that such testing logic is quite useful for developing their own agent. The occurrence of this situation suggests that you need to improve the quality of your prompts.

3.2 MCP Tools

The entire Claude Code itself only maintains one tengu_mcp_server while supporting users to add MCP Servers. Claude Code manages users' MCP tools through a three-tier hierarchical structure:

  • global: General MCP with global configuration
  • MCPrc: Configuration files that can be shared
  • project: Project-level, meaning the current codebase can be configured separately

The MCP configuration at the lower level can override the MCP configuration at the upper level.

Adding MCP Server

How to obtain tools from multiple MCP Servers, request all MCP Servers, gather all tools, and send the aggregated tools to the large model.

getMCPTools

3.3 Detecting Security through AI

Utilizing AI for security assistance. For example, determining whether commands are susceptible to injection.

Determining whether commands are susceptible to injection

3.4 Context Compression Processing

Core function: Clear conversation history while retaining a context summary, addressing the context window issue caused by long conversations.

Technical highlights:

  1. Intelligent summary generation: Using the Sonnet model to generate conversation summaries, retaining key information for future use;

  2. Fork mechanism application: Utilizing setForkConvoWithMessagesOnTheNextRender to create new conversation branches, with the summary serving as the starting point for the new conversation;

  3. Token usage optimization: Setting the token usage for the summary to 0 to avoid triggering context window warnings;

  4. Cache clearing: Clearing getContext and getCodeStyle caches to ensure a clean new conversation environment;

Core code flow:

  1. Retrieve current conversation history

  2. Construct summary request and call the Sonnet model

  3. Extract and validate summary content

  4. Clear screen, clear message history

  5. Create a new conversation branch containing the summary

3.5 Simple Tasks Assigned to Small Models

Claude internally has several model instances. For tasks that only require determining correctness or are simple, they will be assigned to the haiku model.

queryHaiku

3.6 Efficient File System Strategy

  • Layered code project pulling, first obtaining the high-level project structure, then delving into specific directories as needed, avoiding loading too much content at once;
  • Ripgrep integration: Utilizing the high-performance search tool ripgrep, written in Rust, to achieve millisecond-level codebase searches;
  • Built-in binary support: Including precompiled ripgrep binary files to ensure cross-platform consistency and performance;
  • Intelligent result sorting: Search results sorted by modification time, prioritizing recently changed files to enhance relevance;
  • Concurrent search capability: Supporting multiple search requests simultaneously, significantly improving analysis efficiency for large codebases;
  • LRU caching mechanism: Caching information such as file encoding and line ending types to reduce repetitive operations; 3.7 Ingenious Tools

The implementation and prompts of the 15 built-in tools in Claude Code are worth studying repeatedly, as these exceptional tools enable efficient task execution.

Four, Easter Eggs

Five, iFlow CLI

With the explosive popularity of Claude Code, we have found that this product genuinely enhances programmers' development efficiency. We have also continuously tracked the upgrade progress of Claude Code for two months, helping many students use Claude Code in domestic environments. As Cursor and Claude Code have intensified control over domestic IPs, using such cutting-edge tools has become quite challenging. However, the past month has brought many surprises: domestic large models such as Kimi K2, Qwen3-Coder, and GLM-4.5 have emerged one after another, and Gemini CLI has also announced open-source. Domestic programming tools are continuously breaking through and innovating, aiming to create a more intelligent and efficient ultimate development experience for domestic developers.

The Flow team has been exploring the path to AGI, and we have been searching for the technical architecture and product form of the most universal AI assistant. The emergence of CLI + MCP makes us feel that this might be our path to achieving AGI. Therefore, we are proud to introduce our latest developed CLI tool, iFlow CLI 2.0.

It is based on Gemini CLI and we have spent some time refining it, integrating some features of Claude Code.

  • Supports 4 running modes: yolo (model has maximum permissions and can perform any operation), accepting edits (model only has permission to modify files), plan mode (plan before execution), default (model has no permissions);
  • Upgraded subAgent functionality. This allows the CLI to evolve from a general assistant to an expert team, providing you with more professional and accurate advice. Using /agent will show more pre-configured agents;
  • Upgraded task tool. Effectively compresses context length, allowing the CLI to delve deeper into completing your tasks, automatically compressing when the context reaches 70%;
  • Access the Flow Open Market. Quickly install the user-friendly MCP tools, Subagent, and custom commands. You can learn more through /mcp;
  • Free use of multimodal models, and you can now paste images in the CLI (Ctrl+V to paste images);
  • Supports saving and rolling back historical conversations (iflow --resume and /chat commands);
  • Supports more and better terminal commands (iflow -h to see more commands);
  • Supports VSCode and Jetbrains plugins (note the corresponding version number of the IDE);
  • Automatic upgrades, no more worries about missing out on the latest features;

5.1 One-click Installation

mac/linux/ubuntu Users

Users who have already installed can execute this script again to update, and the CLI will automatically update in the future.

Windows Users

  1. Visit https://nodejs.org/zh-cn/download to download the latest Node.js installer;

  2. Run the installer to install Node.js;

  3. Restart the terminal: CMD or PowerShell;

  4. Run npm install -g @iflow-ai/iflow-cli to install iFlow CLI;

  5. Run iflow to start iFlow CLI;

5.2 Install SubAgent and MCP Tools from the Open Market

The CLI is incomplete without MCP and Subagent; adding MCP and Subagent will turn the CLI into a domain expert! For many novice users, the operation is really too difficult!

The Flow Open Market helps you solve this ???? Experience it now: https://platform.iflow.cn/cli

MCP Open Market, one-click installation, unlock efficient tools.

Agent Open Market, one-click installation of Subagent, introducing more powerful expert agents.

Copy the installation command! Execute it in the terminal! One-click installation experience for MCP and Subagent!

6. What Can CLI Really Do

6.1 Familiarize with the Project, Write Code, Debug

This is the strength of CLI. Enter your project, open iFlow CLI, and ask it about any unfamiliar functions; clearly describe the business you need to implement and let CLI help you achieve it; if you encounter an error, paste the error message to CLI and let it help you solve it.

6.2 Build Websites

Use local private data to create your own reporting website.

6.3 DeepResearch

6.4 Introduce Sub Agents to Implement Business Logic

Product Requirement Document -> Requirement Processing Agent -> UI Design Agent -> UI Optimization Agent -> Code Logic Development Agent -> Interface Integration Agent -> Unit Testing Agent

Author of this article: Mao Dao, Source: Alibaba Cloud Developer, Original Title: "Deep Breakdown of Claude Code: The Core Architecture of a Top AI Programming Tool"

Risk Warning and Disclaimer

The market has risks, and investment requires caution. This article does not constitute personal investment advice and does not take into account the specific investment goals, financial conditions, or needs of individual users. Users should consider whether any opinions, views, or conclusions in this article are suitable for their specific circumstances. Invest at your own risk