}

Claude Code: Complete Terminal AI Agent Guide (2026)

Claude Code: Complete Terminal AI Agent Guide (2026)

Claude Code is Anthropic's terminal-first agentic coding tool. Unlike IDE plugins that augment an existing editor, Claude Code operates directly in your shell: it reads your codebase, edits files, runs commands, fixes test failures, and iterates — all from a single claude invocation. In benchmark evaluations in 2026, Claude Code ranks at the top of the state-of-the-art for coding tasks, outperforming competing tools on repository-level refactors, bug localization, and test generation. This guide covers everything from installation to advanced CI/CD integration.


What Is Claude Code?

Claude Code is an agentic coding assistant that lives in the terminal. Its core design principle is that the terminal is where real work happens: where you run tests, inspect logs, read diffs, and push commits. By meeting developers in that environment rather than asking them to switch to a GUI, Claude Code fits into existing workflows without friction.

Key characteristics: - Terminal-first: runs in any shell, on any machine, including remote servers and CI runners. - Agentic by default: it does not just suggest code — it reads files, writes files, runs commands, and loops until the task is complete. - Context-aware: it indexes your repository and understands the relationships between files. - Permission-controlled: every potentially risky action (deleting a file, running a migration) requires explicit approval unless you configure auto-approval.

Claude Code is built on Anthropic's Claude family of models. The default model in 2026 is claude-sonnet-4-5, with options to switch to claude-haiku-4-5 for faster/cheaper tasks or claude-opus-4-5 for the most complex reasoning.


Installation

Claude Code is distributed as an npm package. You need Node.js 18 or later. Check your version:

node --version
# v18.0.0 or higher required

Install Claude Code globally:

npm install -g @anthropic-ai/claude-code

Verify the installation:

claude --version

Run the built-in health check to confirm that all dependencies are present and the network can reach the Anthropic API:

claude doctor

claude doctor checks Node.js version, API connectivity, authentication status, and the current model configuration. If any check fails, it prints a specific error message with a suggested fix.


Authentication

Claude Code authenticates against the Anthropic API. You can authenticate in two ways.

Option 1: Anthropic Account (Recommended)

Run the interactive login flow:

claude auth login

This opens a browser tab where you sign in to your Anthropic account. After signing in, an API key is written automatically to ~/.claude/auth.json. No manual key management required.

Option 2: API Key Environment Variable

If you are setting up a CI runner or a server where browser auth is not available, set the key as an environment variable:

export ANTHROPIC_API_KEY=sk-ant-...

Add this to your shell profile (.bashrc, .zshrc) or your CI secrets store. Claude Code reads this variable automatically on startup.

Confirm authentication is working:

claude doctor
# ✓ Authentication: valid (account: your@email.com)

Core Usage

Interactive Mode

Running claude with no arguments starts an interactive session:

cd /path/to/your/project
claude

Claude Code indexes your repository and presents a prompt. Type your request in natural language and press Enter. It will read relevant files, plan a sequence of actions, and execute them — pausing to ask for approval before any write or shell operation (in the default permission mode).

Interactive mode is best for exploratory tasks where you want to guide the agent, ask follow-up questions, and iterate in real time.

One-Shot Mode

For scripted or repeatable tasks, use the -p flag to pass a prompt directly:

claude -p "Fix the failing test in tests/test_auth.py and explain what was wrong"

Claude Code runs the task, prints its actions and reasoning to stdout, and exits. One-shot mode is the basis of CI/CD integration.

Piping Input

Claude Code reads from stdin, which lets you pipe logs, error messages, or any text directly into the agent:

cat error.log | claude "Diagnose this error and suggest a fix"
pytest 2>&1 | claude "Fix the failing tests"
git diff HEAD~1 | claude "Write a clear commit message for these changes"

This pipe-based interface makes Claude Code a composable Unix tool: it fits naturally into existing shell scripts and Makefiles.


CLAUDE.md: Project-Level Instructions

CLAUDE.md is the most important configuration file for Claude Code. Place it at the root of your repository. Claude Code reads it at the start of every session and injects its contents into the agent's context. All subagents and CI runs also read it automatically.

Think of CLAUDE.md as the onboarding document you would give a new developer — except the audience is an AI that will read every word before touching your code.

What to Include

# Project Overview
This is a multi-tenant SaaS application built with FastAPI (Python 3.12),
PostgreSQL 16, and React 18. The backend is in `src/`, the frontend in `web/`.

# Tech Stack
- Backend: FastAPI, SQLAlchemy 2.x ORM, Alembic for migrations, Pydantic v2
- Frontend: React 18, TypeScript 5, Vite, Tailwind CSS
- Testing: pytest (backend), Vitest (frontend)
- CI: GitHub Actions

# Conventions
- Never write raw SQL. Use SQLAlchemy ORM.
- All API endpoints must have at least one pytest in tests/api/.
- Error responses use the ErrorResponse Pydantic model in src/models/errors.py.
- Generate migrations with: alembic revision --autogenerate -m "description"
- Commit messages follow Conventional Commits (feat:, fix:, chore:, docs:).

# What NOT to Change
- Do not modify alembic/versions/ files by hand.
- Do not change pyproject.toml dependency versions without asking first.
- The web/src/generated/ directory is auto-generated. Do not edit it.

How It Persists

CLAUDE.md is committed to your repository. Every team member and every CI run gets the same instructions. You do not need per-developer configuration. When your conventions change, update CLAUDE.md and commit — Claude Code will follow the new rules from that point forward.


Agentic Mode in Practice

In agentic mode (the default), Claude Code does not wait for you to tell it which files to open. It explores the codebase autonomously:

  1. It reads CLAUDE.md and any relevant configuration files.
  2. It searches for files related to the task (using file path search and grep-style content search).
  3. It reads those files to understand the existing code.
  4. It plans a sequence of edits.
  5. It executes the edits, runs tests, inspects failures, and iterates.

Example session:

$ claude -p "The /api/users/me endpoint returns a 500 when the user has no profile. Fix it and add a regression test."

Reading CLAUDE.md...
Searching for /api/users/me handler...
Reading src/api/routes/users.py...
Reading src/models/user.py...
Reading tests/api/test_users.py...

Found issue: UserProfile.objects.get() raises DoesNotExist when profile is missing.
Plan:
  1. Wrap the query in a try/except and return a 200 with profile=null
  2. Add test_get_me_no_profile to tests/api/test_users.py

Editing src/api/routes/users.py... done.
Editing tests/api/test_users.py... done.
Running pytest tests/api/test_users.py...

3 passed in 0.8s.
Task complete.

Claude Code ran, fixed, tested, and verified — without a single manual file open.


Key Commands Reference

Session Management

Flag / Command Effect
claude --continue Resume the most recent session, including full conversation history
claude --resume <session-id> Resume a specific past session by ID
/compact Summarize the conversation history to reduce token usage while keeping context
/clear Wipe the current conversation and start fresh in the same directory
/model claude-haiku-4-5 Switch models mid-session

Useful Flags

# Set the model for a one-shot run
claude -p "..." --model claude-opus-4-5

# Run without the confirmation prompt (auto-approve safe operations)
claude -p "..." --auto-approve

# Limit the number of agentic steps (useful in CI to prevent runaway loops)
claude -p "..." --max-turns 20

# Output only the final answer, suppress intermediate logs
claude -p "..." --quiet

Subagents: Specialized Instances for Complex Tasks

Claude Code can spawn subagents — separate Claude instances with their own context windows — to handle distinct sub-problems in parallel or in sequence. This is useful when a task is too large for a single context window or when different parts of the task require different expertise.

Common uses: - Code review subagent: spawn a subagent whose only job is to critique the changes made by the main agent. - Debugging subagent: isolate a failing test in its own context so the main agent's context stays clean. - Domain expert subagent: give a subagent a focused system prompt (e.g., "You are a database optimization expert") and route only the schema-related questions to it.

In interactive mode, you can direct Claude Code to use a subagent:

> Spawn a subagent to review the changes in src/api/ for security issues while you continue writing tests.

Claude Code will start a subagent session, report its findings back to the main session, and incorporate the feedback.

For programmatic use, the Claude Code SDK (available as an npm package @anthropic-ai/claude-code-sdk) exposes a spawnSubagent() API that lets you orchestrate multi-agent workflows from TypeScript or JavaScript.


MCP Integration: Connect External Tools

Claude Code supports the Model Context Protocol (MCP), the open standard for connecting AI agents to external systems. MCP servers expose tools that Claude Code can call during a task — querying a database, opening a GitHub issue, fetching a Jira ticket.

Configure MCP servers in .claude/mcp.json at the project root:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_URL": "${DATABASE_URL}"
      }
    },
    "jira": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-jira"],
      "env": {
        "JIRA_URL": "${JIRA_URL}",
        "JIRA_TOKEN": "${JIRA_TOKEN}"
      }
    }
  }
}

With these configured, Claude Code can: - Look up the requirements in a Jira ticket before writing code. - Query the live database schema to generate accurate migrations. - Create a GitHub branch, push commits, and open a pull request — all in one agentic run.

MCP servers run as local processes. They communicate with Claude Code over a local socket; your credentials never leave your machine.


Permission Model

Claude Code uses a layered permission model that controls which actions the agent can take without asking.

Manual Approval (Default)

Every file write, shell command, and external API call requires you to type y or n. This is the safest mode and the right starting point when you are exploring what Claude Code does.

Auto-Approve

Pass --auto-approve to approve all actions automatically. Claude Code has built-in classifiers that tag actions as "safe" (reading files, running tests) or "risky" (deleting files, running database migrations, making HTTP requests to external services). In auto-approve mode, safe actions run without prompting; risky actions still require confirmation unless you also pass --auto-approve-risky.

Allowlist / Blocklist

For fine-grained control, define an allowlist in .claude/permissions.json:

{
  "allow": [
    "read:*",
    "write:src/**",
    "write:tests/**",
    "shell:pytest *",
    "shell:alembic *"
  ],
  "block": [
    "shell:rm *",
    "shell:curl *",
    "write:alembic/versions/**"
  ]
}

This configuration lets Claude Code read any file, write to src/ and tests/, run pytest and alembic, but blocks it from deleting files, making network requests, or hand-editing migration files.


CI/CD Integration

Running Claude Code in CI turns it into an automated code quality and fix layer that runs on every pull request.

GitHub Actions Example

name: Claude Code Fix

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  claude-fix:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run tests and fix failures
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          pytest 2>&1 | claude -p "Fix any failing tests. Commit the fixes." \
            --auto-approve \
            --max-turns 15

Pipe Logs Into Claude Code

The pipe interface works especially well in CI where you have structured log output:

# Fix linting errors automatically
ruff check . 2>&1 | claude -p "Fix all linting errors reported by ruff" --auto-approve

# Fix type errors
mypy src/ 2>&1 | claude -p "Fix all mypy type errors" --auto-approve

# Fix build failures
docker build . 2>&1 | claude -p "Fix the Docker build failure" --auto-approve

These one-liners can be added to any existing CI pipeline with minimal changes.


Editor Extensions

Claude Code is terminal-first, but you do not have to stare at a terminal to review its output. Official extensions for the major editors provide a visual diff interface:

  • VS Code: install the "Claude Code" extension from the VS Code Marketplace. It shows Claude Code's diffs in the standard VS Code diff viewer and lets you accept or reject individual hunks.
  • Cursor: Claude Code integrates with Cursor's native diff viewer. You can start a Claude Code session from the Cursor terminal and review changes in the editor pane.
  • JetBrains (IntelliJ, PyCharm, WebStorm): the JetBrains plugin surfaces Claude Code output in the built-in version control diff tool.

All three extensions are read-only review layers. They do not change how Claude Code runs; they just make it easier to read and approve its output without switching to a separate diff tool.


Cost Management

Claude Code charges per token. Choosing the right model tier for each task is the single most impactful cost control lever.

Model Speed Cost Best For
claude-haiku-4-5 Fastest Lowest Tab completion, small fixes, linting, formatting
claude-sonnet-4-5 Balanced Mid Most agentic tasks, test writing, moderate refactors
claude-opus-4-5 Slowest Highest Complex architecture decisions, security audits, large multi-file refactors

Practical rules: - Default to sonnet for interactive sessions. - Switch to haiku for high-frequency one-shot CI tasks (linting, formatting, commit message generation). - Reserve opus for tasks where the reasoning depth clearly matters: designing a new module's architecture, reviewing security-sensitive code, or planning a database schema migration with complex dependencies.

Use /compact during long interactive sessions. It summarizes the conversation history into a compressed representation, reducing the token count on subsequent turns without losing the essential context.

Monitor your usage in the Anthropic console at console.anthropic.com. Set a monthly spending alert so you are notified before costs escalate.


Practical Workflow Example: Adding a New Feature End-to-End

Here is a complete example of using Claude Code to add a password reset feature to a FastAPI application.

Step 1: Start an interactive session with context.

cd /path/to/myapp
claude

Step 2: Describe the feature.

> Add a password reset flow. Users should be able to POST to /api/auth/forgot-password
> with their email. If the email exists, send a reset link (use the existing EmailService).
> The reset token should expire in 1 hour and be stored in Redis. Add a POST
> /api/auth/reset-password endpoint that validates the token and updates the password.
> Write tests for both endpoints.

Step 3: Review the plan.

Claude Code will outline which files it intends to create and modify. Read the plan. Adjust if needed — for example, if it proposes to create a new Redis module but you already have one, tell it which file to use instead.

Step 4: Approve step by step.

For each file write and shell command, Claude Code pauses and shows you what it is about to do. Review and approve. If something looks wrong, type n, explain the issue, and it will adjust.

Step 5: Run the final test suite.

> Run the full pytest suite and fix any failures before we finish.

Claude Code runs pytest, reads the output, identifies failures, edits the relevant files, and reruns until everything passes.

Step 6: Generate a commit message and commit.

> Commit these changes with a Conventional Commits message.
git log --oneline -3
# feat(auth): add password reset flow with Redis token storage

The entire workflow — from blank prompt to passing tests to commit — took one terminal session and no manual file editing.


Conclusion

Claude Code brings the power of a state-of-the-art coding agent directly into the terminal environment where developers already work. The key to using it effectively is the same as with any powerful tool: start with a clear task, give it the context it needs (via CLAUDE.md and MCP), and maintain the habit of reviewing its output before accepting. Use haiku for speed-sensitive CI tasks, sonnet for day-to-day agentic work, and opus for the decisions that genuinely require deep reasoning. With a solid CLAUDE.md in place, subagents for large parallel tasks, and MCP servers connecting your external tools, Claude Code becomes less of a coding assistant and more of a capable engineering collaborator that happens to live in your terminal.