跪拜 Guibai
← Back to the summary

Claude Code in Practice: Structuring Projects, Rules, and Agent Workflows

1. Introduction to Claude Code

Claude Code is an AI programming collaboration tool for developers launched by Anthropic. The core goal of Claude Code is to understand your entire project and participate in real coding, modification, and refactoring processes. Claude Code is not a code generator, but an AI programming tool that can read projects, understand context, and follow constraints. It is not a chat box in a web page, but runs directly in your terminal, reads the code of your entire project, understands the relationships between files, directly modifies code files, executes your instructions, and gives suggestions.

2. Claude Code Features

3. Installation Tutorial

3.1 Installing Claude Code

Using the official script:

curl -fsSL https://claude.ai/install.sh | bash

macOS installation: npm install -g @anthropic-ai/claude-code

Verify after installation:

claude --version

3.2 Configuring Claude Code

Configuration file path: ~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "Your Coding Plan API Key",
    "ANTHROPIC_BASE_URL": "https://token-plan.cn-beijing.maas.aliyuncs.com/apps/anthropic",
    "ANTHROPIC_DEFAULT_FABLE_MODEL": "qwen3.7-plus[1M]",
    "ANTHROPIC_DEFAULT_FABLE_MODEL_NAME": "qwen3.7-plus",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-5.2",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME": "glm-5.2",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "kimi-k2.7-code[1M]",
    "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME": "kimi-k2.7-code",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "qwen3.7-max[1M]",
    "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME": "qwen3.7-max"
  },
  "custom_instructions": {
    "language": "Always respond in Simplified Chinese. You must not output English explanations or mixed language."
  },
  "includeCoAuthoredBy": false,
  "model": "sonnet",
  "enabledPlugins": {
    "superpowers@claude-plugins-official": true,
    "frontend-design@claude-plugins-official": true,
    "playwright@claude-plugins-official": true
  },
  "effortLevel": "high",
  "theme": "dark",
  "switchModelsOnFlag": true,
  "permissions": {
    "allow": [
      "mcp__codegraph__*"
    ]
  },
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "codegraph prompt-hook"
          }
        ]
      }
    ]
  }
}

Through the above steps, the configuration of Claude Code is complete. Next, start practicing how to use it.

3.3 Three Permission Modes of Claude Code

Mode Behavior
Normal Mode Ask before each operation
Plan Mode Explain the plan first, execute after approval
Auto-Accept Mode Edit directly, no longer ask

Other small features:

4. Basic Usage

4.1 Common Commands

Command Function
Esc Exit execution
/resume Resume conversation
/ List all commands
/clear Clear session
/cost View consumption (prevent token burning)
/compact Compress context
/reset Switch tasks
/review Check Git staging area

4.2 Quick Operations

Operation Function
Ctrl+C Cancel current operation
Ctrl+L Clear screen
Ctrl+O Toggle detailed output
Ctrl+K Delete to end of line
Starting with / Trigger slash command
Starting with ! Run Bash command directly
@ Trigger file path auto-completion
\ + Enter Line break input

5. Working Logic: Agent Loop

The core of Claude Code is the Agent Loop, working autonomously like a human programmer:

Think → Act → Verify → (Loop)

5.1 Models (Brain)

Model Applicable Scenario
Sonnet Daily coding, fast speed, high cost-effectiveness
Opus Complex architecture design, deep reasoning

5.2 Built-in Tools (Hands)

Tool Capability
File Operations Read, modify, create, rename
Search Find by filename or regex
Execute Commands npm, git, test, start server
Web Search Query documentation or error messages
Code Intelligence LSP integration, type checking

Example Workflow: Run tests → Read error logs → Search related files → Understand code → Modify → Verify again

5.3 Enhanced Capability System

Basic Capabilities
  ├── Skills
  ├── MCP (External Services)
  ├── Hooks (Automation)
  └── SubAgents

6. Project Application

The previous sections introduced the installation, commands, and basic capabilities of Claude Code. The key to truly using Claude Code well lies in letting it understand your project, follow your specifications, and assist you in completing development tasks in the appropriate mode.

In actual projects, Claude Code usually revolves around the following aspects:

  1. Use /init to initialize project context
  2. Solidify project rules through CLAUDE.md
  3. Use the .claude/ directory to manage commands, rules, skills, and sub-agents

6.1 Project Initialization: /init

/init is a very important command for Claude Code in a project.

Its core function is: Generate a CLAUDE.md file for the current project.

This file can be understood as Claude Code's "project manual" or "long-term context." With it, Claude can quickly understand each time it enters this project:

6.1.1 How to Use /init

After entering the project root directory, start Claude Code:

claude

Then enter in the Claude Code session:

/init

Claude Code will automatically scan the current project and generate a file similar to this:

CLAUDE.md

6.1.2 What is CLAUDE.md?

CLAUDE.md is the core configuration file for Claude Code in the current project.

It is not a code file, but a Markdown document used to tell Claude:

How you should work in this project.

A typical CLAUDE.md might contain the following:

# Project Overview

This is a React + TypeScript frontend project.

## Tech Stack

- React
- TypeScript
- Vite
- Tailwind CSS
- pnpm

## Common Commands

- Install dependencies: `pnpm install`
- Start dev server: `pnpm dev`
- Run tests: `pnpm test`
- Build project: `pnpm build`

## Code Style

- Use TypeScript for all new files
- Prefer functional components
- Use named exports instead of default exports
- Keep components small and focused

## Project Structure

- `src/components`: reusable UI components
- `src/pages`: page-level components
- `src/hooks`: custom React hooks
- `src/utils`: utility functions

## Development Rules

- Do not introduce new dependencies without confirmation
- Do not modify public APIs unless explicitly requested
- Run tests after changing business logic

6.1.3 What Does CLAUDE.md Usually Contain?

Content Description
Project Description Current project goals, business background, core functions
Tech Stack Languages, frameworks, build tools, testing frameworks used
Common Commands Install dependencies, start project, run tests, package build
Directory Structure Responsibilities and uses of each directory
Code Style Naming conventions, component conventions, comment conventions, etc.
Architecture Conventions Module layering, interface design, state management methods
Workflow Commit conventions, testing requirements, review rules
Notes Files not allowed to be modified arbitrarily, sensitive logic descriptions

6.1.4 Benefits of Using /init

1. Establish Project Context

Without CLAUDE.md, you need to tell Claude again each time:

This is a Vue project, uses pnpm, tests with Vitest, don't use npm.

With CLAUDE.md, this information can be saved long-term in the project, and Claude can automatically read it each time it enters the project.

2. Maintain Consistent Code Style

In team projects, the biggest fear is that AI-modified code style is inconsistent with the original project.

For example, the project requires:

These rules can all be written into CLAUDE.md, allowing Claude to automatically comply when generating and modifying code.

3. Reduce Communication Costs

If a project has multiple members, and everyone uses Claude Code, after committing CLAUDE.md to the Git repository, team members can share the same set of AI usage specifications.

This way, Claude will not produce completely different code styles due to different people's descriptions.

6.2 Claude Code Project Structure

In actual projects, Claude Code does not only rely on one CLAUDE.md file. As project complexity increases, a dedicated .claude/ directory usually appears to manage Claude's behavior rules, permissions, custom commands, skills, and sub-agents.

A relatively complete Claude Code project structure is as follows:

your-project/
├── CLAUDE.md
├── CLAUDE.local.md
├── .mcp.json
├── .claude/
│   ├── settings.json
│   ├── commands/
│   │   ├── review.md
│   │   ├── test.md
│   │   └── release.md
│   ├── rules/
│   │   ├── code-style.md
│   │   ├── git.md
│   │   └── testing.md
│   ├── skills/
│   │   ├── write-unit-tests/
│   │   │   └── SKILL.md
│   │   └── refactor-component/
│   │       └── SKILL.md
│   └── agents/
│       ├── frontend-reviewer.md
│       ├── backend-analyst.md
│       └── data-analyst.md
├── src/
├── package.json
└── README.md

The following explains the roles of these files and directories one by one.

6.2.1 CLAUDE.md: Project-Level Manual

Location:

CLAUDE.md

Role:

Suitable for writing:

Example:

# Claude Instructions

## Project

This is a Node.js backend service.

## Rules

- Use TypeScript for all new files.
- Do not change database schema without confirmation.
- Use pnpm instead of npm.
- Run `pnpm test` after modifying business logic.

6.2.2 CLAUDE.local.md: Personal Private Rules

Location:

CLAUDE.local.md

Role:

For example:

# Local Claude Preferences

- My local database is running on port 5433.
- When testing locally, use `.env.local`.
- Prefer shorter explanations unless I ask for details.

Because this file may contain personal environment information, it is recommended to add to .gitignore:

CLAUDE.local.md

6.2.3 .claude/settings.json: Permission and Security Configuration

Location:

.claude/settings.json

Role:

For example, Claude can be restricted from executing dangerous commands:

{
  "permissions": {
    "allow": [
      "Bash(pnpm test)",
      "Bash(pnpm build)",
      "Bash(git status)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Bash(curl * | bash)"
    ]
  }
}

This can prevent Claude from accidentally deleting files or executing high-risk commands during automated execution.

6.2.4 .claude/commands/: Custom Slash Commands

Location:

.claude/commands/

Role:

For example, create a file:

.claude/commands/review.md

Content:

Please check the changes in the current Git staging area, focusing on:

1. Are there obvious bugs?
2. Does it comply with project code standards?
3. Are there performance issues?
4. Do tests need to be supplemented?
5. Are there security risks?

Please output in the format of "Problem / Impact / Suggested Modification."

Afterwards, you can use it directly in Claude Code:

/project:review

This way, team members do not need to repeatedly input long prompts.

6.2.5 .claude/rules/: Modular Behavior Rules

Location:

.claude/rules/

Role:

For example:

.claude/rules/code-style.md
.claude/rules/testing.md
.claude/rules/git.md

code-style.md:

# Code Style Rules

- Use TypeScript.
- Avoid `any` unless necessary.
- Prefer small functions.
- Use meaningful variable names.
- Do not introduce new dependencies without approval.

testing.md:

# Testing Rules

- Add unit tests for new business logic.
- Run tests after modifying core modules.
- Follow the existing test style.

This approach is suitable for medium to large projects, allowing rules to be split more clearly.

6.2.6 .claude/skills/: Auto-Invoked Workflows

Location:

.claude/skills/

Role:

Directory structure example:

.claude/skills/
└── write-unit-tests/
    └── SKILL.md

SKILL.md example:

# Write Unit Tests Skill

When the user asks to add or improve tests:

1. Inspect the target file.
2. Find existing test patterns.
3. Create or update the corresponding test file.
4. Cover normal cases, edge cases, and error cases.
5. Run the test command if allowed.
6. Summarize what was tested.

When you say:

Please help me add unit tests for this function.

Claude may automatically read this Skill and execute according to the process defined within.

6.2.7 .claude/agents/: Sub-Agent Roles

Location:

.claude/agents/

Role:

For example:

.claude/agents/frontend-reviewer.md

Content:

---
name: frontend-reviewer
description: Review frontend code quality and user experience
---

You are a frontend code reviewer.

Focus on:

1. Component structure
2. React hooks usage
3. TypeScript correctness
4. Accessibility
5. UI consistency
6. Performance issues

Do not modify files directly. Only provide review comments and suggestions.

In complex tasks, the main Claude can assign different tasks to different sub-agents, avoiding cramming all context into one session.

7. Using MCP in Claude Code

MCP is the bridge connecting Claude Code to the outside world, evolving AI from a "code advisor" to a "full-stack engineer."

7.1 Basic Concepts

Dimension Description
Definition An open protocol proposed by Anthropic
Function Allows Claude to access external system data in real-time
Analogy The "USB-C interface" for AI applications
Capabilities Access GitHub/Databases/Slack/Browsers, etc.

7.2 Adding MCP Server

Three Communication Methods:

Type Use
http Remote service
stdio Local process
sse Legacy (gradually deprecated)

Add Remote HTTP MCP:

claude mcp add --transport http notion https://mcp.notion.com/mcp

Add Local Node.js MCP:

claude mcp add everything -- npx -y @modelcontextprotocol/server-everything

With Authentication:

claude mcp add --transport http my-api https://api.example.com/mcp \
  --header "Authorization: Bearer $TOKEN"

7.3 Common MCP Management Commands

Command Function
claude mcp list List all MCP servers
claude mcp get <name> View specified configuration
claude mcp remove <name> Remove specified
/mcp View + authenticate within session
claude mcp serve Serve itself as an MCP Server

7.4 Configuration Files

User-Level (Global): ~/.claude.json

Project-Level (Recommended for team sharing): .mcp.json

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

7.5 Scope and Loading

Three Layers of Scope:

Scope Location Priority
User ~/.claude.json Low
Project .mcp.json Medium
Local Project within project High

8. Summary

Claude Code is not a simple chatbot, but an engineer with extremely strong execution ability, yet requiring clear constraints. Remember three key principles:

  1. The more specific the question, the more precise the output — Clearly state the background, goals, and constraints.
  2. Choose the appropriate mode — Ask to clarify, Plan to avoid detours, Edit to execute cautiously.
  3. Make good use of MCP extensions — Let Claude go from "writing code" to "running code, testing code, managing code."

Start using your AI programming partner! 🚀