> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Working with Claude Code Agents

> How to create, edit, and run Claude Code agents via CLI and SDK for interactive development and CI/CD automation, with examples for model selection, tooling, and best practices

In this lesson we cover Claude Code agents: what they are, how to create and edit them from the CLI, and how to run them programmatically with the Claude Code SDK (useful for CI/CD checks). You’ll get step-by-step examples for interactive CLI creation, agent editing, invoking agents, and a programmatic Python example for automation.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/Xs8Ruv7b0QCZf7iM/images/Claude-Code-for-Beginners/Advanced-Features/Working-with-Claude-Code-Agents/claude-code-agents-demo-slide.jpg?fit=max&auto=format&n=Xs8Ruv7b0QCZf7iM&q=85&s=5daf68f625ca5692627926fa86f6d3f3" alt="A presentation slide reading &#x22;Working with Claude Code Agents&#x22; with a large &#x22;Demo&#x22; label on a dark blue curved shape on the right. The background is light gray with a small &#x22;© Copyright KodeKloud&#x22; in the bottom-left." width="1920" height="1080" data-path="images/Claude-Code-for-Beginners/Advanced-Features/Working-with-Claude-Code-Agents/claude-code-agents-demo-slide.jpg" />
</Frame>

Overview

* Two common workflows:
  * Interactive: Create sub-agents from the Claude Code CLI and call them inside your development workflow.
  * Programmatic: Instantiate and run agents via the Claude Code SDK (Python, or other SDKs) for CI/CD automation.

<Callout icon="lightbulb" color="#1CB2FE">
  When choosing a model for an agent, balance capability and cost. "Inherit-from-parent" keeps behavior consistent with the main conversation; "Sonnet" is a strong, general-purpose choice; "Haiku" is faster and cheaper for simpler checks.
</Callout>

CLI: Create and run a sub-agent interactively

Quick flow

1. Open Claude Code inside your repository (CLI shows your current working directory).
2. Use the `/agents` command to list existing agents or start creating a new one.
3. Choose a creation method: generate with Claude (recommended) or manual configuration.
4. Select tools that the agent is allowed to use.
5. Pick a model for the agent.
6. Confirm and save the agent (stored under `.claude/agents`).
7. Invoke the saved agent by name from the CLI.

Step-by-step example (condensed CLI transcript)

```bash theme={null}
* Welcome to Claude Code!

/help for help, /status for your current setup

cwd: /Users/jeremy/Repos/Claude Code Course/Express-login-demo

> /agents
Agents
No agents found

› Create new agent
```

Creation method prompt

```bash theme={null}
> /agents
Create new agent
Creation method

› 1. Generate with Claude (recommended)
  2. Manual configuration
```

Tool selection (interactive UI)
The CLI displays tool groups (All tools, Read-only, Edit, Execution, MCP, etc.). For a read-only reviewer you might enable only read-related tools such as Read, Grep, and WebFetch.

Example selection prompt (condensed):

```text theme={null}
Create new agent
Select tools

[ Continue ]

────────────────────────
☒ All tools
☒ Read-only tools
> ☒ Edit tools
☒ Execution tools
☒ MCP tools
────────────────────────
[ Show advanced options ]

All tools selected
```

Model selection
Pick a model that matches the complexity and cost trade-offs of your task:

```bash theme={null}
Create new agent
Select model
Model determines the agent's reasoning capabilities and speed.

1. Sonnet               Balanced performance - best for most agents✔
2. Haiku                Fast and efficient for simple tasks
> 3. Inherit from parent Use the same model as the main conversation
```

Confirm and save
When you confirm, the CLI shows a summary including the agent file path, tools, model, and description. Agents are saved as YAML/MD files under `.claude/agents`.

Example agent summary (trimmed):

```yaml theme={null}
Create new agent
Confirm and save

Name: code-readability-reviewer
Location: .claude/agents/code-readability-reviewer.md
Tools: Bash, Glob, Grep, LS, Read, WebFetch, TodoWrite, WebSearch, BashOutput, KillBash
Model: Inherit from parent

Description (tells Claude when to use this agent):

Use this agent when you need to evaluate code for readability, variable naming conventions, and overall code clarity. Examples: ...
System prompt:

You are a Senior Code Quality Specialist with expertise in software readability, maintainability, and naming conventions across multiple programming languages. Your primary focus is evaluating code for clarity, comprehensibility, and adherence to clean code principles.
```

Editing an agent

* Agents are stored in the repo (project-scoped) as files under `.claude/agents`. Open and edit them with your preferred editor to update name, description, tools, model, color, system prompts, and rules.
* After saving edits the CLI may prompt to restart or reload to pick up changes.
* Keep system prompts structured: clear rules, expected output format, and an examples section so agent outputs are consistent and actionable.

Example snippet from an agent file (metadata, system prompt, and rules). Note the YAML contains illustrative tags used by the agent file:

```yaml theme={null}
name: code-readability-reviewer
description: Use this agent when you need to evaluate code for readability, variable naming conventions, and overall code clarity. Examples: <example>Context: User has just written a function and wants feedback on code quality. user: 'I just wrote this function to calculate user statistics, can you review it for readability?' assistant: 'I'll use the code-readability-reviewer agent to evaluate your code for readability and naming conventions.' <commentary>The user is asking for code readability review, so use the code-readability-reviewer agent to analyze the code quality.</commentary></example>
tools: Bash, Glob, Grep, LS, Read, WebFetch, TodoWrite, WebSearch, BashOutput, KillBash
model: inherit
color: green
---

You are a Senior Code Quality Specialist with expertise in software readability, maintainability, and naming conventions across multiple programming languages. Your primary focus is evaluating code for clarity, comprehensibility, and adherence to clean code principles.

When reviewing code, you will:

**Variable and Function Naming Analysis:**
- Assess whether names clearly communicate purpose and intent
- Identify vague, abbreviated, or misleading names (e.g., 'data', 'temp', 'x', 'mgr')
- Evaluate consistency in naming patterns within the codebase
- Check adherence to language-specific conventions (camelCase, snake_case, etc.)
- Suggest specific, descriptive alternatives for problematic names

**Code Structure and Readability:**
- Analyze function and method length for cognitive load
- Evaluate logical flow and organization
- Assess comment quality and necessity
- Review indentation, spacing, and formatting consistency
- Identify overly complex expressions that could be simplified

**Output Format:**
- Start with a clear summary of overall readability
- Use specific line references when pointing out issues
- Provide before/after examples for naming suggestions
- Prioritize feedback by impact (critical vs. minor improvements)
- End with 2-3 key actionable recommendations
```

Using an agent from the CLI
Once saved, call the agent by its name from the CLI. Example usage for a readability review:

```bash theme={null}
> use the code_readability_reviewer agent to inspect auth.js and give me a report.
• I'll use the code-readability-reviewer agent to analyze the auth.js file and provide you with a readability report.

● code-readability-reviewer(Review auth.js readability)
└ Done (2 tool uses · 12.1k tokens · 29.9s)

• The code-readability-reviewer agent has analyzed your auth.js file and provided a comprehensive readability report. Here are the key findings:

Overall Score: 8/10 – The code is well-structured with good naming conventions and follows Express.js patterns effectively.

Main Strengths:
- Clear variable names like userQuery, isPasswordValid
- Consistent camelCase naming
- Proper separation of validation and business logic
- Good security practices (parameterized queries, password hashing)

Key Areas for Improvement:
1. Extract database error handling – define error codes as constants
2. Function Length – the main handler is long (consider breaking into smaller functions)
3. Magic strings – move SQL queries and error codes into constants

Recommended Priority Fixes:
- Define constants for database error codes
- Extract authentication logic into a separate function
- Move hardcoded SQL query to a constant
```

Why agents are useful

* Encode standard audits and rules (naming conventions, security checks) in an agent’s system prompt so you don’t re-write prompts.
* Share agents in a repo for team consistency or keep them global/personal.
* Run agents in CI to automate reviews before merges or deployments.

Programmatic use: Python SDK (CI/CD integration)

Use cases

* Automate readability/security/dependency checks in CI jobs.
* Gate merges by failing the build on critical findings or by posting warnings to PRs.
* Run reproducible, configurable inspections with consistent output formats.

Install the SDK in CI:

```bash theme={null}
pip install claude-code-sdk
# optionally also install the claude-code CLI if needed
```

Example Node/Express snippet (context for what an agent might inspect)

```javascript theme={null}
const pool = require('../config/database');
const router = express.Router();

router.post('/login', [
  body('email')
    .isEmail()
    .withMessage('Please provide a valid email address')
    .normalizeEmail(),
  body('password')
    .isLength({ min: 8 })
    .withMessage('Password must be at least 8 characters long')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        error: 'Validation failed',
        details: errors.array()
      });
    }

    const { email, password } = req.body;
    // authentication logic...
```

Sample Python program using the Claude Code SDK

* This example shows instantiating a Claude SDK client with a focused system prompt and a restricted set of allowed tools. It then queries the agent and streams the response, which is suitable for CI scripts that need structured output.

```python theme={null}
import asyncio
from claude_code_sdk import ClaudeSDKClient, ClaudeCodeOptions

async def main():
    async with ClaudeSDKClient(
        options=ClaudeCodeOptions(
            system_prompt="You are an SRE agent. Diagnose incidents step-by-step and propose safe fixes.",
            allowed_tools=["Read", "Grep", "Bash"],  # fine-grained control
            max_turns=4
        )
    ) as client:
        await client.query("API error rates just spiked in payments - investigate and propose fixes.")
        async for msg in client.receive_response():
            if hasattr(msg, "content"):
                for block in msg.content:
                    if hasattr(block, "text"):
                        print(block.text, end="")

if __name__ == "__main__":
    asyncio.run(main())
```

Model selection examples

* Choose the right model identifier when configuring agents or clients. Below is a representative list of models (use the latest identifiers from the docs when available).

| Model family | Example identifiers |
| - | - |
| Claude 4 | `claude-opus-4-1-20250805`, `claude-opus-4-1`, `claude-opus-4-20250514`, `claude-opus-4-0`, `claude-sonnet-4-20250514` |
| Claude 3.7 | `claude-3-7-sonnet-20250219`, `claude-3-7-sonnet-latest` |
| Claude 3.5 | `claude-3-5-haiku-20241022`, `claude-3-5-haiku-latest`, `claude-3-5-sonnet-20241022` |

Other SDKs and language examples

* SDKs are available in multiple languages (TypeScript, Java, Go, Ruby). Below is a compact Ruby example for reference (Anthropic client shown as a short snippet):

```ruby theme={null}
require "bundler/setup"
require "anthropic"

anthropic = Anthropic::Client.new(
  api_key: "my_api_key" # defaults to ENV["ANTHROPIC_API_KEY"]
)

message =
  anthropic.messages.create(
    max_tokens: 1024,
    messages: [{
      role: "user",
      content: "Hello, Claude"
    }],
    model: "claude-sonnet-4-20250514"
  )

puts(message.content)
```

<Callout icon="warning" color="#FF6B6B">
  Be careful enabling write or execution tools (e.g., Bash, TodoWrite, KillBash) in CI. Execution-capable agents can change state or systems — prefer read-only tools for automated checks unless you have strict controls and audits in place.
</Callout>

Practical CI/CD recipe

* Add a CI job that:
  1. Installs the Claude Code SDK (`pip install claude-code-sdk`) or other language SDK.
  2. Runs a script that instantiates a project-scoped agent with a deterministic system prompt and allowed tools.
  3. Parses agent output for structured results (e.g., JSON, line-tagged findings).
  4. Fails or warns the build based on severity thresholds.

Summary

* Claude Code agents let you encode repeatable auditing rules (readability, security, dependency checks) into project-scoped or personal agents.
* The CLI is ideal for iterative, interactive creation and local testing; agents are stored under `.claude/agents`.
* The SDK supports programmatic execution in CI/CD for automated gating and reproducible checks.
* Structure agent system prompts (rules + output format + examples) to get consistent actionable results.

Next steps

* Try creating a lightweight `code-readability-reviewer` agent via the CLI, test it on a small file, then add a CI job that runs the agent on PRs.
* In the next lesson we’ll cover test-driven development workflows with Claude agents and integrating them into your development lifecycle.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/claude-code-for-beginners/module/a295c914-f61e-47bb-8adc-7a3145745aa6/lesson/2600436d-4843-474a-b6d2-93921ce1ef91" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.