claude-code-best-practice

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Code Best Practice

Claude Code 最佳实践

Skill by ara.so — Claude Code Skills collection.
Master the transition from "vibe coding" to agentic engineering with comprehensive best practices, implementation patterns, and real-world examples for Claude Code.
ara.so 提供的技能 — Claude Code 技能合集。
掌握从“凭感觉编码”到智能体工程的转变,学习Claude Code的全面最佳实践、实现模式和真实案例。

Overview

概述

This project provides battle-tested patterns for building sophisticated AI coding workflows using Claude Code's agent system. It covers subagents, commands, skills, orchestration workflows, MCP servers, hooks, and advanced features like agent teams and scheduled tasks.
本项目提供了经过实战检验的模式,用于利用Claude Code的智能体系统构建复杂的AI编码工作流。内容涵盖子智能体、命令、技能、编排工作流、MCP服务器、钩子以及智能体团队、定时任务等高级功能。

Core Concepts

核心概念

Project Structure

项目结构

your-project/
├── .claude/
│   ├── agents/           # Subagent definitions
│   │   └── <name>.md
│   ├── commands/         # Custom slash commands
│   │   └── <name>.md
│   ├── skills/           # Skill packages
│   │   └── <name>/
│   │       └── SKILL.md
│   ├── hooks/            # Lifecycle hooks
│   │   └── <hook-name>.sh
│   ├── rules/            # Project-specific rules
│   │   └── <name>.md
│   └── settings.json     # Configuration
├── .mcp.json             # MCP server config
└── CLAUDE.md             # Project memory/context
your-project/
├── .claude/
│   ├── agents/           # 子智能体定义
│   │   └── <name>.md
│   ├── commands/         # 自定义斜杠命令
│   │   └── <name>.md
│   ├── skills/           # 技能包
│   │   └── <name>/
│   │       └── SKILL.md
│   ├── hooks/            # 生命周期钩子
│   │   └── <hook-name>.sh
│   ├── rules/            # 项目特定规则
│   │   └── <name>.md
│   └── settings.json     # 配置文件
├── .mcp.json             # MCP服务器配置
└── CLAUDE.md             # 项目记忆/上下文

Subagents

子智能体

Purpose: Specialized AI agents focused on specific domains.
Location:
.claude/agents/<name>.md
Structure:
markdown
---
name: backend-api
description: Expert in FastAPI, database design, and REST APIs
model: claude-3-7-sonnet-20250219
---

You are a backend API specialist...
用途:专注于特定领域的专业AI智能体。
存放位置
.claude/agents/<name>.md
结构:
markdown
---
name: backend-api
description: Expert in FastAPI, database design, and REST APIs
model: claude-3-7-sonnet-20250219
---

You are a backend API specialist...

Capabilities

Capabilities

  • Design RESTful APIs
  • Optimize database queries
  • Handle authentication patterns
  • Design RESTful APIs
  • Optimize database queries
  • Handle authentication patterns

Guidelines

Guidelines

  • Always validate input
  • Use async/await patterns
  • Include proper error handling

**Invocation**:
```bash
  • Always validate input
  • Use async/await patterns
  • Include proper error handling

**调用方式**:
```bash

Direct invocation

直接调用

@backend-api help me design a user authentication endpoint
@backend-api help me design a user authentication endpoint

From command

通过命令调用

/api-review # Can delegate to @backend-api

**Best Practices**:
- Keep agents focused (single responsibility)
- Define clear capabilities and constraints
- Use appropriate models (Sonnet for complex, Haiku for simple)
- Include domain-specific guidelines
/api-review # 可委托给@backend-api

**最佳实践**:
- 保持智能体专注(单一职责)
- 定义清晰的能力和约束
- 使用合适的模型(Sonnet用于复杂任务,Haiku用于简单任务)
- 包含领域特定指南

Commands

命令

Purpose: Reusable workflows triggered by
/command-name
.
Location:
.claude/commands/<name>.md
Basic Command:
markdown
---
name: api-review
description: Review API design for REST best practices
---

Review the current API implementation:

1. Check endpoint naming conventions
2. Verify HTTP method usage
3. Validate response status codes
4. Check error handling patterns
5. Assess documentation completeness

Focus on files in `src/api/` and `src/routes/`.
Orchestration Command (delegates to agents):
markdown
---
name: full-stack-review
description: Comprehensive review using specialized agents
---

Orchestrate a complete codebase review:
用途:通过
/command-name
触发的可复用工作流。
存放位置
.claude/commands/<name>.md
基础命令:
markdown
---
name: api-review
description: Review API design for REST best practices
---

Review the current API implementation:

1. Check endpoint naming conventions
2. Verify HTTP method usage
3. Validate response status codes
4. Check error handling patterns
5. Assess documentation completeness

Focus on files in `src/api/` and `src/routes/`.
编排命令(委托给智能体):
markdown
---
name: full-stack-review
description: Comprehensive review using specialized agents
---

Orchestrate a complete codebase review:

Step 1: Backend Review

Step 1: Backend Review

@backend-api review all API endpoints in
src/api/
for:
  • Security vulnerabilities
  • Performance issues
  • Best practices compliance
@backend-api review all API endpoints in
src/api/
for:
  • Security vulnerabilities
  • Performance issues
  • Best practices compliance

Step 2: Frontend Review

Step 2: Frontend Review

@frontend-expert analyze components in
src/components/
for:
  • Accessibility issues
  • Performance optimizations
  • React best practices
@frontend-expert analyze components in
src/components/
for:
  • Accessibility issues
  • Performance optimizations
  • React best practices

Step 3: Integration Check

Step 3: Integration Check

@integration-agent verify:
  • API contract matches frontend usage
  • Error handling is consistent
  • Loading states are handled
@integration-agent verify:
  • API contract matches frontend usage
  • Error handling is consistent
  • Loading states are handled

Final Report

Final Report

Synthesize findings into a prioritized action plan.

**With Parameters**:
```markdown
---
name: generate-crud
description: Generate CRUD endpoints for a model
---

Generate complete CRUD operations for: {model_name}

1. Create `src/models/{model_name}.py`
2. Create `src/routes/{model_name}.py`
3. Add database migrations
4. Generate OpenAPI documentation
5. Create integration tests

Use existing patterns from `src/models/user.py` as reference.
Synthesize findings into a prioritized action plan.

**带参数的命令**:
```markdown
---
name: generate-crud
description: Generate CRUD endpoints for a model
---

Generate complete CRUD operations for: {model_name}

1. Create `src/models/{model_name}.py`
2. Create `src/routes/{model_name}.py`
3. Add database migrations
4. Generate OpenAPI documentation
5. Create integration tests

Use existing patterns from `src/models/user.py` as reference.

Skills

技能

Purpose: Installable expertise packages with tools and context.
Location:
.claude/skills/<skill-name>/SKILL.md
Example FastAPI Skill:
markdown
---
name: fastapi-expert
description: Expert FastAPI development patterns and best practices
triggers:
  - "create a FastAPI endpoint"
  - "help with FastAPI routing"
  - "optimize FastAPI performance"
---
用途:包含工具和上下文的可安装专业知识包。
存放位置
.claude/skills/<skill-name>/SKILL.md
FastAPI技能示例:
markdown
---
name: fastapi-expert
description: Expert FastAPI development patterns and best practices
triggers:
  - "create a FastAPI endpoint"
  - "help with FastAPI routing"
  - "optimize FastAPI performance"
---

FastAPI Expert Skill

FastAPI Expert Skill

Installation

Installation

bash
pip install fastapi uvicorn sqlalchemy pydantic
bash
pip install fastapi uvicorn sqlalchemy pydantic

Basic Endpoint Pattern

Basic Endpoint Pattern

python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    description: str | None = None

@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
    item = await fetch_item(item_id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.post("/items", response_model=Item, status_code=201)
async def create_item(item: Item):
    created = await save_item(item)
    return created
python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    description: str | None = None

@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
    item = await fetch_item(item_id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.post("/items", response_model=Item, status_code=201)
async def create_item(item: Item):
    created = await save_item(item)
    return created

Dependency Injection

Dependency Injection

python
from fastapi import Depends
from sqlalchemy.orm import Session

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users")
async def get_users(db: Session = Depends(get_db)):
    return db.query(User).all()
python
from fastapi import Depends
from sqlalchemy.orm import Session

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/users")
async def get_users(db: Session = Depends(get_db)):
    return db.query(User).all()

Background Tasks

Background Tasks

python
from fastapi import BackgroundTasks

def send_email(email: str, message: str):
    # Email sending logic
    pass

@app.post("/send-notification")
async def notify(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email, email, "Welcome!")
    return {"message": "Notification queued"}
python
from fastapi import BackgroundTasks

def send_email(email: str, message: str):
    # Email sending logic
    pass

@app.post("/send-notification")
async def notify(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email, email, "Welcome!")
    return {"message": "Notification queued"}

Best Practices

Best Practices

  • Use Pydantic models for validation
  • Leverage dependency injection
  • Implement proper error handling
  • Use async/await for I/O operations
  • Document with OpenAPI metadata
undefined
  • Use Pydantic models for validation
  • Leverage dependency injection
  • Implement proper error handling
  • Use async/await for I/O operations
  • Document with OpenAPI metadata
undefined

Workflows (Orchestration)

工作流(编排)

Purpose: Multi-step processes that coordinate multiple agents.
Example Weather Orchestrator:
markdown
---
name: weather-orchestrator
description: Fetch and analyze weather data using specialized agents
---
用途:协调多个智能体的多步骤流程。
天气编排器示例:
markdown
---
name: weather-orchestrator
description: Fetch and analyze weather data using specialized agents
---

Weather Analysis Workflow

Weather Analysis Workflow

Phase 1: Data Collection

Phase 1: Data Collection

@data-fetcher retrieve current weather data for {city} using:
  • Temperature
  • Humidity
  • Wind speed
  • Forecast
@data-fetcher retrieve current weather data for {city} using:
  • Temperature
  • Humidity
  • Wind speed
  • Forecast

Phase 2: Analysis

Phase 2: Analysis

@data-analyst analyze the weather data for:
  • Trends over next 48 hours
  • Unusual patterns
  • Alerts or warnings
@data-analyst analyze the weather data for:
  • Trends over next 48 hours
  • Unusual patterns
  • Alerts or warnings

Phase 3: Recommendations

Phase 3: Recommendations

@recommendation-engine generate actionable advice:
  • Outdoor activity suitability
  • Clothing recommendations
  • Travel considerations
@recommendation-engine generate actionable advice:
  • Outdoor activity suitability
  • Clothing recommendations
  • Travel considerations

Phase 4: Report

Phase 4: Report

Compile findings into a user-friendly summary with:
  • Current conditions
  • 48-hour forecast
  • Personalized recommendations

**Invocation**:
```bash
/weather-orchestrator city="San Francisco"
Compile findings into a user-friendly summary with:
  • Current conditions
  • 48-hour forecast
  • Personalized recommendations

**调用方式**:
```bash
/weather-orchestrator city="San Francisco"

MCP Servers

MCP服务器

Purpose: Extend Claude with external tools and data sources.
Configuration (
.mcp.json
):
json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "${BRAVE_API_KEY}"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
      }
    }
  }
}
Usage in Agents:
markdown
Use the GitHub MCP server to:
- List open pull requests
- Create issues
- Search repositories
- Analyze commit history
用途:通过外部工具和数据源扩展Claude的能力。
配置文件
.mcp.json
):
json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "${BRAVE_API_KEY}"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
      }
    }
  }
}
在智能体中使用:
markdown
Use the GitHub MCP server to:
- List open pull requests
- Create issues
- Search repositories
- Analyze commit history

Hooks

钩子

Purpose: Execute scripts at key lifecycle points.
Available Hooks:
  • BeforeChat
    - Before processing user message
  • AfterChat
    - After generating response
  • BeforeToolCall
    - Before executing tool
  • AfterToolCall
    - After tool execution
  • BeforeFileEdit
    - Before modifying files
  • AfterFileEdit
    - After file changes
  • WorktreeCreate
    - When creating worktree
  • WorktreeRemove
    - When removing worktree
Example (
.claude/hooks/BeforeFileEdit.sh
):
bash
#!/bin/bash
用途:在关键生命周期节点执行脚本。
可用钩子:
  • BeforeChat
    - 处理用户消息前
  • AfterChat
    - 生成响应后
  • BeforeToolCall
    - 执行工具前
  • AfterToolCall
    - 工具执行后
  • BeforeFileEdit
    - 修改文件前
  • AfterFileEdit
    - 文件修改后
  • WorktreeCreate
    - 创建工作树时
  • WorktreeRemove
    - 删除工作树时
示例
.claude/hooks/BeforeFileEdit.sh
):
bash
#!/bin/bash

Backup files before editing

Backup files before editing

FILE_PATH="$1" BACKUP_DIR=".claude/backups"
mkdir -p "$BACKUP_DIR" timestamp=$(date +%Y%m%d_%H%M%S) cp "$FILE_PATH" "$BACKUP_DIR/$(basename "$FILE_PATH").$timestamp.bak"
echo "Backed up $FILE_PATH"

Make executable:
```bash
chmod +x .claude/hooks/BeforeFileEdit.sh
FILE_PATH="$1" BACKUP_DIR=".claude/backups"
mkdir -p "$BACKUP_DIR" timestamp=$(date +%Y%m%d_%H%M%S) cp "$FILE_PATH" "$BACKUP_DIR/$(basename "$FILE_PATH").$timestamp.bak"
echo "Backed up $FILE_PATH"

设置可执行权限:
```bash
chmod +x .claude/hooks/BeforeFileEdit.sh

Settings

设置

Configuration (
.claude/settings.json
):
json
{
  "model": "claude-3-7-sonnet-20250219",
  "maxTokens": 8000,
  "temperature": 0.7,
  "statusline": {
    "left": ["model", "tokens"],
    "right": ["time", "cost"]
  },
  "permissions": {
    "read": ["**/*"],
    "write": ["src/**", "tests/**"],
    "execute": ["scripts/**/*.sh"]
  },
  "autoMode": {
    "enabled": false,
    "confirmThreshold": 10
  },
  "outputStyle": "markdown",
  "fastMode": false,
  "isolation": "none"
}
Global Settings (
~/.claude/settings.json
):
json
{
  "defaultModel": "claude-3-7-sonnet-20250219",
  "apiKey": "${ANTHROPIC_API_KEY}",
  "theme": "dark",
  "telemetry": false
}
配置文件
.claude/settings.json
):
json
{
  "model": "claude-3-7-sonnet-20250219",
  "maxTokens": 8000,
  "temperature": 0.7,
  "statusline": {
    "left": ["model", "tokens"],
    "right": ["time", "cost"]
  },
  "permissions": {
    "read": ["**/*"],
    "write": ["src/**", "tests/**"],
    "execute": ["scripts/**/*.sh"]
  },
  "autoMode": {
    "enabled": false,
    "confirmThreshold": 10
  },
  "outputStyle": "markdown",
  "fastMode": false,
  "isolation": "none"
}
全局设置
~/.claude/settings.json
):
json
{
  "defaultModel": "claude-3-7-sonnet-20250219",
  "apiKey": "${ANTHROPIC_API_KEY}",
  "theme": "dark",
  "telemetry": false
}

Memory (CLAUDE.md)

记忆(CLAUDE.md)

Purpose: Persistent project context and preferences.
Example:
markdown
undefined
用途:持久化的项目上下文和偏好设置。
示例:
markdown
undefined

Project: E-commerce API

Project: E-commerce API

Tech Stack

Tech Stack

  • FastAPI 0.104
  • PostgreSQL 15
  • Redis for caching
  • Stripe for payments
  • FastAPI 0.104
  • PostgreSQL 15
  • Redis for caching
  • Stripe for payments

Architecture Decisions

Architecture Decisions

  • Use repository pattern for data access
  • Implement CQRS for orders
  • JWT for authentication
  • Event-driven for notifications
  • Use repository pattern for data access
  • Implement CQRS for orders
  • JWT for authentication
  • Event-driven for notifications

Code Style

Code Style

  • Use async/await throughout
  • Type hints required
  • Max line length: 100
  • Sort imports with isort
  • Use async/await throughout
  • Type hints required
  • Max line length: 100
  • Sort imports with isort

Testing Strategy

Testing Strategy

  • Pytest for all tests
  • Minimum 80% coverage
  • Integration tests for API endpoints
  • Mock external services
  • Pytest for all tests
  • Minimum 80% coverage
  • Integration tests for API endpoints
  • Mock external services

Common Commands

Common Commands

  • make dev
    - Start development server
  • make test
    - Run test suite
  • make migrate
    - Apply database migrations
  • make lint
    - Run linters
  • make dev
    - Start development server
  • make test
    - Run test suite
  • make migrate
    - Apply database migrations
  • make lint
    - Run linters

Never Do

Never Do

  • Commit secrets to repository
  • Skip migration files
  • Use print() for logging
  • Deploy without tests passing
undefined
  • Commit secrets to repository
  • Skip migration files
  • Use print() for logging
  • Deploy without tests passing
undefined

Advanced Features

高级功能

Agent Teams

智能体团队

Enable (environment variable):
bash
export CLAUDE_AGENT_TEAMS=true
claude
Team Configuration:
markdown
undefined
启用方式(环境变量):
bash
export CLAUDE_AGENT_TEAMS=true
claude
团队配置:
markdown
undefined

In .claude/agents/team-lead.md

In .claude/agents/team-lead.md


name: team-lead description: Coordinates multiple specialized agents team:
  • backend-api
  • frontend-expert
  • database-admin
  • security-auditor

I coordinate specialized agents to solve complex problems.
When given a task, I:
  1. Break it into domain-specific subtasks
  2. Delegate to appropriate specialists
  3. Synthesize their outputs
  4. Ensure consistency across domains
undefined

name: team-lead description: Coordinates multiple specialized agents team:
  • backend-api
  • frontend-expert
  • database-admin
  • security-auditor

I coordinate specialized agents to solve complex problems.
When given a task, I:
  1. Break it into domain-specific subtasks
  2. Delegate to appropriate specialists
  3. Synthesize their outputs
  4. Ensure consistency across domains
undefined

Scheduled Tasks

定时任务

Create Scheduled Command (
.claude/commands/daily-health-check.md
):
markdown
---
name: daily-health-check
description: Daily codebase health assessment
schedule: "0 9 * * *"  # 9 AM daily
---

Perform daily health check:

1. Run test suite and report failures
2. Check for dependency vulnerabilities
3. Analyze code quality metrics
4. Review open pull requests
5. Check CI/CD pipeline status

Email summary to: ${TEAM_EMAIL}
Manual Scheduling:
bash
/schedule daily-health-check "0 9 * * *"
创建定时命令
.claude/commands/daily-health-check.md
):
markdown
---
name: daily-health-check
description: Daily codebase health assessment
schedule: "0 9 * * *"  # 9 AM daily
---

Perform daily health check:

1. Run test suite and report failures
2. Check for dependency vulnerabilities
3. Analyze code quality metrics
4. Review open pull requests
5. Check CI/CD pipeline status

Email summary to: ${TEAM_EMAIL}
手动调度:
bash
/schedule daily-health-check "0 9 * * *"

Worktrees (Git Isolation)

工作树(Git隔离)

Create Isolated Environment:
bash
claude --worktree feature/new-api
In Command:
markdown
---
name: safe-refactor
description: Refactor in isolated worktree
isolation: worktree
---

Safely refactor {component} by:
1. Creating clean worktree
2. Running comprehensive tests
3. Applying changes incrementally
4. Validating each step
创建隔离环境:
bash
claude --worktree feature/new-api
在命令中使用:
markdown
---
name: safe-refactor
description: Refactor in isolated worktree
isolation: worktree
---

Safely refactor {component} by:
1. Creating clean worktree
2. Running comprehensive tests
3. Applying changes incrementally
4. Validating each step

Ultrareview

Ultrareview

Start Deep Code Review:
bash
/ultrareview src/
Track Progress:
bash
/ultrareview --status
In settings.json:
json
{
  "ultrareview": {
    "depth": "thorough",
    "focus": ["security", "performance", "maintainability"],
    "excludePatterns": ["*.test.ts", "*.spec.ts"]
  }
}
启动深度代码审查:
bash
/ultrareview src/
跟踪进度:
bash
/ultrareview --status
在settings.json中配置:
json
{
  "ultrareview": {
    "depth": "thorough",
    "focus": ["security", "performance", "maintainability"],
    "excludePatterns": ["*.test.ts", "*.spec.ts"]
  }
}

Real-World Patterns

真实场景模式

Full-Stack Feature Development

全栈功能开发

Command (
.claude/commands/new-feature.md
):
markdown
---
name: new-feature
description: Scaffold complete full-stack feature
---

Create feature: {feature_name}
命令
.claude/commands/new-feature.md
):
markdown
---
name: new-feature
description: Scaffold complete full-stack feature
---

Create feature: {feature_name}

Backend (@backend-api)

Backend (@backend-api)

  1. Create data model in
    src/models/{feature_name}.py
  2. Create API routes in
    src/routes/{feature_name}.py
  3. Add database migration
  4. Write integration tests
  1. Create data model in
    src/models/{feature_name}.py
  2. Create API routes in
    src/routes/{feature_name}.py
  3. Add database migration
  4. Write integration tests

Frontend (@frontend-expert)

Frontend (@frontend-expert)

  1. Create React components in
    src/components/{feature_name}/
  2. Add API client methods
  3. Implement form validation
  4. Add unit tests
  1. Create React components in
    src/components/{feature_name}/
  2. Add API client methods
  3. Implement form validation
  4. Add unit tests

Integration (@integration-agent)

Integration (@integration-agent)

  1. Verify API contract
  2. Test error scenarios
  3. Validate loading states
  4. Check accessibility
  1. Verify API contract
  2. Test error scenarios
  3. Validate loading states
  4. Check accessibility

Documentation

Documentation

  1. Update OpenAPI spec
  2. Add component Storybook stories
  3. Update README.md
undefined
  1. Update OpenAPI spec
  2. Add component Storybook stories
  3. Update README.md
undefined

Security Audit Workflow

安全审计工作流

Command (
.claude/commands/security-audit.md
):
markdown
---
name: security-audit
description: Comprehensive security review
---
命令
.claude/commands/security-audit.md
):
markdown
---
name: security-audit
description: Comprehensive security review
---

Phase 1: Dependency Check

Phase 1: Dependency Check

@security-auditor scan dependencies:
bash
npm audit
pip-audit
@security-auditor scan dependencies:
bash
npm audit
pip-audit

Phase 2: Code Analysis

Phase 2: Code Analysis

@security-auditor review for:
  • SQL injection vulnerabilities
  • XSS attack vectors
  • Authentication bypass risks
  • Exposed secrets
@security-auditor review for:
  • SQL injection vulnerabilities
  • XSS attack vectors
  • Authentication bypass risks
  • Exposed secrets

Phase 3: Configuration Review

Phase 3: Configuration Review

@security-auditor check:
  • CORS policies
  • CSP headers
  • Environment variable usage
  • API rate limiting
@security-auditor check:
  • CORS policies
  • CSP headers
  • Environment variable usage
  • API rate limiting

Phase 4: Report

Phase 4: Report

Generate security report with:
  • Critical findings (immediate action)
  • Medium priority issues
  • Recommendations
  • Remediation steps
undefined
Generate security report with:
  • Critical findings (immediate action)
  • Medium priority issues
  • Recommendations
  • Remediation steps
undefined

Database Migration Pattern

数据库迁移模式

Agent (
.claude/agents/database-admin.md
):
markdown
---
name: database-admin
description: Database schema and migration expert
model: claude-3-7-sonnet-20250219
---

Expert in database design and migrations.
智能体
.claude/agents/database-admin.md
):
markdown
---
name: database-admin
description: Database schema and migration expert
model: claude-3-7-sonnet-20250219
---

Expert in database design and migrations.

Migration Template

Migration Template

python
"""
Migration: {description}
Created: {timestamp}
"""

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'table_name',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('created_at', sa.DateTime, nullable=False),
    )
    
    # Add indexes
    op.create_index('ix_table_name_id', 'table_name', ['id'])

def downgrade():
    op.drop_index('ix_table_name_id')
    op.drop_table('table_name')
python
"""
Migration: {description}
Created: {timestamp}
"""

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'table_name',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('created_at', sa.DateTime, nullable=False),
    )
    
    # Add indexes
    op.create_index('ix_table_name_id', 'table_name', ['id'])

def downgrade():
    op.drop_index('ix_table_name_id')
    op.drop_table('table_name')

Safety Checks

Safety Checks

  • Always provide downgrade path
  • Test migration on copy of production data
  • Add indexes for foreign keys
  • Use transactions where possible
undefined
  • Always provide downgrade path
  • Test migration on copy of production data
  • Add indexes for foreign keys
  • Use transactions where possible
undefined

Troubleshooting

故障排除

Agent Not Found

智能体未找到

bash
undefined
bash
undefined

List available agents

列出可用智能体

ls .claude/agents/
ls .claude/agents/

Verify agent syntax

验证智能体语法

@agent-name --help
undefined
@agent-name --help
undefined

Command Fails

命令执行失败

bash
undefined
bash
undefined

Check command definition

检查命令定义

cat .claude/commands/command-name.md
cat .claude/commands/command-name.md

View command output

查看命令输出

/command-name --verbose
undefined
/command-name --verbose
undefined

MCP Server Issues

MCP服务器问题

bash
undefined
bash
undefined

Test MCP server

测试MCP服务器

npx @modelcontextprotocol/server-github --help
npx @modelcontextprotocol/server-github --help

Check environment variables

检查环境变量

echo $GITHUB_TOKEN
echo $GITHUB_TOKEN

Validate .mcp.json

验证.mcp.json

jq . .mcp.json
undefined
jq . .mcp.json
undefined

Permission Errors

权限错误

json
{
  "permissions": {
    "read": ["**/*"],
    "write": ["src/**", "!src/config/**"],
    "execute": ["scripts/**/*.sh"]
  }
}
json
{
  "permissions": {
    "read": ["**/*"],
    "write": ["src/**", "!src/config/**"],
    "execute": ["scripts/**/*.sh"]
  }
}

Hook Not Executing

钩子未执行

bash
undefined
bash
undefined

Verify executable permission

验证可执行权限

chmod +x .claude/hooks/BeforeFileEdit.sh
chmod +x .claude/hooks/BeforeFileEdit.sh

Test hook directly

直接测试钩子

.claude/hooks/BeforeFileEdit.sh "test.txt"
.claude/hooks/BeforeFileEdit.sh "test.txt"

Check hook output

检查钩子输出

cat ~/.claude/logs/hooks.log
undefined
cat ~/.claude/logs/hooks.log
undefined

Best Practices Summary

最佳实践总结

  1. Agents: Keep focused, use appropriate models, define clear boundaries
  2. Commands: Document parameters, handle errors, provide examples
  3. Skills: Include real code, cover common patterns, troubleshoot
  4. Workflows: Break into phases, coordinate agents, validate steps
  5. MCP: Secure credentials, test servers, handle failures
  6. Hooks: Keep fast, handle errors, log actions
  7. Settings: Version control, document choices, test changes
  8. Memory: Keep updated, be specific, include decisions
  1. 智能体:保持专注,使用合适的模型,定义清晰边界
  2. 命令:记录参数,处理错误,提供示例
  3. 技能:包含真实代码,覆盖常见模式,提供故障排除方法
  4. 工作流:拆分为多个阶段,协调智能体,验证每个步骤
  5. MCP:安全存储凭证,测试服务器,处理故障
  6. 钩子:保持执行快速,处理错误,记录操作
  7. 设置:版本控制,记录选择,测试变更
  8. 记忆:保持更新,内容具体,包含决策信息

Resources

资源