Zero Labs
Industry News / AI

Claude Code Under the Hood: How Context, Tokens, Tools and Subagents Work

Source · Towards AI By Sudha Subramaniam

From the publisher’s feed, collected in the ZeroLabs newsroom.

What actually happens when Claude Code analyzes a repository, generates tests, edits files, runs commands and keeps working?When Claude Code takes on a coding task, the experience can look deceptively simple.You give it a task. It explores the code, edits files, runs commands, sees the results, and keeps going.For exampleAnalyze this Spring Boot repository, identify the technology stack, generate JUnit 5 tests for BookingService, run the tests, fix any failures, and prepare the changes for reviewTo a developer, that sounds like one task.But behind that single request is a much more interesting process.Claude Code needs to determine what it needs to know, discover the relevant files, understand the instructions that apply, decide which tools to use, execute commands, interpret their results, and determine what to do next.It isn’t simply a matter of sending the entire repository to the model and asking it to start coding.Instead, the work happens through a continuous interaction between context, model inference, tools, tool results, and subsequent decisions.And that raises some important questionsDoes Claude Code actually read the entire repository?Which files enter the model’s context — and when?How do CLAUDE.md, Rules, and Skills influence that context and behavior?How does token usage grow during a long-running task?What happens when the context becomes too large?What changes when work is delegated to a subagent?Where do MCP tools, Hooks, and permissions fit into the execution loop?The answers reveal something important about AI coding agents: the code change you see is only the visible outcome of a much larger execution loop.This article follows that loop under the hood — from the initial prompt and context assembly to model inference, tool execution, results, iteration, and subagent delegation.This article looks at Claude Code under the hood to answer those questions.The goal is not to explain how to use Claude Code.The goal is to understand how the system works while it is working.For an agent, it is a chain of smaller decisionsClaude Code is therefore more than a model that writes code in a terminal. The interesting part is the system around the model: how it gathers context, chooses tools, manages state, delegates work, executes commands and reacts to what happens next.Anthropic describes this style of agent as a model working with tools in a loop, while its context-engineering guidance focuses on continuously curating the information available to the model as the task progresses.That is what makes Claude Code worth examining under the hood.The first question: does Claude Code read the whole repository?This is probably the first question an architect or senior developer will ask.Suppose you have a repository with5 million lines of codethousands of filesmultiple modulesJava + Spring BootAngularDockerKubernetesTerraformCI/CDAnalyze the repository and tell me the technology stack.Does Claude Code read every file and put everything into the context window?Not necessarily. This is one of the most important ideas behind agentic coding.Anthropic explicitly describes Claude Code as using a hybrid context strategy. Project instructions such as CLAUDE.md can be loaded up front, while tools such as file search and shell commands allow Claude to retrieve additional information just in time as the task requires it. Anthropic uses Claude Code itself as an example of navigating large environments without loading the entire environment into context.So the better mental model isHow big is my repository?It isWhich parts of the repository did Claude actually retrieve for this task?That is a much more useful way to think about context.Context is a working set, not a database dumpAnthropic describes context as the set of tokens available to the model during an inference. For agents, that context can include system instructions, tools, MCP, external data, message history and information retrieved during the task.In Claude Code, that working context can evolve into something likeSystem instructions +Project instructions +Current prompt +Previous conversation +Relevant files +Tool results +MCP results +Test failures+Other state needed for the next decisionAnd it changes over time. At the beginning of a task, Claude may know very little about the repository.After several searches, it knows more. After reading a few source files, it knows more again.After running a test, the test output becomes part of the information available for the next step.After compaction, some earlier history can be summarized rather than carried forward in full.After delegating to a subagent, the main agent can receive a result rather than the entire exploration that produced it.That is why context engineering has become such an important part of agent architecture.Claude Code loads context in layersClaude Code’s current architecture gives us a useful way to think about where information comes from.Anthropic’s current documentation describes these features as different ways of extending Claude Code, with different implications for when information enters the agent’s workflow.A useful mental model from the material you provided is to separate them into knowledge and workers: CLAUDE.md and Skills influence what Claude knows, while subagents and Agent Teams perform work in separate contexts.That distinction becomes particularly important when we start talking about tokens.CLAUDE.md: the always-on layerLet’s start with the simplest piece.Anthropic positions CLAUDE.md as the place for persistent project instructions: coding conventions, repository structure, build commands, testing conventions and other guidance Claude should consistently follow.For exampleUse Maven, not Gradle.Run unit tests with:./mvnw testUse JUnit 5 and Mockito.Do not modify src/legacy.Use constructor injection.Follow existing exception-handling patterns.This information is different from the user’s current prompt.The prompt could be Generate tests for BookingServiceCLAUDE.md can tell Claude how this repository expects those tests to be written.Why CLAUDE.md is also a token decisionThere is a subtle point here that is easy to miss.CLAUDE.md is intended for information that should remain relevant throughout the session.That means it becomes part of the context repeatedly.Anthropic’s guidance recommends keeping CLAUDE.md focused rather than turning it into a giant repository manual.This creates a simple engineering rule:Put something in CLAUDE.md when Claude should know it for most tasks.Don’t put every possible document, procedure and reference there simply because you can.Rules: context that becomes relevant at the right placeClaude Code also supports path-specific rules.Imagine a monorepo with different conventionssrc/test/**src/security/**src/legacy/**A rule can apply only when Claude is working in the relevant part of the repository.That gives us a more layered structureThe idea is simple,not every piece of project knowledge belongs in every request. That becomes especially important as repositories become larger.Skills: knowledge loaded when the task needs itNow suppose your team has a detailed testing procedureSpring Boot testing conventionsMockito patternsTest naming rulesCoverage expectationsTest-data buildersMock verification rulesYou could put all of that into CLAUDE.md. But then every unrelated request would carry it too. Claude Code Skills provide another option- reusable knowledge and workflows that can be discovered and loaded when relevant. Anthropic documents Skills as a mechanism for reusable instructions and resources, with the full Skill content loaded when the Skill is used.For exampleSkill: spring-boot-testing │ ├── JUnit conventions ├── Mockito conventions ├── test naming ├── coverage rules └── supporting referencesThe full testing procedure does not need to occupy the context of every coding task.This is progressive disclosure.And progressive disclosure is one of the recurring ideas in agent design: start with a small amount of information, then reveal more when the task actually needs it.MCP: context and capabilities can come from outside the repositoryA repository is not always enough.A real development workflow might also depend on Jira, internal APIs, databases, documentation systems or other services.Claude Code supports MCP servers for connecting the agent to external tools and data. Anthropic’s current documentation also describes techniques for limiting unnecessary tool-schema context until a tool is actually needed.The flow becomesBut there is another implication.An MCP tool can return information. That information can then become part of the agent’s working context.MCP tool ↓External system ↓Tool response ↓Claude context ↓Next decisionSo MCP is not only an integration mechanism. It can also become another source of context.Now the agent loopLet’s take the concrete exampleGenerate JUnit 5 tests for BookingServiceClaude Code can begin by locating the target and inspecting what matters around it. The flow can look likeAnthropic describes this kind of just-in-time retrieval as a core technique for agents operating in large environments.The important point is that repository exploration becomes part of the task.So how many tokens does the JUnit task use?There is no fixed number.Anthropic does not publish a rule such asGenerating JUnit tests for a Spring Boot service costs 40,000 tokensAnd it would be misleading to invent one.Claude Code’s current usage documentation says each turn includes the conversation so far, project context such as CLAUDE.md and files Claude has read, and the new prompt. Claude Code also provides /context and /cost for inspecting the current context and session usage.So the input to a later turn is more likeTurn N input =Conversation state+Project context+Retrieved files+Tool results+Current promptThen Claude produces output and possibly requests tools. Those tools return results. Those results become new information for the next decision.The cycle continues.Token usage follows the whole trajectorySuppose the task requires six steps:1. Find service2. Inspect dependencies3. Inspect existing tests4. Generate tests5. Run tests6. Fix failuresThe token consumption isn’t simply -files read × one model callEach step can build on the previous one.this can be viewed asThis is why a coding-agent session can use substantially more tokens than the original prompt would suggest.Anthropic’s usage guidance explicitly notes that Claude Code can be more token-intensive because coding sessions include system prompts, file context, tool calls and multi-turn work.Context window and token usage are not the same thingA context window tells you how much information the model can work with at once.Token usage tells you how much input and output processing occurs over the work.Current Claude documentation lists context windows up to 1 million tokens for supported Claude models in Claude Code, depending on model and account configuration.That does not mean ,Claude loads one million tokens every timeIt means the model can support that amount of working context when applicable.A five-million-token repository can therefore be larger than the model’s context window without forcing the system to load all five million tokens at once.The agent can retrieve information progressively.Claude Code lets you see part of this yourselfFor engineers, this is where things become practical,Claude Code provides /context to inspect the current context and /cost to inspect session token and spend information when using API billing./context — gives you — What is currently occupying my working context?and /cost — gives you — What did this session consume?That distinction is important because the current context and cumulative session usage are not the same measurement.Prompt caching changes repeated-input costAnother subtle part of the picture is caching.Anthropic documents prompt caching for Claude Code and specifically discusses caching of CLAUDE.md. The first request pays the normal input-token rate for the content; subsequent requests can reuse the cached prefix at a lower cache-read rate during the cache lifetime.So we have another distinction ,Caching can reduce the cost of sending repeated context. It does not mean the context is no longer part of the model’s working input.What happens when the conversation becomes too large?Now imagine Claude has been working for a while. It hasread 30 filesedited 12 filesrun tests several timesseen compiler errorsfixed failuresreviewed diffsThe conversation is getting large.Claude Code supports automatic and manual compaction. Anthropic describes compaction as summarizing the conversation while preserving important state so the task can continue without carrying the entire history forward indefinitely.Large context │ ▼ Compaction │ ├── Preserve decisions ├── Preserve unresolved issues ├── Preserve implementation state └── Reduce redundant history │ ▼Smaller working context │ ▼Continue taskThis is an important part of long-running agents. The system is not simply accumulating more and more text forever. It is managing a changing working set.Subagents: when the main context should not do all the workNow consider a broader requestAnalyze how authentication is implemented across this repositoryClaude could do all the exploration itself.But if that exploration touches dozens of files, a lot of intermediate information could accumulate in the main conversation.This is where subagents become useful.Anthropic documents subagents as separate Claude instances that run with their own context window and return their results to the calling agent. They can have their own system instructions, tools and Skills.The subagent can perform the investigation without forcing the entire exploration history into the main session.Anthropic’s context-engineering guidance specifically describes subagents as a way to isolate large explorations and return a smaller distilled result.A subagent protects the main context — it doesn’t make the work freeThis is an important distinction. Imagine an exploration takes a large amount of internal context.Without a subagentMain agent │ └── large exploration ↓ large main contextWith a subagentMain agent │ └── Explorer │ own context │ summary │ ▼ Main agentThe second architecture protects the main context.But the subagent still consumes its own input and output tokens.Anthropic’s context-engineering research gives an example in which a subagent may use tens of thousands of tokens or more during deep exploration and then return a much smaller distilled result to the coordinating agent.So , Context isolation and token reduction are related, but they are not the same thing.This is why subagents are useful for large-repository analysisSuppose the task is Analyze the entire repository and give me the technology stackA large repository is a poor fit for one giant context. A more scalable architecture can split the investigation.One worker can focus on Java and Spring dependencies. Another can investigate frontend tooling. Another can inspect Kubernetes, Docker or infrastructure. Each worker can retrieve the evidence relevant to its own task and return structured findings. The main agent then synthesizes those results. Claude Code’s current documentation also describes dynamic workflows for large tasks that can use multiple agents to inspect and cross-check a codebase.Agent Teams are a different level of collaborationClaude Code also has Agent Teams, but they should not be confused with ordinary subagents.A subagent typically looks likeMain Agent │ ├── Worker A ├── Worker B └── Worker CWorkers return results to main agent ,An Agent Team looks more likeTeam Lead │ ┌──────────┼──────────┐ ▼ ▼ ▼ Worker A Worker B Worker C ↕ ↕ ↕ direct peer communicationAnthropic documents Agent Teams as multiple independent Claude Code sessions with their own context windows, shared task coordination and direct communication between teammates. Anthropic also notes that they use significantly more tokens than a single session and are currently experimental.That gives us a practical distinctionFor generating JUnit tests for one service, a full Agent Team would usually be unnecessary.For a large migration involving frontend, backend, infrastructure and testing, it becomes a different architectural choice.Skills can also be isolated from the main conversationClaude Code also supports Skills that can execute in a forked context.Anthropic documents context: fork as a way for a task-oriented Skill to run in a separate context instead of using the main conversation. Again, the point is context control.Hooks(PreToolUse ,PostToolUse) are different from SkillsAnother distinction becomes important here. A Skill provides knowledge or a workflow. A Hook performs a deterministic action at a lifecycle event.Anthropic documents hooks such as PreToolUse, PostToolUse and session-related hooks. They can execute commands or other actions without requiring the model itself to reason through the procedure. Hook output becomes relevant to the conversation only when the hook returns information for Claude to use.For exampleAnthropic also documents a pattern where hooks can run tests and prevent Claude from stopping while failures remain.This gives the agent architecture another useful separationSkill -What should Claude know or do?Hook -What should the system automatically executed?A failing test becomes new contextNow return to the JUnit example. Claude generates a test. It executes./mvnw test — The build fails ,The failure becomes part of the next decisionThis is the essence of the agent loop. Claude is not reasoning only from the original prompt. It is reasoning from the current state of the environment.Anthropic’s context-engineering guidance explicitly treats tool results and environment feedback as inputs that can be brought into subsequent model calls. This is where an agent becomes more than a code generator.It can observe → act → observe again.Permissions sit between the model and executionOnce an agent can edit files and execute commands, another layer becomes necessaryWhat is it actually allowed to do?Claude Code has permission controls around tool execution. Anthropic’s Auto Mode adds additional defenses, including a prompt-injection probe for tool results and an action classifier that evaluates potentially risky operations before execution.Put the entire flow togetherNow the architecture behind the original Spring Boot request is much clearer , This is what sits behind what looks like a simple coding request.So, does Claude Code read every file for JUnit generation?The technically careful answer is No, that is not a default requirement.Claude Code can retrieve files incrementally as the task requires them. For a narrow request such as generating JUnit tests for one Spring Boot service, the useful context may begin with the target class, relevant dependencies, existing test patterns and build configuration. If execution reveals missing information, the agent can expand its investigation. Anthropic explicitly describes this just-in-time retrieval strategy.But there is an equally important second halfClaude can read much more if the task requires broader understanding.CompareGenerate JUnit tests for BookingServicewithAnalyze the entire repository and identify every framework, library, database, messaging technology and deployment platformThe second task naturally requires much broader repository exploration.There is no official Anthropic rule saying “JUnit tasks always read X files” or “repository analysis always reads Y% of the repository.”The actual path is task-dependent.And how many tokens does that use?Again, there is no single number. Token usage depends on the agent’s actual trajectoryAnthropic provides /context to inspect the current working context and /cost to inspect session usage when API billing is used.So a better question thanHow many tokens does Claude need for a JUnit task?isWhat information entered the context, how many model/tool iterations were required, and how much work was delegated?That is the measurement that actually explains the behavior.Final takeawayThe important change in AI-assisted software development is not simply that Claude can generate more code.It is that Claude Code has become a system for managing context, tools, execution and feedback over time.A large repository does not automatically become one giant prompt.A JUnit task does not automatically require every Java file to be read.A Skill does not need to occupy the context when it is irrelevant.A large investigation does not have to consume the main conversation’s entire context.A subagent can explore independently and return a distilled result.A long-running session can be compacted.A Hook can trigger deterministic validation.A permission layer can sit between an action proposed by the model and actual execution.And a failed test can become new evidence for the next iteration.That is what makes Claude Code different from a simple code-generation assistant.Claude Code Under the Hood: How Context, Tokens, Tools and Subagents Work was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.