Initial commit to new repository
This commit is contained in:
38
docs/claude-code-docs-main/00_목차.md
Normal file
38
docs/claude-code-docs-main/00_목차.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Claude Code 공식 문서 (한국어 번역)
|
||||
|
||||
> 출처: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> 번역 일자: 2026-04-01
|
||||
|
||||
---
|
||||
|
||||
## 문서 목록
|
||||
|
||||
### 소개
|
||||
- [01_소개.md](./01_소개.md) — Claude Code란 무엇인가
|
||||
- [02_빠른시작.md](./02_빠른시작.md) — 5분 안에 시작하기
|
||||
- [03_설치.md](./03_설치.md) — 설치 상세 가이드
|
||||
|
||||
### 핵심 개념
|
||||
- [04_작동원리.md](./04_작동원리.md) — Claude Code가 어떻게 생각하고 행동하는가
|
||||
- [05_메모리와컨텍스트.md](./05_메모리와컨텍스트.md) — CLAUDE.md 메모리 시스템
|
||||
- [06_권한시스템.md](./06_권한시스템.md) — 퍼미션 모드와 허용/차단 규칙
|
||||
- [07_도구목록.md](./07_도구목록.md) — 사용 가능한 도구들
|
||||
|
||||
### 설정
|
||||
- [08_CLAUDE.md설정.md](./08_CLAUDE.md설정.md) — 프로젝트 메모리 파일 작성법
|
||||
- [09_환경변수.md](./09_환경변수.md) — 환경 변수 레퍼런스
|
||||
- [10_설정파일.md](./10_설정파일.md) — settings.json 레퍼런스
|
||||
|
||||
### 가이드
|
||||
- [11_인증.md](./11_인증.md) — 인증 방법 (OAuth, API 키, Bedrock, Vertex)
|
||||
- [12_훅.md](./12_훅.md) — 훅 시스템 가이드
|
||||
- [13_MCP서버.md](./13_MCP서버.md) — MCP 서버 연결 및 관리
|
||||
- [14_멀티에이전트.md](./14_멀티에이전트.md) — 서브에이전트와 병렬 작업
|
||||
- [15_스킬.md](./15_스킬.md) — 재사용 가능한 스킬 만들기
|
||||
|
||||
### 레퍼런스
|
||||
- [16_커맨드개요.md](./16_커맨드개요.md) — CLI 플래그 vs 슬래시 커맨드
|
||||
- [17_CLI플래그.md](./17_CLI플래그.md) — 모든 CLI 플래그 상세
|
||||
- [18_슬래시커맨드.md](./18_슬래시커맨드.md) — 세션 내 슬래시 커맨드
|
||||
- [19_훅레퍼런스.md](./19_훅레퍼런스.md) — 훅 이벤트 전체 레퍼런스
|
||||
- [20_SDK개요.md](./20_SDK개요.md) — SDK stdin/stdout 제어 프로토콜
|
||||
54
docs/claude-code-docs-main/01_소개.md
Normal file
54
docs/claude-code-docs-main/01_소개.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# 소개
|
||||
|
||||
> Claude Code는 터미널에서 실행되는 AI 코딩 에이전트로, 전체 코드베이스에 걸쳐 코드를 읽고, 편집하고, 실행합니다.
|
||||
|
||||
Claude Code는 Claude를 기반으로 만들어진 터미널 기반 AI 에이전트입니다. 파일 시스템, 셸, 도구에 직접 접근할 수 있어서, 자연어로 작업을 설명하면 Claude가 처음부터 끝까지 구현을 처리합니다 — 복사&붙여넣기 없이, 컨텍스트 전환 없이.
|
||||
|
||||
## Claude Code가 할 수 있는 일
|
||||
|
||||
- **파일 읽기 및 편집** — 소스 파일을 읽고, 새 내용을 작성하고, 정밀하게 편집합니다. 변경 사항을 적용하기 전에 diff를 보여줘서 사용자가 통제권을 유지합니다.
|
||||
- **셸 커맨드 실행** — 테스트, 빌드 스크립트, git 작업 등 모든 셸 커맨드를 실행합니다. 설정 가능한 권한 제어로 안전성을 보장합니다.
|
||||
- **코드베이스 검색** — glob 패턴으로 파일을 찾고, 정규식으로 내용을 검색하며, 모든 파일을 수동으로 읽지 않아도 대규모 코드베이스를 탐색합니다.
|
||||
- **웹에서 정보 가져오기** — 문서를 가져오거나, API 스펙을 읽거나, 웹을 검색합니다 — 모두 터미널 세션에서 벗어나지 않고.
|
||||
- **서브에이전트 생성** — 복잡한 작업을 병렬 워크스트림으로 분리합니다. Claude가 여러 에이전트를 스폰하고 조율해서 문제의 각 부분을 동시에 처리합니다.
|
||||
- **MCP 서버 연결** — 데이터베이스, API, 내부 도구 등을 위한 Model Context Protocol 서버로 Claude의 역량을 확장합니다.
|
||||
|
||||
## 권한 시스템
|
||||
|
||||
Claude Code의 모든 도구 사용은 권한 확인을 거칩니다. 사용자가 Claude에게 얼마나 많은 자율성을 줄지 제어합니다.
|
||||
|
||||
| 모드 | 동작 |
|
||||
|------|------|
|
||||
| `default` | 셸 커맨드 실행 및 편집 전에 Claude가 확인을 요청합니다. 각 작업을 승인하거나 거부할 수 있습니다. |
|
||||
| `acceptEdits` | 파일 편집이 자동으로 적용됩니다. 셸 커맨드는 여전히 승인이 필요합니다. |
|
||||
| `plan` | Claude가 계획을 만들고 어떤 작업도 실행하기 전에 승인을 요청합니다. 큰 변경 사항이 발생하기 전에 검토하기 좋습니다. |
|
||||
| `bypassPermissions` | 모든 작업이 프롬프트 없이 실행됩니다. 샌드박스 환경의 자동화 파이프라인 전용 — 대화형 사용에는 적합하지 않습니다. |
|
||||
|
||||
> ⚠️ `bypassPermissions` 모드는 모든 확인 프롬프트를 비활성화합니다. Claude가 작업 범위 외부의 시스템에 영향을 줄 수 없는 격리된 환경(Docker 컨테이너, CI 샌드박스)에서만 사용하세요.
|
||||
|
||||
시작 시 `--permission-mode` 플래그로 설정하거나, 세션 중 `/permissions`로 변경하세요:
|
||||
|
||||
```bash
|
||||
claude --permission-mode acceptEdits
|
||||
```
|
||||
|
||||
## CLAUDE.md 메모리 시스템
|
||||
|
||||
Claude Code는 매 세션 시작 시 저장소의 `CLAUDE.md` 파일을 읽습니다. 이 파일을 통해 프로젝트별 지식 — 빌드 커맨드, 코딩 컨벤션, 아키텍처 노트, 필요한 환경 변수 등 — 을 인코딩할 수 있어서, Claude가 매번 처음부터 다시 발견할 필요가 없습니다.
|
||||
|
||||
세 가지 범위:
|
||||
|
||||
- **프로젝트** (`CLAUDE.md` — 저장소 루트) — 팀 전체가 공유, 소스 컨트롤에 커밋
|
||||
- **개인** (`CLAUDE.local.md` — 저장소 루트) — 이 프로젝트에 대한 개인 설정, gitignore됨
|
||||
- **서브디렉토리** (서브디렉토리 안의 `CLAUDE.md`) — Claude가 해당 디렉토리에서 작업할 때 자동으로 로드됨. 별개의 모듈이 있는 모노레포에 유용
|
||||
|
||||
Claude Code 세션 안에서 `/init`을 실행하면 프로젝트의 `CLAUDE.md`가 자동으로 생성됩니다.
|
||||
|
||||
> 💡 `CLAUDE.md`는 간결하게 유지하세요. 모든 줄이 이 테스트를 통과해야 합니다: "이것을 제거하면 Claude가 실수를 할까?" 그렇지 않다면 삭제하세요.
|
||||
|
||||
## 인증
|
||||
|
||||
Claude Code는 두 가지 방식으로 인증합니다:
|
||||
|
||||
1. **OAuth (권장)** — `claude.ai`에서 Anthropic 계정으로 로그인. 처음 `claude`를 실행하면 브라우저 프롬프트가 나타납니다.
|
||||
2. **API 키** — `ANTHROPIC_API_KEY` 환경 변수를 설정. CI 파이프라인과 비대화형 세션에 유용합니다.
|
||||
127
docs/claude-code-docs-main/02_빠른시작.md
Normal file
127
docs/claude-code-docs-main/02_빠른시작.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# 빠른 시작
|
||||
|
||||
> Claude Code를 설치하고, 인증하고, 5분 안에 첫 번째 코딩 작업을 완료하세요.
|
||||
|
||||
## 사전 요구사항
|
||||
|
||||
- Node.js 18 이상
|
||||
- npm
|
||||
|
||||
Node.js 버전 확인:
|
||||
|
||||
```bash
|
||||
node --version
|
||||
```
|
||||
|
||||
Node.js를 설치하거나 업그레이드해야 한다면 [nodejs.org](https://nodejs.org)에서 다운로드하세요.
|
||||
|
||||
---
|
||||
|
||||
## 1단계: Claude Code 설치
|
||||
|
||||
npm으로 전역 설치:
|
||||
|
||||
```bash
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
설치 확인:
|
||||
|
||||
```bash
|
||||
claude --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2단계: 인증
|
||||
|
||||
아무 디렉토리에서나 `claude`를 실행해 최초 설정을 시작:
|
||||
|
||||
```bash
|
||||
claude
|
||||
```
|
||||
|
||||
처음 실행하면, Claude Code가 브라우저를 열고 Anthropic 계정으로 로그인하는 과정을 안내합니다. 완료하면 자격 증명이 안전하게 저장되어 이후 세션에서 재사용됩니다.
|
||||
|
||||
**대안으로**, OAuth를 사용하지 않으려면 API 키를 직접 설정하세요:
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
|
||||
> 📝 `ANTHROPIC_API_KEY` 환경 변수가 설정되어 있으면 API 키가 우선합니다. 대화형 사용에는 OAuth가 권장됩니다 — 토큰 갱신을 자동으로 처리합니다.
|
||||
|
||||
---
|
||||
|
||||
## 3단계: 프로젝트로 이동
|
||||
|
||||
Claude Code는 현재 디렉토리 내에서 작동합니다. 작업하려는 프로젝트로 이동하세요:
|
||||
|
||||
```bash
|
||||
cd my-project
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4단계: 대화형 세션 시작
|
||||
|
||||
`claude`를 실행해 대화형 세션을 열기:
|
||||
|
||||
```bash
|
||||
claude
|
||||
```
|
||||
|
||||
자연어로 작업을 입력할 수 있는 프롬프트가 나타납니다. Claude가 프로젝트 파일을 읽고, 커맨드를 실행하고, 지시에 따라 변경 사항을 만듭니다.
|
||||
|
||||
**첫 번째로 시도할 예제 작업들:**
|
||||
|
||||
```
|
||||
> 이 코드베이스의 구조를 설명해줘
|
||||
> 회원가입 폼에 입력 검증 추가해줘
|
||||
> UserService 클래스에 대한 테스트 작성해줘
|
||||
> 에러를 잡고 무시하는 곳을 모두 찾아줘
|
||||
```
|
||||
|
||||
Claude는 권한이 필요한 변경 사항을 만들기 전에 계획을 보여줍니다. 각 단계에서 승인하거나, 거부하거나, 다른 접근 방식을 요청할 수 있습니다.
|
||||
|
||||
---
|
||||
|
||||
## 5단계: CLAUDE.md 파일 초기화
|
||||
|
||||
세션 안에서 `/init`을 실행해 프로젝트의 `CLAUDE.md` 파일을 생성:
|
||||
|
||||
```
|
||||
/init
|
||||
```
|
||||
|
||||
Claude가 저장소를 분석하여 — 매니페스트 파일, 기존 문서, 코드 구조를 읽어 — 코드베이스에서 효과적으로 작업하는 데 필요한 커맨드와 컨텍스트를 담은 `CLAUDE.md`를 생성합니다. 커밋하기 전에 생성된 파일을 검토하고 편집하세요.
|
||||
|
||||
> 💡 `CLAUDE.md`는 매 세션 시작 시 로드됩니다. 비표준 빌드 커맨드, 테스트 특이사항, 팀 고유의 코딩 컨벤션 등을 기록하기 가장 좋은 곳입니다.
|
||||
|
||||
---
|
||||
|
||||
## 비대화형 커맨드 실행
|
||||
|
||||
`-p` 플래그를 사용해 단일 작업을 실행하고 결과를 출력합니다 — 대화형 세션에 들어가지 않고. 스크립팅이나 일회성 쿼리에 유용합니다:
|
||||
|
||||
```bash
|
||||
claude -p "이 코드베이스를 설명해줘"
|
||||
claude -p "src/ 안의 모든 TODO 주석과 파일을 나열해줘"
|
||||
claude -p "src/ 안의 미사용 export를 확인해줘"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 핵심 슬래시 커맨드
|
||||
|
||||
대화형 세션 안에서 가장 유용한 슬래시 커맨드들:
|
||||
|
||||
| 커맨드 | 설명 |
|
||||
|--------|------|
|
||||
| `/help` | 사용 가능한 커맨드와 키보드 단축키 표시 |
|
||||
| `/init` | 현재 프로젝트의 `CLAUDE.md` 생성 또는 업데이트 |
|
||||
| `/memory` | 메모리 파일(`CLAUDE.md`, `CLAUDE.local.md`) 보기 및 편집 |
|
||||
| `/permissions` | 현재 권한 모드 보기 또는 변경 |
|
||||
| `/mcp` | 연결된 MCP 서버 관리 |
|
||||
| `/clear` | 현재 대화 컨텍스트 지우기 |
|
||||
| `/exit` | 세션 종료 |
|
||||
253
docs/claude-code-docs-main/03_설치.md
Normal file
253
docs/claude-code-docs-main/03_설치.md
Normal file
@@ -0,0 +1,253 @@
|
||||
# 설치
|
||||
|
||||
> macOS, Linux, Windows(WSL 경유)에 Claude Code를 설치합니다. Node.js 18 이상이 필요합니다.
|
||||
|
||||
## 요구사항
|
||||
|
||||
- **Node.js 18 이상** — Claude Code는 시작 시 Node.js 버전을 확인하고, 18 미만이면 오류와 함께 종료합니다.
|
||||
- **npm** — Node.js에 포함되어 있습니다.
|
||||
|
||||
현재 버전 확인:
|
||||
|
||||
```bash
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Claude Code 설치
|
||||
|
||||
npm으로 전역 설치:
|
||||
|
||||
```bash
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
설치 후 동작 확인:
|
||||
|
||||
```bash
|
||||
claude --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 플랫폼별 안내
|
||||
|
||||
### macOS
|
||||
|
||||
macOS에서는 npm 전역 설치가 기본적으로 작동합니다. `npm install -g` 실행 시 권한 오류가 발생하면 두 가지 옵션이 있습니다:
|
||||
|
||||
**옵션 A: npm 권한 수정 (권장)**
|
||||
|
||||
홈 폴더의 디렉토리를 사용하도록 npm을 설정:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.npm-global
|
||||
npm config set prefix ~/.npm-global
|
||||
```
|
||||
|
||||
셸 프로파일(`~/.zshrc` 또는 `~/.bash_profile`)에 다음 추가:
|
||||
|
||||
```bash
|
||||
export PATH=~/.npm-global/bin:$PATH
|
||||
```
|
||||
|
||||
프로파일 다시 로드 후 설치:
|
||||
|
||||
```bash
|
||||
source ~/.zshrc
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
**옵션 B: Node 버전 관리자 사용**
|
||||
|
||||
[nvm](https://github.com/nvm-sh/nvm) 또는 [fnm](https://github.com/Schniz/fnm) 같은 도구는 홈 디렉토리에 Node.js를 설치해서 전역 권한 문제를 완전히 피할 수 있습니다:
|
||||
|
||||
```bash
|
||||
# nvm 사용
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
대부분의 Linux 배포판에서 `npm install -g`는 `sudo` 또는 npm prefix 수정이 필요합니다. `sudo` 사용은 나중에 권한 문제를 일으킬 수 있으므로 권장하지 않습니다.
|
||||
|
||||
**권장: Node 버전 관리자 사용**
|
||||
|
||||
```bash
|
||||
# nvm 설치
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
|
||||
|
||||
# 셸 다시 로드 후 Node.js 설치
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
|
||||
# Claude Code 설치
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
**대안: npm 전역 prefix 수정**
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.npm-global
|
||||
npm config set prefix ~/.npm-global
|
||||
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
### Windows (WSL)
|
||||
|
||||
Claude Code는 Windows Subsystem for Linux(WSL)를 통해 Windows에서 실행됩니다. 커맨드 프롬프트나 PowerShell에서 직접 실행하는 것은 지원되지 않습니다.
|
||||
|
||||
**1단계: WSL 설치**
|
||||
|
||||
관리자 권한으로 PowerShell 열고 실행:
|
||||
|
||||
```powershell
|
||||
wsl --install
|
||||
```
|
||||
|
||||
메시지가 나타나면 재시작. 기본적으로 Ubuntu와 함께 WSL 2가 설치됩니다.
|
||||
|
||||
**2단계: WSL 터미널 열기**
|
||||
|
||||
시작 메뉴에서 Ubuntu를 실행하거나, PowerShell에서 `wsl`을 실행합니다.
|
||||
|
||||
**3단계: WSL 안에 Node.js 설치**
|
||||
|
||||
```bash
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
|
||||
source ~/.bashrc
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
```
|
||||
|
||||
**4단계: Claude Code 설치**
|
||||
|
||||
```bash
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
> 📝 항상 WSL 터미널 안에서 `claude`를 실행하세요 — Windows CMD나 PowerShell에서 실행하지 마세요. 프로젝트 파일은 WSL 파일시스템(`~/projects/` 등) 안에 있어야 최상의 성능을 발휘합니다. `/mnt/c/...`를 통한 Windows 파일 접근은 가능하지만 느립니다.
|
||||
|
||||
---
|
||||
|
||||
## 업데이트
|
||||
|
||||
최신 버전으로 업데이트:
|
||||
|
||||
```bash
|
||||
npm update -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
또는 Claude Code 내장 업데이트 커맨드 사용:
|
||||
|
||||
```bash
|
||||
claude update
|
||||
```
|
||||
|
||||
현재 버전 확인:
|
||||
|
||||
```bash
|
||||
claude --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 제거
|
||||
|
||||
Claude Code 제거:
|
||||
|
||||
```bash
|
||||
npm uninstall -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
`claude` 바이너리가 제거됩니다. `~/.claude/`의 설정 파일은 자동으로 제거되지 않습니다. 삭제하려면:
|
||||
|
||||
```bash
|
||||
rm -rf ~/.claude
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 문제 해결
|
||||
|
||||
### 설치 후 `claude` 커맨드를 찾을 수 없음
|
||||
|
||||
npm 전역 bin 디렉토리가 `PATH`에 없는 경우입니다.
|
||||
|
||||
npm이 전역 바이너리를 설치하는 위치 확인:
|
||||
|
||||
```bash
|
||||
npm config get prefix
|
||||
```
|
||||
|
||||
해당 경로의 `bin` 서브디렉토리를 `PATH`에 추가해야 합니다. 예를 들어 출력이 `/home/you/.npm-global`이면:
|
||||
|
||||
```bash
|
||||
export PATH=/home/you/.npm-global/bin:$PATH
|
||||
```
|
||||
|
||||
셸을 다시 로드(`source ~/.zshrc` 또는 새 터미널 열기) 후 다시 시도하세요.
|
||||
|
||||
### Node.js 버전이 18 미만
|
||||
|
||||
Claude Code는 Node.js 18 이상이 필요합니다. 시작 시 이 오류가 보이면:
|
||||
|
||||
```
|
||||
Error: Claude Code requires Node.js version 18 or higher.
|
||||
```
|
||||
|
||||
버전 관리자를 사용해 Node.js를 업그레이드하세요:
|
||||
|
||||
```bash
|
||||
# nvm
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
|
||||
# fnm
|
||||
fnm install --lts
|
||||
fnm use --lts
|
||||
```
|
||||
|
||||
### npm install -g 시 권한 거부
|
||||
|
||||
`sudo npm install -g`를 사용하지 마세요 — root 소유 파일이 남아 추가 문제를 일으킬 수 있습니다. 대신 npm prefix를 사용자 쓰기 가능 디렉토리로 수정하세요:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.npm-global
|
||||
npm config set prefix ~/.npm-global
|
||||
export PATH=~/.npm-global/bin:$PATH
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
### 첫 실행 시 인증 실패
|
||||
|
||||
브라우저 기반 OAuth 흐름이 실패하거나 브라우저를 사용할 수 없는 경우, 환경 변수로 API 키를 직접 설정하세요:
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
claude
|
||||
```
|
||||
|
||||
셸 프로파일에 추가하면 영구적으로 설정됩니다. API 키는 [Anthropic Console](https://console.anthropic.com)에서 발급받을 수 있습니다.
|
||||
|
||||
### Docker 또는 CI 환경에서 실행
|
||||
|
||||
비대화형 환경에서는 환경 변수로 인증하세요:
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
|
||||
비대화형으로 실행하려면 `-p` 플래그 사용:
|
||||
|
||||
```bash
|
||||
claude -p "테스트 스위트를 실행하고 실패를 보고해줘"
|
||||
```
|
||||
|
||||
샌드박스 컨테이너에서 권한 프롬프트 없이 Claude Code를 작동시켜야 한다면 `--dangerously-skip-permissions` 플래그를 사용하세요. 이 플래그는 Claude Code의 샌드박스 안전 검사를 통과한 환경(인터넷 접근 없음, 컨테이너 외부에서 root로 실행하지 않음)에서만 작동합니다.
|
||||
82
docs/claude-code-docs-main/04_작동원리.md
Normal file
82
docs/claude-code-docs-main/04_작동원리.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# 작동 원리
|
||||
|
||||
> 에이전틱 루프, 컨텍스트 로딩, 도구 실행 모델, 대화 생명주기에 대한 내부 동작 설명.
|
||||
|
||||
Claude Code는 터미널 기반 코딩 에이전트로, 연속적인 에이전틱 루프를 실행합니다. 요청을 읽고, 무엇을 해야 할지 추론하고, 도구를 호출하고, 결과를 관찰하고, 작업이 완료되거나 입력이 필요할 때까지 이를 반복합니다.
|
||||
|
||||
## 에이전틱 루프
|
||||
|
||||
모든 상호작용은 동일한 기본 사이클을 따릅니다:
|
||||
|
||||
1. **사용자가 메시지를 보냄** — 터미널에서 메시지를 입력하거나(대화형 모드), `--print` / stdin을 통해 전달합니다(비대화형/헤드리스 모드). 메시지는 대화 기록에 추가됩니다.
|
||||
|
||||
2. **컨텍스트 조립** — 모델을 호출하기 전에, Claude Code가 시스템 프롬프트를 조립합니다: 현재 날짜, git 상태(브랜치, 최근 커밋, 워킹트리 상태), 로드된 CLAUDE.md 메모리 파일들, 사용 가능한 도구 목록. 이 컨텍스트는 대화당 한 번 구성되고 메모이제이션됩니다.
|
||||
|
||||
3. **Claude가 추론하고 도구를 선택** — 조립된 대화가 Anthropic API로 전송됩니다. 모델이 작업에 대해 추론하고 하나 이상의 `tool_use` 블록을 출력합니다 — 각각 도구 이름과 구조화된 JSON 입력을 지정합니다.
|
||||
|
||||
4. **권한 확인** — 각 도구 호출을 실행하기 전에, Claude Code가 현재 권한 모드와 허용/차단 규칙을 평가합니다. 모드에 따라 자동 승인하거나, 확인을 요청하거나, 호출을 완전히 차단합니다.
|
||||
|
||||
5. **도구가 실행되고 결과를 반환** — 승인된 도구 호출이 실행됩니다. 결과(파일 내용, 명령어 출력, 검색 결과)는 `tool_result` 블록으로 대화에 추가됩니다.
|
||||
|
||||
6. **루프 계속** — 모델이 도구 결과를 받아 더 많은 도구를 호출하거나 최종 텍스트 응답을 생성합니다. 모델 턴에 도구 호출이 더 이상 없을 때까지 루프가 반복됩니다.
|
||||
|
||||
> 📝 루프는 전적으로 터미널 프로세스 안에서 실행됩니다. 원격 실행 서버가 없습니다 — 도구가 명시적으로 전송하지 않는 한(`WebFetch`, `WebSearch`, 또는 MCP 서버 등), 파일, 셸, 자격 증명이 사용자의 머신을 벗어나지 않습니다.
|
||||
|
||||
## 컨텍스트 로딩
|
||||
|
||||
각 대화 시작 시, Claude Code가 모든 API 호출에 앞에 추가되는 두 개의 컨텍스트 블록을 구성합니다:
|
||||
|
||||
**시스템 컨텍스트** (`context.ts`의 `getSystemContext()`로 조립):
|
||||
- **Git 상태** — 현재 브랜치, 기본/메인 브랜치, git 사용자명, `git status --short` 출력(2,000자 초과 시 자름), `git log --oneline`의 마지막 5개 커밋
|
||||
- **캐시 무효화 주입** — 디버깅 중 서버 측 프롬프트 캐시를 무효화하기 위해 내부적으로 사용되는 임시 문자열
|
||||
|
||||
**사용자 컨텍스트** (`context.ts`의 `getUserContext()`로 조립):
|
||||
- **CLAUDE.md 메모리** — 4단계 계층(managed → user → project → local)에서 발견된 모든 메모리 파일
|
||||
- **현재 날짜** — 모델이 항상 날짜를 알 수 있도록 `Today's date is YYYY-MM-DD`로 주입
|
||||
|
||||
두 컨텍스트 블록은 `lodash/memoize`를 사용해 대화 기간 동안 **메모이제이션**됩니다.
|
||||
|
||||
## 도구 실행 모델
|
||||
|
||||
Claude Code는 기본적으로 도구 호출을 자율적으로 실행하지 않습니다. 각 도구는 `checkPermissions` 메서드를 가지며, 그 결과가 다음 동작을 결정합니다:
|
||||
|
||||
| 권한 결과 | 동작 |
|
||||
|-----------|------|
|
||||
| `allow` | 도구가 즉시 실행되고 결과가 대화에 추가됩니다 |
|
||||
| `ask` | Claude Code가 일시 중지하고 확인 다이얼로그를 렌더링합니다 |
|
||||
| `deny` | 도구 호출이 거부되고 Claude가 오류 결과를 받습니다 |
|
||||
|
||||
안전하고 읽기 전용인 도구 호출(`Read`, `Glob`, `Grep` 등)은 일반적으로 모든 모드에서 자동 승인됩니다.
|
||||
|
||||
## 대화형 vs 비대화형(작업) 모드
|
||||
|
||||
**대화형(REPL) 모드** — 기본 경험. Claude Code가 React/Ink를 사용해 라이브 터미널 UI를 렌더링합니다. 에이전트가 작업하는 동안 스트리밍 출력, 도구 사용 확인, 스피너 애니메이션을 볼 수 있습니다. 메시지는 종료할 때까지 세션 전반에 걸쳐 유지됩니다.
|
||||
|
||||
**비대화형/프린트 모드** — `--print`로 활성화하거나 stdin을 파이핑합니다. UI가 렌더링되지 않습니다. 출력이 stdout에 기록되어 스크립트나 CI 파이프라인에서 캡처할 수 있습니다. 일회성 자동화 작업에 유용합니다.
|
||||
|
||||
### 서브에이전트 (Task 도구)
|
||||
|
||||
Claude가 `Task` 도구(`AgentTool`)를 통해 서브에이전트를 스폰할 수 있습니다. 각 서브에이전트는 격리된 대화와 선택적으로 제한된 도구 집합을 가진 자체 중첩된 에이전틱 루프를 실행합니다. 서브에이전트는 로컬(인프로세스) 또는 원격 컴퓨팅에서 실행될 수 있습니다. 서브에이전트가 완료되면 결과가 부모 에이전트로 반환됩니다.
|
||||
|
||||
## 대화 저장 및 재개
|
||||
|
||||
대화는 디스크의 JSON 트랜스크립트 파일로 저장됩니다(기본적으로 `~/.claude/`에). 각 대화에는 고유한 세션 ID가 있습니다. `--resume <session-id>`로 이전 대화를 재개하거나, `--resume`만으로 목록에서 선택할 수 있습니다.
|
||||
|
||||
대화가 재개될 때:
|
||||
- 전체 메시지 기록이 디스크에서 로드됩니다
|
||||
- 메모리 파일이 다시 발견되어 대화 최초 시작 시와 다를 수 있습니다
|
||||
- 권한 모드가 세션에 유지되지 않는 한 설정된 기본값으로 재설정됩니다
|
||||
|
||||
> 💡 긴 대화는 주기적으로 **컴팩트**됩니다 — 가장 오래된 메시지가 요약되어 컨텍스트 윈도우를 관리 가능하게 유지합니다. 원본 트랜스크립트 전체는 항상 디스크에 보존됩니다; 컴팩트는 API에 전송되는 내용에만 영향을 줍니다.
|
||||
|
||||
## 쿼리 엔진
|
||||
|
||||
내부적으로, 에이전틱 루프의 각 "턴"은 **쿼리** — `query.ts`에 대한 호출로, 현재 메시지 목록을 Anthropic API에 전송하고 응답을 스트리밍합니다 — 에 의해 구동됩니다. 쿼리 엔진이 처리하는 것들:
|
||||
|
||||
- 실시간으로 터미널에 토큰 출력 스트리밍
|
||||
- `tool_use` 블록을 적절한 도구 핸들러에 디스패치
|
||||
- 턴당 토큰 및 도구 호출 예산 적용
|
||||
- 도구 결과 수집 및 다음 모델 호출 전 추가
|
||||
- 컨텍스트 윈도우가 꽉 찰 때 컴팩트 트리거
|
||||
|
||||
각 도구에는 `maxResultSizeChars` 속성이 있습니다. 결과가 이 한계를 초과하면 내용이 임시 파일로 저장되고 모델이 파일 경로와 함께 미리보기를 받아, 대용량 출력으로 인한 컨텍스트 윈도우 오버플로우를 방지합니다.
|
||||
127
docs/claude-code-docs-main/05_메모리와컨텍스트.md
Normal file
127
docs/claude-code-docs-main/05_메모리와컨텍스트.md
Normal file
@@ -0,0 +1,127 @@
|
||||
# 메모리와 컨텍스트 (CLAUDE.md)
|
||||
|
||||
> Claude Code가 CLAUDE.md 메모리 파일을 어떻게 발견하고, 로드하고, 우선순위를 결정하는지 설명합니다.
|
||||
|
||||
Claude Code는 일반 마크다운 파일 기반의 계층적 메모리 시스템을 지원합니다. 파일 시스템의 여러 레벨에 있는 `CLAUDE.md` 파일에 지시사항을 작성해서 Claude의 동작을 전역적으로, 프로젝트별로, 또는 사용자별로 커스터마이징할 수 있습니다.
|
||||
|
||||
## 4단계 메모리 계층
|
||||
|
||||
메모리 파일은 다음 순서로 로드됩니다(낮은 우선순위 → 높은 우선순위). **나중에** 로드된 파일이 우선합니다. 컨텍스트 윈도우에서 나중에 나타나는 지시사항에 모델이 더 주의를 기울이기 때문입니다.
|
||||
|
||||
**1단계: Managed 메모리 (최저 우선순위)**
|
||||
- 경로: `/etc/claude-code/CLAUDE.md`
|
||||
- 관리자 또는 배포 도구가 설정한 시스템 전체 지시사항. 머신의 모든 사용자에게 적용됩니다.
|
||||
|
||||
**2단계: User 메모리**
|
||||
- 경로: `~/.claude/CLAUDE.md` 및 `~/.claude/rules/*.md`
|
||||
- 모든 프로젝트에 적용되는 개인 전역 지시사항. 선호하는 코드 스타일, 기본 언어, git 사용자명 등 개인 설정에 적합합니다. 이 파일은 어떤 저장소에도 커밋되지 않습니다.
|
||||
|
||||
**3단계: Project 메모리**
|
||||
- 경로(CWD까지 각 상위 디렉토리에서 확인): `CLAUDE.md`, `.claude/CLAUDE.md`, `.claude/rules/*.md`
|
||||
- 팀 전체가 공유하는 코드베이스에 커밋된 지시사항. 프로젝트 컨벤션, 아키텍처 노트, 테스트 커맨드에 이상적입니다.
|
||||
|
||||
**4단계: Local 메모리 (최고 우선순위)**
|
||||
- 경로: `CLAUDE.local.md` (각 상위 디렉토리에서 확인)
|
||||
- `.gitignore`에 추가해야 하는 개인 프로젝트별 재정의. 로컬 환경 경로, 개인 디버깅 노트 등에 사용합니다.
|
||||
|
||||
> 📝 현재 작업 디렉토리에 더 가까운 파일이 **나중에** 로드되어 **더 높은 우선순위**를 가집니다. 프로젝트 루트의 `CLAUDE.md`가 상위 디렉토리의 것보다 우선합니다.
|
||||
|
||||
## 파일 발견 알고리즘
|
||||
|
||||
Claude Code 시작 시, 현재 작업 디렉토리에서 **파일시스템 루트까지** 올라가며 각 레벨의 메모리 파일을 수집합니다. 발견 순서는 낮은 우선순위 파일이 먼저 조립된 컨텍스트에 나타나도록 보장합니다:
|
||||
|
||||
1. Managed 파일이 먼저 로드됩니다
|
||||
2. User 파일이 다음으로 로드됩니다
|
||||
3. Project 및 Local 파일은 **루트에서 CWD로 내려가며** 반복됩니다 — 상위 디렉토리가 하위 디렉토리보다 먼저 옵니다
|
||||
|
||||
> 📝 발견된 파일 목록은 대화 기간 동안 메모이제이션됩니다. `/memory`를 실행해 메모리 에디터를 열고 강제 리로드하거나, 세션을 재시작해 Claude Code 외부에서 만들어진 변경 사항을 반영합니다.
|
||||
|
||||
## `@include` 지시어
|
||||
|
||||
메모리 파일은 `@` 표기법으로 다른 파일을 참조할 수 있습니다. 참조된 파일은 포함하는 파일 이전에 별도 항목으로 컨텍스트에 삽입됩니다.
|
||||
|
||||
```markdown
|
||||
# My project CLAUDE.md
|
||||
|
||||
@./docs/architecture.md
|
||||
@./docs/conventions/typescript.md
|
||||
|
||||
커밋 전에 항상 `bun test`를 실행하세요.
|
||||
```
|
||||
|
||||
| 구문 | 해석 |
|
||||
|------|------|
|
||||
| `@filename` | 포함하는 파일 디렉토리 기준 상대 경로 |
|
||||
| `@./relative/path` | 명시적 상대 경로 |
|
||||
| `@~/home/path` | 사용자 홈 디렉토리 기준 경로 |
|
||||
| `@/absolute/path` | 절대 경로 |
|
||||
|
||||
**규칙:**
|
||||
- 코드 블록 및 인라인 코드 안의 `@include`는 무시됩니다
|
||||
- 순환 참조는 감지되어 건너뜁니다
|
||||
- 존재하지 않는 파일은 조용히 무시됩니다
|
||||
- 최대 include 깊이는 **5단계**입니다
|
||||
- 텍스트 기반 파일 형식만 포함됩니다(`.md`, `.ts`, `.py`, `.json` 등). 이미지와 PDF 같은 바이너리 파일은 건너뜁니다
|
||||
|
||||
## `.claude/rules/*.md` — 세분화된 규칙 파일
|
||||
|
||||
모든 것을 하나의 큰 `CLAUDE.md`에 넣는 대신, `.claude/rules/` 안의 여러 마크다운 파일로 지시사항을 나눌 수 있습니다:
|
||||
|
||||
```
|
||||
my-project/
|
||||
├── CLAUDE.md
|
||||
└── .claude/
|
||||
└── rules/
|
||||
├── testing.md
|
||||
├── typescript-style.md
|
||||
└── git-workflow.md
|
||||
```
|
||||
|
||||
모든 `.md` 파일은 자동으로 로드됩니다. 규칙 파일은 **경로 범위 프론트매터**도 지원합니다:
|
||||
|
||||
```markdown
|
||||
---
|
||||
paths:
|
||||
- "src/api/**"
|
||||
- "src/services/**"
|
||||
---
|
||||
|
||||
항상 의존성 주입을 사용하세요. 구체적인 구현을 직접 import하지 마세요.
|
||||
```
|
||||
|
||||
`paths`가 설정되면, 규칙 파일은 Claude가 해당 glob 패턴과 일치하는 파일을 작업할 때만 컨텍스트에 주입됩니다. 대규모 프로젝트에서 컨텍스트를 간결하게 유지합니다.
|
||||
|
||||
## 최대 파일 크기
|
||||
|
||||
단일 메모리 파일의 권장 최대 크기는 **40,000자**입니다. 이 한계를 초과하는 파일은 플래그 처리되고, Claude가 전체 내용을 읽지 못할 수 있습니다. 메모리 파일은 집중적이고 간결하게 유지하세요.
|
||||
|
||||
## 메모리가 Claude 동작에 미치는 영향
|
||||
|
||||
메모리 파일이 로드되면, 다음과 같은 프리픽스가 붙은 단일 컨텍스트 블록으로 조립됩니다:
|
||||
|
||||
> *"Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."*
|
||||
|
||||
즉, CLAUDE.md 파일의 지시사항이 Claude의 내장 기본값보다 우선합니다. 이를 활용해 프로젝트 컨벤션을 강제하거나, 특정 작업을 제한하거나, 도메인 지식을 주입할 수 있습니다.
|
||||
|
||||
## 각 레벨 사용 지침
|
||||
|
||||
| 레벨 | 용도 |
|
||||
|------|------|
|
||||
| **Managed 메모리** | 모든 사용자가 따라야 하는 조직 전체 정책, 보안 가이드라인 |
|
||||
| **User 메모리** (`~/.claude/CLAUDE.md`) | 모든 프로젝트에 걸쳐 적용되는 개인 선호도: 응답 언어, 커밋 메시지 스타일 |
|
||||
| **Project 메모리** (`CLAUDE.md`) | 팀과 공유하는 프로젝트 컨벤션: 테스트 실행 방법, 빌드 커맨드, 아키텍처 결정 |
|
||||
| **Local 메모리** (`CLAUDE.local.md`) | 특정 프로젝트의 개인 재정의: 로컬 환경 경로, 개인 디버깅 노트 |
|
||||
|
||||
## `/memory` 커맨드
|
||||
|
||||
Claude Code REPL 안에서 `/memory`를 실행해 메모리 파일 에디터를 엽니다. 현재 로드된 메모리 파일을 보여주고, 직접 편집하며, 저장 시 컨텍스트를 리로드합니다.
|
||||
|
||||
> 💡 Claude에게 직접 물어볼 수도 있습니다: *"CLAUDE.md에 항상 2칸 들여쓰기를 사용한다는 규칙을 추가해줘."* Claude가 적절한 메모리 파일을 찾아 지시사항을 작성합니다.
|
||||
|
||||
## 메모리 로딩 비활성화
|
||||
|
||||
| 방법 | 효과 |
|
||||
|------|------|
|
||||
| `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` | 모든 메모리 파일 로딩 완전 비활성화 |
|
||||
| `--bare` 플래그 | CWD 워크에서 메모리 파일 자동 발견 건너뜀 |
|
||||
| `claudeMdExcludes` 설정 | 건너뛸 메모리 파일 경로의 Glob 패턴 |
|
||||
131
docs/claude-code-docs-main/06_권한시스템.md
Normal file
131
docs/claude-code-docs-main/06_권한시스템.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# 권한 시스템
|
||||
|
||||
> Claude Code가 어떤 작업을 자동으로 수행하고 어떤 작업에 명시적 승인이 필요한지 제어하는 방법.
|
||||
|
||||
Claude Code는 로컬 머신에서 도구를 실행합니다 — 셸 커맨드 실행, 파일 편집, URL 가져오기. 권한 시스템은 Claude가 자동으로 수행하는 작업과 명시적 승인이 필요한 작업을 정밀하게 제어합니다.
|
||||
|
||||
## 권한이 제어하는 것
|
||||
|
||||
권한은 세 가지 작업 범주에 적용됩니다:
|
||||
|
||||
- **파일 작업** — `Read`, `Edit`, `Write` 도구를 통한 로컬 파일시스템 읽기, 편집, 쓰기
|
||||
- **Bash 커맨드** — `Bash` 도구를 통한 셸 커맨드 실행(설치, 빌드, git 작업, 임의 스크립트 포함)
|
||||
- **MCP 도구 호출** — 연결된 MCP 서버가 노출한 도구(데이터베이스 쿼리, API 호출, 브라우저 자동화 등)
|
||||
|
||||
## 권한 모드
|
||||
|
||||
권한 모드는 특정 허용/차단 규칙과 일치하는 도구 호출이 없을 때의 기본 동작을 결정합니다. 모드를 한 번 설정하면 세션 전체에 적용됩니다.
|
||||
|
||||
**`default` — 잠재적으로 위험한 작업에 확인 요청**
|
||||
표준 모드. 셸 커맨드 실행, 파일 편집, 네트워크 요청 등 부작용이 있을 수 있는 작업에 확인을 요청합니다. 파일 읽기, 검색 등 읽기 전용 작업은 자동 승인됩니다. 일상적인 사용에 권장됩니다.
|
||||
|
||||
**`acceptEdits` — 파일 편집 자동 승인**
|
||||
`Edit`, `Write` 도구가 프롬프트 없이 자동 승인됩니다. Bash 커맨드는 여전히 확인이 필요합니다. Claude가 파일을 자유롭게 편집하도록 하되 셸 커맨드는 검토하고 싶을 때 유용합니다.
|
||||
|
||||
**`plan` — 읽기 전용 계획 모드**
|
||||
Claude가 파일을 읽고, 코드베이스를 검색하고, 변경 사항에 대해 논의할 수 있지만 쓰기 또는 bash 작업을 실행할 수 없습니다. 모든 변경 도구 호출이 차단됩니다. Claude가 문제를 분석하고 변경 사항을 승인하기 전에 계획을 만들도록 할 때 사용하세요.
|
||||
|
||||
**`bypassPermissions` — 모든 권한 검사 건너뛰기**
|
||||
모든 권한 검사가 비활성화됩니다. 모든 도구 호출이 확인 프롬프트 없이 즉시 실행됩니다.
|
||||
> ⚠️ 이 모드는 Claude가 수행할 작업을 미리 감사한 완전 스크립트화된 자동화 워크플로우 전용입니다. Claude가 예기치 않은 작업을 취할 수 있는 대화형 세션에서는 절대 사용하지 마세요.
|
||||
|
||||
## 권한 모드 설정 방법
|
||||
|
||||
**CLI 플래그:**
|
||||
```bash
|
||||
claude --permission-mode acceptEdits
|
||||
claude --permission-mode bypassPermissions
|
||||
claude --permission-mode plan
|
||||
```
|
||||
|
||||
**`/permissions` 커맨드 (세션 중):**
|
||||
```
|
||||
/permissions
|
||||
```
|
||||
재시작 없이 모드를 변경합니다.
|
||||
|
||||
**settings.json:**
|
||||
```json
|
||||
{
|
||||
"defaultMode": "acceptEdits"
|
||||
}
|
||||
```
|
||||
유효한 값: `"default"`, `"acceptEdits"`, `"bypassPermissions"`, `"plan"`, `"dontAsk"`
|
||||
|
||||
## 권한 규칙 (허용/차단 목록)
|
||||
|
||||
전역 모드 외에도, 활성 모드에 관계없이 특정 도구 호출을 항상 허용하거나 항상 차단하는 세분화된 규칙을 만들 수 있습니다.
|
||||
|
||||
규칙은 세 가지 구성 요소를 가집니다:
|
||||
|
||||
| 필드 | 설명 |
|
||||
|------|------|
|
||||
| `toolName` | 규칙이 적용되는 도구 이름 (예: `"Bash"`, `"Edit"`, `"mcp__myserver"`) |
|
||||
| `ruleContent` | 도구 입력과 일치해야 하는 선택적 패턴 |
|
||||
| `behavior` | `"allow"`, `"deny"`, 또는 `"ask"` |
|
||||
|
||||
규칙은 권한 모드보다 **먼저** 평가됩니다. 일치하는 규칙이 있으면 해당 동작이 즉시 적용됩니다.
|
||||
|
||||
### 예시: 특정 git 커맨드 항상 허용
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git status)",
|
||||
"Bash(git diff *)",
|
||||
"Bash(git log *)",
|
||||
"Read(*)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(rm -rf *)",
|
||||
"Bash(sudo *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Bash 권한 작동 방식
|
||||
|
||||
**패턴 매칭:**
|
||||
- `git status` — 정확한 일치만
|
||||
- `git *` — 모든 `git` 서브커맨드와 일치
|
||||
- `npm run *` — 모든 `npm run` 스크립트와 일치
|
||||
- `*` — 모든 bash 커맨드와 일치 (극도의 주의 필요)
|
||||
|
||||
**복합 커맨드:**
|
||||
`&&`, `||`, `;`, 파이프(`|`)로 연결된 복합 커맨드는 각 서브커맨드가 독립적으로 검사됩니다. 하나의 서브커맨드라도 차단되면 전체 복합 커맨드가 차단됩니다.
|
||||
|
||||
**항상 차단/에스컬레이션되는 작업:**
|
||||
- 프로젝트 디렉토리 외부 경로로의 출력 리다이렉션(`>`, `>>`)
|
||||
- 워킹트리 외부로의 디렉토리 변경(`cd`)
|
||||
- `sed -i` 편집 인플레이스 커맨드(파일 수정 추적을 위해 특별 처리)
|
||||
- `.claude/` 또는 `.git/` 설정 디렉토리를 대상으로 하는 커맨드
|
||||
- 셸 설정 파일 수정(`.bashrc`, `.zshrc` 등)
|
||||
|
||||
## MCP 도구 권한
|
||||
|
||||
MCP 도구는 내장 도구와 동일한 규칙 시스템을 따릅니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": {
|
||||
"deny": [
|
||||
"mcp__myserver"
|
||||
],
|
||||
"allow": [
|
||||
"mcp__myserver__read_database"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`mcp__servername`을 규칙으로 사용하면(특정 도구 이름 없이) 해당 서버의 모든 도구가 차단됩니다 — 모델이 보기 전에 도구 목록에서 필터링됩니다.
|
||||
|
||||
## 보안 권장 사항
|
||||
|
||||
- **`default` 모드**로 모든 대화형 세션을 시작하세요
|
||||
- 익숙하지 않은 코드베이스를 탐색하거나 큰 변경 사항을 설계할 때는 **`plan` 모드**를 사용하세요
|
||||
- Claude가 파일을 자유롭게 편집하도록 하되 셸 커맨드는 검토하려면 **`acceptEdits`**를 사용하세요
|
||||
- 광범위한 모드 에스컬레이션 대신 **세분화된 허용 규칙**을 선호하세요. `Bash(git *)`를 허용하는 것이 `bypassPermissions`로 전환하는 것보다 안전합니다
|
||||
- 친숙하지 않은 저장소를 클론할 때 `.claude/settings.json`을 검토하세요 — 권한 규칙이 미리 설정되어 있을 수 있습니다
|
||||
102
docs/claude-code-docs-main/07_도구목록.md
Normal file
102
docs/claude-code-docs-main/07_도구목록.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# 도구 목록
|
||||
|
||||
> Claude Code가 사용할 수 있는 모든 내장 도구 레퍼런스 — 파일 작업, 셸 실행, 웹 접근, 서브에이전트 생성 포함.
|
||||
|
||||
## 파일 도구
|
||||
|
||||
**Read — 파일 읽기**
|
||||
로컬 파일시스템에서 파일을 읽습니다. 기본적으로 최대 2,000줄 읽기. 대용량 파일의 타겟 읽기를 위한 `offset`과 `limit` 지원. `cat -n` 형식으로 줄 번호와 함께 내용 반환. 이미지(PNG, JPG 등), PDF(한 번에 최대 20페이지), Jupyter 노트북(`.ipynb`) 읽기도 지원. 읽기 전용, 항상 자동 승인.
|
||||
|
||||
**Edit — 파일 편집**
|
||||
파일에서 정확한 문자열 교체를 수행합니다. 같은 대화에서 해당 파일을 먼저 `Read`해야 합니다. `old_string`을 `new_string`으로 교체 — 파일에서 유일하게 일치해야 합니다. 파일 전체에서 이름을 변경하려면 `replace_all: true` 사용. `old_string`이 두 번 이상 나타나면 실패합니다(replace_all이 설정되지 않은 경우).
|
||||
|
||||
**Write — 파일 생성/덮어쓰기**
|
||||
새 파일을 만들거나 기존 파일을 완전히 덮어씁니다. 기존 파일은 같은 대화에서 먼저 `Read`가 필요합니다. 기존 파일 수정에는 `Edit`를 선호하세요 — `Write`는 전체 파일 내용을 전송하며 새 파일이나 전체 재작성에 더 적합합니다.
|
||||
|
||||
**Glob — 파일 패턴 검색**
|
||||
이름 패턴으로 파일을 찾습니다. 어떤 코드베이스 크기에서도 작동하는 빠른 패턴 매칭. 수정 시간 기준으로 정렬된 매칭 파일 경로 반환. `**/*.ts`, `src/**/*.test.js`, `**/CLAUDE.md` 같은 패턴 지원. 읽기 전용, 항상 자동 승인.
|
||||
|
||||
## 셸 도구
|
||||
|
||||
**Bash — 셸 커맨드 실행**
|
||||
대화 내에서 지속되는 셸 세션에서 커맨드를 실행합니다. 도구 호출 간에 환경 변수와 작업 디렉토리 변경이 유지됩니다. `timeout` 파라미터 지원.
|
||||
|
||||
주요 동작:
|
||||
- **복합 커맨드** (`&&`, `||`, `;`, `|`) — 파싱되어 각 서브커맨드가 독립적으로 권한 검사됨
|
||||
- **백그라운드 실행** — `run_in_background: true`를 전달해 블로킹 없이 장시간 실행 커맨드 실행
|
||||
- **출력 제한** — stdout/stderr이 도구 결과 크기 예산을 초과하면 미리보기와 파일 경로가 반환됨
|
||||
- **검색 커맨드** — 콘텐츠 검색에는 최적화된 권한과 접근을 가진 전용 `Grep` 도구를 선호하세요
|
||||
|
||||
## 검색 도구
|
||||
|
||||
**Grep — 파일 내용 검색**
|
||||
정규식을 사용해 파일 내용을 검색합니다. ripgrep 기반. 전체 regex 구문, 파일 타입 필터링(`*.ts`, `**/*.py`), 세 가지 출력 모드 지원:
|
||||
- `files_with_matches` (기본) — 파일 경로만 반환
|
||||
- `content` — 컨텍스트와 함께 매칭된 줄 반환
|
||||
- `count` — 파일당 매칭 수 반환
|
||||
|
||||
`multiline: true`로 멀티라인 패턴 지원. 읽기 전용, 항상 자동 승인.
|
||||
|
||||
**LS — 디렉토리 내용 나열**
|
||||
구조화된 형식으로 파일과 서브디렉토리를 반환합니다. 파일을 읽거나 편집하기 전에 프로젝트 구조를 탐색하는 데 유용합니다. 읽기 전용, 항상 자동 승인.
|
||||
|
||||
## 웹 도구
|
||||
|
||||
**WebFetch — URL 가져오기**
|
||||
URL에서 정보를 가져와 추출합니다. HTML을 마크다운으로 변환한 후 보조 모델을 통해 집중된 답변을 생성합니다.
|
||||
- HTTP URL은 자동으로 HTTPS로 업그레이드됨
|
||||
- 15분 자가 정리 캐시 포함
|
||||
- URL이 다른 호스트로 리다이렉트되면 후속 요청을 위한 리다이렉트 URL 반환
|
||||
- GitHub URL의 경우 `gh` CLI를 통한 Bash 사용 권장
|
||||
|
||||
`default` 모드에서 승인 요청.
|
||||
|
||||
**WebSearch — 웹 검색**
|
||||
웹을 검색하고 결과를 반환합니다. 제목, 스니펫, URL을 마크다운 링크로 형식화해서 반환. 모델의 훈련 컷오프 이후 정보에 접근하는 데 유용합니다. 응답 후 Claude가 자동으로 참조된 모든 URL을 나열하는 `Sources:` 섹션을 추가합니다. 현재 미국에서만 이용 가능. `default` 모드에서 승인 요청.
|
||||
|
||||
## 에이전트 및 작업 도구
|
||||
|
||||
**Task (Agent) — 서브에이전트 생성**
|
||||
별도의 컨텍스트에서 서브에이전트를 시작합니다. 서브에이전트는 자체 대화 기록, 도구 집합(선택적으로 제한됨)을 가지고 완료될 때까지 실행한 후 부모 에이전트에 결과를 반환합니다.
|
||||
|
||||
서브에이전트 실행 방식:
|
||||
- **로컬** — 인프로세스, 부모의 파일시스템과 셸 공유
|
||||
- **원격** — 원격 에이전트 자격 기준이 충족될 때 별도 컴퓨팅에서 실행
|
||||
|
||||
개방형 다단계 검색, 병렬 워크스트림, 또는 독립된 서브 문제를 격리된 에이전트에 위임할 때 사용하세요.
|
||||
|
||||
**TodoWrite — 작업 목록 관리**
|
||||
구조화된 할 일 항목(`pending`, `in_progress`, `completed` 상태)을 터미널 UI의 영구 패널에 씁니다. Claude가 복잡한 다단계 작업의 진행 상황을 추적하는 데 도움이 됩니다. 3개 이상의 별개 단계가 있는 작업에 적극적으로 사용하세요.
|
||||
|
||||
## MCP 도구
|
||||
|
||||
MCP(Model Context Protocol) 서버가 Claude Code에 추가 도구를 노출할 수 있습니다. 연결된 도구는 내장 도구와 함께 도구 목록에 나타나며 동일한 권한 시스템을 따릅니다.
|
||||
|
||||
MCP 도구 이름 형식:
|
||||
```
|
||||
mcp__<server-name>__<tool-name>
|
||||
```
|
||||
|
||||
예: `mydb` 서버의 `query` 도구 → `mcp__mydb__query`
|
||||
|
||||
일반적인 MCP 도구 범주:
|
||||
- 데이터베이스 쿼리 및 관리 도구
|
||||
- 브라우저 및 웹 자동화 도구
|
||||
- 클라우드 제공업체 API (AWS, GCP, Azure)
|
||||
- 이슈 트래커 통합 (GitHub, Linear, Jira)
|
||||
- 내부 회사 도구 및 API
|
||||
|
||||
## 노트북 도구
|
||||
|
||||
**NotebookEdit — Jupyter 노트북 편집**
|
||||
`.ipynb` 파일의 셀을 줄 단위 정밀도로 삽입, 교체, 삭제합니다. 노트북 읽기는 표준 `Read` 도구를 사용합니다(모든 셀과 출력 반환).
|
||||
|
||||
## 도구 가용성
|
||||
|
||||
모든 도구가 모든 컨텍스트에서 이용 가능한 것은 아닙니다:
|
||||
- `CLAUDE_CODE_SIMPLE=1` — `Bash`, `Read`, `Edit`만으로 제한
|
||||
- 권한 차단 규칙 — 규칙으로 포괄 차단된 도구는 모델이 보기 전에 목록에서 제거됨
|
||||
- `isEnabled()` 검사 — 각 도구는 환경 조건에 따라 자가 비활성화 가능
|
||||
- MCP 서버 연결 상태 — MCP 도구는 서버가 실행 중이고 연결된 경우에만 이용 가능
|
||||
|
||||
REPL에서 `/tools` 커맨드로 활성 도구 집합을 확인할 수 있습니다.
|
||||
171
docs/claude-code-docs-main/08_CLAUDE.md설정.md
Normal file
171
docs/claude-code-docs-main/08_CLAUDE.md설정.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# CLAUDE.md 설정
|
||||
|
||||
> Claude에게 세션마다 자동으로 로드되는 지속적인 프로젝트별 지시사항을 주기 위한 CLAUDE.md 파일 작성 및 구성 방법.
|
||||
|
||||
`CLAUDE.md` 파일로 Claude가 모든 세션 시작 시 로드하는 프로젝트 지식을 인코딩할 수 있습니다. 매번 프로젝트 컨벤션, 빌드 시스템, 아키텍처를 설명하는 대신, 한 번 작성하면 Claude가 자동으로 읽습니다.
|
||||
|
||||
## CLAUDE.md에 들어가야 할 것
|
||||
|
||||
빠진 경우 실수를 일으킬 지시사항을 작성하세요. 그 외에는 노이즈입니다.
|
||||
|
||||
**포함할 것:**
|
||||
- 빌드, 테스트, lint 커맨드 (도구 이름만 아닌 정확한 호출)
|
||||
- 코드를 어떻게 작성하고 구성해야 하는지에 영향을 미치는 아키텍처 결정
|
||||
- 프로젝트 고유의 코딩 컨벤션 (네이밍 패턴, 파일 구조 규칙)
|
||||
- 환경 설정 요구사항 (필요한 env 변수, 예상 서비스)
|
||||
- Claude가 알아야 하는 일반적인 함정 또는 패턴
|
||||
- 모노레포 구조와 어떤 패키지가 어떤 책임을 가지는지
|
||||
|
||||
**제외할 것:**
|
||||
- Claude가 이미 아는 것 (표준 TypeScript 구문, 일반 라이브러리 API)
|
||||
- 자명한 알림 ("깔끔한 코드를 작성하세요", "주석을 추가하세요")
|
||||
- 민감한 데이터 — API 키, 비밀번호, 토큰, 또는 어떤 시크릿도
|
||||
- 자주 변경되어 오래될 정보
|
||||
|
||||
> 💡 테스트: "이 줄을 제거하면 Claude가 이 코드베이스에서 실수를 할까?" 그렇지 않다면 삭제하세요.
|
||||
|
||||
## 파일 위치
|
||||
|
||||
Claude는 현재 디렉토리에서 파일시스템 루트까지 올라가며 메모리 파일을 발견합니다. 현재 디렉토리에 더 가까운 파일이 더 높은 우선순위를 가집니다.
|
||||
|
||||
| 파일 | 타입 | 용도 |
|
||||
|------|------|------|
|
||||
| `/etc/claude-code/CLAUDE.md` | Managed | 관리자가 설정한 모든 사용자의 시스템 전체 지시사항 |
|
||||
| `~/.claude/CLAUDE.md` | User | 모든 프로젝트에 적용되는 개인 전역 지시사항 |
|
||||
| `~/.claude/rules/*.md` | User | 모듈식 전역 규칙, 각 파일이 별도로 로드됨 |
|
||||
| `CLAUDE.md` (프로젝트 루트) | Project | 소스 컨트롤에 커밋된 팀 공유 지시사항 |
|
||||
| `.claude/CLAUDE.md` (프로젝트 루트) | Project | 팀 공유 프로젝트 지시사항의 대안 위치 |
|
||||
| `.claude/rules/*.md` (프로젝트 루트) | Project | 주제별로 구성된 모듈식 프로젝트 규칙 |
|
||||
| `CLAUDE.local.md` (프로젝트 루트) | Local | 커밋되지 않는 개인 프로젝트별 지시사항 |
|
||||
|
||||
## 로딩 순서와 우선순위
|
||||
|
||||
파일은 다음 순서로 로드됩니다. 모델이 컨텍스트에서 나중에 나타나는 내용에 더 주의를 기울이기 때문에, 나중에 로드된 파일이 더 높은 실효 우선순위를 가집니다.
|
||||
|
||||
1. **Managed 메모리** — `/etc/claude-code/CLAUDE.md`와 `rules/*.md` — 항상 로드됨
|
||||
2. **User 메모리** — `~/.claude/CLAUDE.md`와 `rules/*.md` — 모든 프로젝트의 개인 전역 지시사항
|
||||
3. **Project 메모리 (루트에서 CWD까지)** — 파일시스템 루트에서 현재 디렉토리까지 각 디렉토리의 `CLAUDE.md`, `.claude/CLAUDE.md`, `.claude/rules/*.md`. CWD에 더 가까운 파일이 나중에 로드됨 (높은 우선순위)
|
||||
4. **Local 메모리** — 루트에서 CWD까지 각 디렉토리의 `CLAUDE.local.md`. 같은 순회 순서. 기본적으로 gitignore됨
|
||||
|
||||
## @include 지시어
|
||||
|
||||
메모리 파일은 `@` 표기법으로 다른 파일을 include할 수 있습니다:
|
||||
|
||||
```markdown
|
||||
# CLAUDE.md
|
||||
|
||||
@./docs/architecture.md
|
||||
@~/shared/style-guide.md
|
||||
@/etc/company-standards.md
|
||||
```
|
||||
|
||||
| 구문 | 해석 |
|
||||
|------|------|
|
||||
| `@filename` | 현재 파일 디렉토리 기준 상대 경로 |
|
||||
| `@./relative/path` | 현재 파일 디렉토리 기준 명시적 상대 경로 |
|
||||
| `@~/path/in/home` | 홈 디렉토리 아래 경로 |
|
||||
| `@/absolute/path` | 절대 파일시스템 경로 |
|
||||
|
||||
**동작:**
|
||||
- 비존재 파일은 조용히 무시됨
|
||||
- 순환 참조는 감지되고 방지됨
|
||||
- Include는 최대 5단계 깊이까지 중첩
|
||||
- 텍스트 파일 형식만 지원 — 이진 파일은 건너뜀
|
||||
- 코드 블록 안의 `@include`는 처리되지 않음
|
||||
|
||||
## 프론트매터 경로 타겟팅
|
||||
|
||||
`.claude/rules/`의 파일은 YAML 프론트매터로 어떤 파일 경로에 적용할지 제한할 수 있습니다:
|
||||
|
||||
```markdown
|
||||
---
|
||||
paths:
|
||||
- "src/api/**"
|
||||
- "*.graphql"
|
||||
---
|
||||
|
||||
# API 컨벤션
|
||||
|
||||
모든 API 핸들러는 공유 `validate()` 헬퍼로 입력을 검증해야 합니다.
|
||||
GraphQL 리졸버는 직접 데이터베이스 쿼리를 수행하면 안 됩니다 — 데이터 레이어를 사용하세요.
|
||||
```
|
||||
|
||||
프론트매터가 없는 규칙은 무조건 적용됩니다. `paths` 프론트매터가 있는 규칙은 Claude가 glob 패턴과 일치하는 파일을 작업할 때만 적용됩니다.
|
||||
|
||||
## TypeScript 프로젝트용 CLAUDE.md 예시
|
||||
|
||||
```markdown
|
||||
# Project: Payments API
|
||||
|
||||
## 빌드 및 테스트
|
||||
|
||||
- 빌드: `bun run build`
|
||||
- 테스트: `bun test` (Bun 내장 테스트 러너 사용 — Jest 사용하지 말 것)
|
||||
- Lint: `bun run lint` (biome, eslint 아님)
|
||||
- 타입 체크: `bun run typecheck`
|
||||
|
||||
변경 사항을 완료하기 전에 항상 `bun run typecheck`를 실행하세요.
|
||||
|
||||
## 아키텍처
|
||||
|
||||
- `src/handlers/` — HTTP 핸들러, 라우트 그룹당 하나의 파일
|
||||
- `src/services/` — 비즈니스 로직, 직접 DB 접근 없음
|
||||
- `src/db/` — 데이터베이스 레이어 (Drizzle ORM); 모든 쿼리가 여기에 있음
|
||||
- `src/schemas/` — 핸들러 검증과 DB 타입 간에 공유되는 Zod 스키마
|
||||
|
||||
핸들러는 서비스를 호출합니다. 서비스는 DB 레이어를 호출합니다. 레이어를 건너뛰지 마세요.
|
||||
|
||||
## 컨벤션
|
||||
|
||||
- 모든 입력 검증 스키마에 `z.object().strict()` 사용
|
||||
- 에러는 `Result<T, AppError>`로 전파 — 서비스 코드에서 절대 throw하지 말 것
|
||||
- 모든 금액 값은 센트 단위 정수
|
||||
- 타임스탬프는 Unix 초(number), Date 객체 아님
|
||||
|
||||
## 환경
|
||||
|
||||
필요한 env 변수: `DATABASE_URL`, `STRIPE_SECRET_KEY`, `JWT_SECRET`
|
||||
로컬 개발: `.env.example`을 `.env.local`로 복사하고 값 입력
|
||||
|
||||
## 피해야 할 일반적인 실수
|
||||
|
||||
- `new Date()`를 직접 사용하지 마세요 — `src/utils/time.ts`의 `getCurrentTimestamp()` 사용
|
||||
- `console.log` 추가하지 마세요 — `src/utils/logger.ts`의 `logger` 사용
|
||||
- Raw SQL 작성하지 마세요 — Drizzle 쿼리 빌더 사용
|
||||
```
|
||||
|
||||
## /init으로 CLAUDE.md 생성
|
||||
|
||||
Claude Code 세션에서 `/init`을 실행하면 프로젝트의 `CLAUDE.md`를 자동 생성합니다:
|
||||
|
||||
```
|
||||
/init
|
||||
```
|
||||
|
||||
Claude가 코드베이스를 분석하고 프로젝트와 가장 관련된 커맨드와 컨텍스트를 담은 파일을 생성합니다. 생성된 파일은 시작점입니다 — 검토하고, 진정으로 유용하지 않은 것은 제거하고, 코드에서 추론할 수 없는 프로젝트별 지식을 추가하세요.
|
||||
|
||||
## /memory로 CLAUDE.md 편집
|
||||
|
||||
`/memory`를 실행해 메모리 에디터를 열면 현재 로드된 모든 메모리 파일을 나열하고 세션 내에서 직접 편집할 수 있습니다:
|
||||
|
||||
```
|
||||
/memory
|
||||
```
|
||||
|
||||
변경 사항은 즉시 적용됩니다 — Claude가 업데이트된 파일을 리로드하고 새 지시사항을 현재 세션에 적용합니다.
|
||||
|
||||
## 파일 제외
|
||||
|
||||
Claude가 로드하지 않도록 할 CLAUDE.md 파일이 있다면(예: 벤더 의존성이나 생성된 코드에 있는 경우), 설정에 제외 패턴을 추가하세요:
|
||||
|
||||
```json
|
||||
{
|
||||
"claudeMdExcludes": [
|
||||
"/absolute/path/to/vendor/CLAUDE.md",
|
||||
"**/generated/**",
|
||||
"**/third-party/.claude/rules/**"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
패턴은 picomatch를 사용해 절대 경로와 매칭됩니다. User, Project, Local 메모리 타입만 제외 가능합니다 — Managed(관리자) 파일은 항상 로드됩니다.
|
||||
111
docs/claude-code-docs-main/09_환경변수.md
Normal file
111
docs/claude-code-docs-main/09_환경변수.md
Normal file
@@ -0,0 +1,111 @@
|
||||
# 환경 변수
|
||||
|
||||
> Claude Code가 인증, API 접근, 동작, 런타임 옵션을 설정하기 위해 읽는 환경 변수.
|
||||
|
||||
Claude Code는 시작 시 환경 변수를 읽습니다. 설정 파일을 수정하지 않고 인증 설정, 커스텀 API 엔드포인트, 런타임 동작 튜닝, 활성 기능 제어가 가능합니다.
|
||||
|
||||
## 인증
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `ANTHROPIC_API_KEY` | Anthropic API 직접 인증용 API 키. 설정 시 OAuth 대신 이 키를 사용합니다. `export ANTHROPIC_API_KEY="sk-ant-..."` |
|
||||
| `ANTHROPIC_AUTH_TOKEN` | 대안 인증 토큰. `ANTHROPIC_API_KEY`가 적용되지 않는 컨텍스트에서 사용합니다. |
|
||||
| `ANTHROPIC_BASE_URL` | Anthropic API 기본 URL 재정의. 프록시, 스테이징 환경, 호환 서드파티 엔드포인트를 가리킬 때 유용합니다. |
|
||||
| `CLAUDE_CODE_API_BASE_URL` | Claude Code 전용 API 기본 URL 재정의. 설정 시 `ANTHROPIC_BASE_URL`보다 우선합니다. |
|
||||
| `ANTHROPIC_BEDROCK_BASE_URL` | AWS Bedrock API 접근용 기본 URL. Bedrock 엔드포인트를 통해 라우팅할 때 설정합니다. |
|
||||
| `ANTHROPIC_VERTEX_PROJECT_ID` | Vertex AI 접근용 Google Cloud 프로젝트 ID. Google Cloud의 Vertex AI 플랫폼을 통해 Claude Code를 사용할 때 필요합니다. |
|
||||
| `CLAUDE_CODE_USE_BEDROCK` | `1` 또는 `true`로 설정해 AWS Bedrock을 API 공급자로 사용합니다. |
|
||||
| `CLAUDE_CODE_USE_FOUNDRY` | `1` 또는 `true`로 설정해 Anthropic Foundry를 API 공급자로 사용합니다. |
|
||||
| `CLAUDE_CODE_OAUTH_TOKEN` | OAuth 액세스 토큰을 직접 사용해 대화형 로그인 흐름을 우회합니다. 자동화 환경에 유용합니다. |
|
||||
|
||||
## 설정 경로
|
||||
|
||||
| 변수 | 기본값 | 설명 |
|
||||
|------|--------|------|
|
||||
| `CLAUDE_CONFIG_DIR` | `~/.claude` | Claude Code가 설정, 설정값, 트랜스크립트를 저장하는 디렉토리 재정의. `export CLAUDE_CONFIG_DIR="/opt/claude-config"` |
|
||||
| `CLAUDE_CODE_MANAGED_SETTINGS_PATH` | - | Managed 설정 파일 경로 재정의. 기본 플랫폼 경로가 적절하지 않은 엔터프라이즈 환경에 유용합니다. |
|
||||
|
||||
## 모델 선택
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `ANTHROPIC_MODEL` | 사용할 기본 모델. 설정 파일의 `model` 설정과 명시적 `--model` 플래그에 의해 재정의됩니다. |
|
||||
| `CLAUDE_CODE_SUBAGENT_MODEL` | 메인 에이전트가 생성하는 서브에이전트 작업에 사용할 모델. 설정하지 않으면 서브에이전트는 메인 세션과 동일한 모델을 사용합니다. |
|
||||
| `CLAUDE_CODE_AUTO_MODE_MODEL` | 자동 모드에서 사용할 모델. 지정하지 않으면 메인 세션 모델을 기본으로 합니다. |
|
||||
|
||||
## 동작 토글
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `CLAUDE_CODE_REMOTE` | `1` 또는 `true`로 설정해 원격/컨테이너 모드 활성화. 비대화형 환경에 맞게 동작을 조정합니다 — API 타임아웃 연장(120s vs 300s), 대화형 프롬프트 억제, 출력 형식 조정. |
|
||||
| `CLAUDE_CODE_SIMPLE` | `1` 또는 `true`로 설정해(또는 `--bare` 전달) bare 모드로 실행. 훅, LSP 통합, 플러그인 동기화, 스킬 디렉토리 워크, 어트리뷰션, 백그라운드 프리페치, 키체인/자격증명 읽기를 모두 건너뜁니다. 경량 스크립트 사용에 유용합니다. |
|
||||
| `DISABLE_AUTO_COMPACT` | `1` 또는 `true`로 설정해 자동 컨텍스트 컴팩션 비활성화. 설정 시 모델의 컨텍스트 한계에 근접해도 대화 컨텍스트를 컴팩트하지 않습니다. |
|
||||
| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | `1` 또는 `true`로 설정해 백그라운드 작업 실행 비활성화. |
|
||||
| `CLAUDE_CODE_DISABLE_THINKING` | `1` 또는 `true`로 설정해 모든 API 호출의 확장 thinking을 비활성화합니다. |
|
||||
| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | `1` 또는 `true`로 설정해 자동 메모리 비활성화. Claude가 자동 메모리 디렉토리를 읽거나 쓰지 않습니다. |
|
||||
| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | `1` 또는 `true`로 설정해 모든 `CLAUDE.md` 메모리 파일 로딩을 완전 비활성화합니다. |
|
||||
| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | `1` 또는 `true`로 설정해 분석, 원격 측정, 기타 비필수 네트워크 요청을 억제합니다. |
|
||||
| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | `1` 또는 `true`로 설정해 각 Bash 커맨드 후 원래 프로젝트 루트로 작업 디렉토리를 재설정합니다. |
|
||||
|
||||
## 리소스 제한
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | API 응답당 최대 출력 토큰 수 재정의. `export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096` |
|
||||
| `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | 최대 컨텍스트 윈도우 크기 재정의. |
|
||||
| `BASH_MAX_OUTPUT_LENGTH` | Bash 커맨드 출력에서 캡처되는 최대 문자 수. `export BASH_MAX_OUTPUT_LENGTH=50000` |
|
||||
| `API_TIMEOUT_MS` | API 요청 타임아웃을 밀리초 단위로 재정의. 기본 300,000ms(5분), 원격 모드에서는 120,000ms(2분). `export API_TIMEOUT_MS=60000` |
|
||||
|
||||
## 원격 측정 및 관찰 가능성
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `CLAUDE_CODE_ENABLE_TELEMETRY` | `1` 또는 `true`로 설정해 트레이스, 메트릭, 로그의 OpenTelemetry 내보내기 활성화. 추가 OTEL 설정이 필요합니다. `export CLAUDE_CODE_ENABLE_TELEMETRY=1` |
|
||||
| `CLAUDE_CODE_JSONL_TRANSCRIPT` | Claude Code가 세션 JSONL 트랜스크립트를 쓸 파일 경로. `export CLAUDE_CODE_JSONL_TRANSCRIPT="/tmp/session.jsonl"` |
|
||||
|
||||
## Node.js 런타임
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `NODE_OPTIONS` | 런타임에 전달되는 표준 Node.js 옵션. Claude Code는 `--max-old-space-size` 같은 플래그를 감지하기 위해 이것을 읽습니다. ⚠️ 코드 실행 플래그를 포함하는 값으로 설정하지 마세요. |
|
||||
|
||||
## 호스트 플랫폼 재정의
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `CLAUDE_CODE_HOST_PLATFORM` | 분석용 보고 호스트 플랫폼 재정의. `"win32"`, `"darwin"`, `"linux"` 허용. `export CLAUDE_CODE_HOST_PLATFORM=darwin` |
|
||||
|
||||
## 클라우드 제공업체 리전 재정의
|
||||
|
||||
Vertex AI에서 모델별 리전 재정의를 지원합니다:
|
||||
|
||||
| 모델 프리픽스 | 환경 변수 |
|
||||
|--------------|----------|
|
||||
| `claude-haiku-4-5` | `VERTEX_REGION_CLAUDE_HAIKU_4_5` |
|
||||
| `claude-3-5-sonnet` | `VERTEX_REGION_CLAUDE_3_5_SONNET` |
|
||||
| `claude-sonnet-4-6` | `VERTEX_REGION_CLAUDE_4_6_SONNET` |
|
||||
| `claude-opus-4` | `VERTEX_REGION_CLAUDE_4_0_OPUS` |
|
||||
|
||||
기본 Vertex 리전은 `CLOUD_ML_REGION`으로 제어됩니다(기본값: `us-east5`).
|
||||
|
||||
## AWS 자격 증명
|
||||
|
||||
Bedrock 접근을 위해 표준 AWS 자격 증명 환경 변수를 지원합니다:
|
||||
|
||||
| 변수 | 설명 |
|
||||
|------|------|
|
||||
| `AWS_REGION` | Bedrock API 호출용 AWS 리전. `AWS_DEFAULT_REGION`으로 폴백, 없으면 `us-east-1` |
|
||||
| `AWS_DEFAULT_REGION` | `AWS_REGION`이 설정되지 않은 경우 폴백 AWS 리전 |
|
||||
|
||||
## 모든 세션에 환경 변수 설정
|
||||
|
||||
셸 프로파일 대신 설정 파일의 `env` 필드를 사용해 모든 Claude Code 세션에 적용되는 환경 변수를 설정할 수 있습니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"DISABLE_AUTO_COMPACT": "1",
|
||||
"BASH_MAX_OUTPUT_LENGTH": "30000"
|
||||
}
|
||||
}
|
||||
```
|
||||
172
docs/claude-code-docs-main/10_설정파일.md
Normal file
172
docs/claude-code-docs-main/10_설정파일.md
Normal file
@@ -0,0 +1,172 @@
|
||||
# 설정 파일 (settings.json)
|
||||
|
||||
> 사용자, 프로젝트, Managed 레벨의 JSON 설정 파일로 Claude Code 동작 설정.
|
||||
|
||||
Claude Code는 여러 범위의 JSON 파일에서 설정을 읽습니다. 낮은 우선순위에서 높은 우선순위 순으로 병합됩니다.
|
||||
|
||||
## 설정 파일 위치
|
||||
|
||||
**전역(사용자):** `~/.claude/settings.json`
|
||||
모든 프로젝트에 걸쳐 실행하는 모든 Claude Code 세션에 적용됩니다. 선호 모델, 테마, 정리 정책 같은 개인 설정을 여기에 설정합니다.
|
||||
|
||||
**프로젝트(공유):** `.claude/settings.json` (프로젝트 루트)
|
||||
소스 컨트롤에 체크인됩니다. 프로젝트 작업자 모두에게 적용되어야 하는 설정 — 권한 규칙, 훅 설정, MCP 서버, 환경 변수.
|
||||
|
||||
**로컬(개인 프로젝트):** `.claude/settings.local.json` (프로젝트 루트)
|
||||
소스 컨트롤에 체크인되지 않습니다(자동으로 `.gitignore`에 추가됨). 특정 프로젝트 내의 개인 재정의.
|
||||
|
||||
**Managed(엔터프라이즈):** 플랫폼별 시스템 경로
|
||||
MDM, 레지스트리(Windows), plist(macOS), 또는 Managed 설정 파일을 통해 관리자가 설정합니다. Managed 설정은 최고 우선순위를 가지며 사용자나 프로젝트가 재정의할 수 없습니다.
|
||||
|
||||
## 설정 우선순위
|
||||
|
||||
```
|
||||
플러그인 기본값 → 사용자 설정 → 프로젝트 설정 → 로컬 설정 → Managed(정책) 설정
|
||||
```
|
||||
|
||||
Managed(정책) 설정은 항상 최종 우선순위를 가집니다.
|
||||
|
||||
## 설정 열기
|
||||
|
||||
세션 내에서 `/config`를 실행해 설정 UI를 엽니다. 각 범위의 현재 활성 설정을 찾아볼 수 있습니다. JSON 파일을 직접 편집할 수도 있습니다 — Claude Code가 파일 변경을 감지하면 자동으로 설정을 다시 로드합니다.
|
||||
|
||||
## 설정 레퍼런스
|
||||
|
||||
### `model`
|
||||
**타입:** `string` | **범위:** 모든 범위
|
||||
|
||||
Claude Code가 사용하는 기본 모델 재정의. 설정된 공급자가 지원하는 모든 모델 ID 허용.
|
||||
|
||||
```json
|
||||
{ "model": "claude-opus-4-5" }
|
||||
```
|
||||
|
||||
### `permissions`
|
||||
**타입:** `object` | **범위:** 모든 범위
|
||||
|
||||
Claude가 사용할 수 있는 도구와 모드를 제어합니다. 규칙 구문은 [권한 시스템](./06_권한시스템.md) 참조.
|
||||
|
||||
| 필드 | 타입 | 설명 |
|
||||
|------|------|------|
|
||||
| `allow` | `string[]` | Claude가 확인 없이 수행할 수 있는 작업 규칙 |
|
||||
| `deny` | `string[]` | Claude가 항상 차단되는 작업 규칙 |
|
||||
| `ask` | `string[]` | 항상 확인을 요청하는 작업 규칙 |
|
||||
| `defaultMode` | `string` | 기본 권한 모드: `"default"`, `"acceptEdits"`, `"plan"`, `"bypassPermissions"` |
|
||||
| `disableBypassPermissionsMode` | `"disable"` | 사용자가 bypass permissions 모드에 들어가는 것을 방지 |
|
||||
| `additionalDirectories` | `string[]` | Claude가 접근할 수 있는 추가 디렉토리 |
|
||||
|
||||
### `hooks`
|
||||
**타입:** `object` | **범위:** 모든 범위
|
||||
|
||||
도구 실행 전후에 커스텀 셸 커맨드를 실행합니다. 지원 훅 이벤트: `PreToolUse`, `PostToolUse`, `Notification`, `UserPromptSubmit`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStop`, `PreCompact`, `PostCompact`.
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [{ "type": "command", "command": "prettier --write $CLAUDE_FILE_PATHS" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `cleanupPeriodDays`
|
||||
**타입:** `integer` | **기본값:** `30` | **범위:** 모든 범위
|
||||
|
||||
채팅 트랜스크립트 보관 일수. `0`으로 설정하면 세션 영속성이 완전히 비활성화됩니다.
|
||||
|
||||
### `env`
|
||||
**타입:** `object` | **범위:** 모든 범위
|
||||
|
||||
모든 Claude Code 세션에 주입할 환경 변수. 값은 문자열로 변환됩니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"NODE_ENV": "development",
|
||||
"MY_API_URL": "https://api.example.com"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `availableModels`
|
||||
**타입:** `string[]` | **범위:** Managed만
|
||||
|
||||
사용자가 선택 가능한 모델의 엔터프라이즈 허용 목록. 패밀리 별칭(`"opus"`는 모든 Opus 버전 허용), 버전 프리픽스, 또는 전체 모델 ID 허용.
|
||||
|
||||
### `worktree`
|
||||
**타입:** `object` | **범위:** 모든 범위
|
||||
|
||||
`--worktree` 플래그 동작 설정.
|
||||
|
||||
| 필드 | 타입 | 설명 |
|
||||
|------|------|------|
|
||||
| `symlinkDirectories` | `string[]` | worktree에 메인 저장소에서 심링크할 디렉토리 (예: `"node_modules"`) |
|
||||
| `sparsePaths` | `string[]` | 대규모 모노레포에서 빠른 worktree를 위한 sparse 체크아웃 경로 |
|
||||
|
||||
### `attribution`
|
||||
**타입:** `object` | **범위:** 모든 범위
|
||||
|
||||
Claude가 커밋과 PR 설명에 추가하는 어트리뷰션 텍스트를 커스터마이징합니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "Co-Authored-By: Claude <noreply@anthropic.com>",
|
||||
"pr": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `language`
|
||||
Claude 응답과 음성 받아쓰기에 선호되는 언어. `{ "language": "korean" }`
|
||||
|
||||
### `alwaysThinkingEnabled`
|
||||
**기본값:** `true` — `false`로 설정해 확장 thinking 비활성화.
|
||||
|
||||
### `effortLevel`
|
||||
`"low"` | `"medium"` | `"high"` — thinking 예산을 지원하는 모델의 effort 레벨.
|
||||
|
||||
### `autoMemoryEnabled`
|
||||
**범위:** 사용자, 로컬 — 이 프로젝트의 자동 메모리 활성화 또는 비활성화.
|
||||
|
||||
### `respectGitignore`
|
||||
**기본값:** `true` — 파일 피커가 `.gitignore` 파일을 존중할지 여부.
|
||||
|
||||
### `defaultShell`
|
||||
`"bash"` | `"powershell"` — 입력 박스의 `!` 커맨드용 기본 셸.
|
||||
|
||||
### `apiKeyHelper`
|
||||
**범위:** 사용자, Managed — API 키를 동적으로 검색하는 스크립트 경로. 스크립트는 stdout에 API 키만 출력하고 코드 0으로 종료해야 합니다.
|
||||
|
||||
## Managed 설정 (엔터프라이즈)
|
||||
|
||||
관리자는 플랫폼 네이티브 메커니즘을 통해 모든 사용자에게 설정을 배포할 수 있습니다.
|
||||
|
||||
**macOS:** `/Library/Preferences/`에 plist 파일 배포 또는 MDM을 통해 `com.anthropic.claudecode` 타겟
|
||||
|
||||
**Windows:** `HKLM\Software\Anthropic\Claude Code` 레지스트리 키에 설정 작성
|
||||
|
||||
**파일 기반:** Managed 설정 파일을 플랫폼별 managed 경로에 배치. 드롭인 설정 조각에는 `managed-settings.d/` 디렉토리 사용(알파벳 순으로 정렬 및 병합됨).
|
||||
|
||||
### Managed 전용 잠금 설정
|
||||
|
||||
| 설정 | 설명 |
|
||||
|------|------|
|
||||
| `allowManagedHooksOnly` | `true`로 설정 시 Managed 설정의 훅만 실행 |
|
||||
| `allowManagedPermissionRulesOnly` | `true`로 설정 시 Managed 설정의 권한 규칙만 존중 |
|
||||
| `allowManagedMcpServersOnly` | `true`로 설정 시 허용 MCP 서버 목록을 Managed 설정에서만 읽음 |
|
||||
| `strictPluginOnlyCustomization` | 특정 커스터마이징 표면을 플러그인 전용 소스로 잠금 |
|
||||
|
||||
## JSON 스키마
|
||||
|
||||
에디터 자동완성 및 유효성 검사를 위해 설정 파일에 `$schema` 추가:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://schemas.anthropic.com/claude-code/settings.json"
|
||||
}
|
||||
```
|
||||
130
docs/claude-code-docs-main/11_인증.md
Normal file
130
docs/claude-code-docs-main/11_인증.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# 인증
|
||||
|
||||
> Anthropic API, AWS Bedrock, GCP Vertex AI로 Claude Code 인증 설정 방법.
|
||||
|
||||
Claude Code는 여러 인증 방식을 지원합니다. 방식은 API에 직접 접근하는지, 클라우드 제공업체를 통하는지, API 키 헬퍼 스크립트를 통하는지에 따라 다릅니다.
|
||||
|
||||
## Claude.ai OAuth (기본)
|
||||
|
||||
API 키가 설정되지 않은 상태에서 `claude`를 처음 실행하면, Claude Code가 claude.ai 계정으로 OAuth 흐름을 시작합니다.
|
||||
|
||||
1. 터미널에서 실행: `claude`
|
||||
2. URL이 표시되면 브라우저에서 열어 claude.ai 계정으로 로그인하고 권한 부여
|
||||
3. 브라우저에서 인증 후 Claude Code가 자동으로 OAuth 토큰을 받아 저장합니다(macOS는 Keychain, 다른 플랫폼은 자격 증명 파일)
|
||||
|
||||
OAuth 토큰은 만료 전에 자동으로 갱신됩니다. 명시적으로 로그아웃하거나 접근을 취소하지 않는 한 재인증이 필요하지 않습니다.
|
||||
|
||||
## API 키
|
||||
|
||||
OAuth 대신 Anthropic API 키로 인증할 수 있습니다.
|
||||
|
||||
**환경 변수:**
|
||||
```bash
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
이 변수가 설정되면 Claude Code가 직접 사용하고 OAuth를 요청하지 않습니다.
|
||||
|
||||
**설정 파일 apiKeyHelper:**
|
||||
```json
|
||||
{
|
||||
"apiKeyHelper": "cat ~/.anthropic/api-key"
|
||||
}
|
||||
```
|
||||
Claude Code가 이 커맨드를 실행해 자격 증명을 동적으로 가져옵니다. 결과는 5분 동안 캐시됩니다(`CLAUDE_CODE_API_KEY_HELPER_TTL_MS`로 설정 가능). 커맨드는 API 키만 stdout에 출력하고 코드 0으로 종료해야 합니다.
|
||||
|
||||
> ⚠️ `ANTHROPIC_API_KEY`가 설정되거나 `apiKeyHelper`가 구성되면 OAuth 흐름이 비활성화됩니다.
|
||||
|
||||
## AWS Bedrock
|
||||
|
||||
AWS Bedrock을 통해 Claude를 사용하려면:
|
||||
|
||||
```bash
|
||||
# 1. Bedrock 모드 활성화
|
||||
export CLAUDE_CODE_USE_BEDROCK=1
|
||||
|
||||
# 2. AWS 자격 증명 설정 (표준 AWS 자격 증명 체인)
|
||||
# - AWS 자격 증명 파일 (~/.aws/credentials)
|
||||
# - 환경 변수: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
|
||||
# - IAM 역할(EC2 인스턴스 프로파일, ECS 태스크 역할 등)
|
||||
# - AWS SSO (aws sso login)
|
||||
|
||||
# 3. 리전 설정 (선택사항)
|
||||
export AWS_REGION=us-east-1
|
||||
```
|
||||
|
||||
**자동 AWS 자격 증명 갱신:**
|
||||
세션이 만료될 경우(예: 단기 SSO 토큰) `awsAuthRefresh`를 설정해 자동으로 자격 증명을 갱신합니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"awsAuthRefresh": "aws sso login --profile my-profile"
|
||||
}
|
||||
```
|
||||
|
||||
커맨드에서 자격 증명을 내보내려면 `awsCredentialExport`를 사용합니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"awsCredentialExport": "aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyRole --role-session-name claude-code --query Credentials --output json"
|
||||
}
|
||||
```
|
||||
|
||||
## GCP Vertex AI
|
||||
|
||||
Google Cloud Vertex AI를 통해 Claude를 사용하려면:
|
||||
|
||||
```bash
|
||||
# 1. Vertex 모드 활성화
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
|
||||
# 2. GCP 자격 증명 설정
|
||||
# - gcloud auth application-default login (대화형)
|
||||
# - GOOGLE_APPLICATION_CREDENTIALS를 통한 서비스 계정 키 파일
|
||||
# - 워크로드 아이덴티티(GKE용)
|
||||
|
||||
# 3. 프로젝트 및 리전 설정 (선택사항)
|
||||
export ANTHROPIC_VERTEX_PROJECT_ID=my-gcp-project
|
||||
export CLOUD_ML_REGION=us-central1
|
||||
```
|
||||
|
||||
**자동 GCP 자격 증명 갱신:**
|
||||
```json
|
||||
{
|
||||
"gcpAuthRefresh": "gcloud auth application-default login"
|
||||
}
|
||||
```
|
||||
|
||||
## 계정 전환
|
||||
|
||||
**다른 계정으로 로그인:**
|
||||
```
|
||||
/login
|
||||
```
|
||||
새 OAuth 흐름을 시작합니다. 저장된 토큰이 새 계정의 토큰으로 교체됩니다.
|
||||
|
||||
**로그아웃:**
|
||||
```
|
||||
/logout
|
||||
```
|
||||
저장된 자격 증명을 제거합니다. 다음 실행 시 인증을 요청합니다.
|
||||
|
||||
## 토큰 만료 및 갱신
|
||||
|
||||
Claude Code가 조용히 토큰 갱신을 처리합니다:
|
||||
- 각 API 요청 전에 액세스 토큰 만료 여부 확인
|
||||
- 만료된 경우 저장된 갱신 토큰으로 잠금을 획득하고 갱신
|
||||
- 여러 동시 Claude Code 인스턴스는 잠금 파일을 통해 중복 갱신 방지
|
||||
- API에서 `401` 응답이 오면 즉시 강제 갱신
|
||||
|
||||
## 인증 우선순위
|
||||
|
||||
여러 인증 소스가 설정된 경우 이 순서로 해석됩니다:
|
||||
|
||||
1. `ANTHROPIC_AUTH_TOKEN` 환경 변수
|
||||
2. `CLAUDE_CODE_OAUTH_TOKEN` 환경 변수
|
||||
3. 파일 디스크립터의 OAuth 토큰(관리형 배포용)
|
||||
4. 설정의 `apiKeyHelper`
|
||||
5. 저장된 claude.ai OAuth 토큰(Keychain 또는 자격 증명 파일)
|
||||
6. `ANTHROPIC_API_KEY` 환경 변수
|
||||
|
||||
> 💡 CI 및 비대화형 환경에서는 `ANTHROPIC_API_KEY` 또는 `CLAUDE_CODE_OAUTH_TOKEN`을 사용하세요. 이것들은 대화형 흐름보다 먼저 확인됩니다.
|
||||
224
docs/claude-code-docs-main/12_훅.md
Normal file
224
docs/claude-code-docs-main/12_훅.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# 훅 (Hooks)
|
||||
|
||||
> Claude가 도구를 사용하거나 세션 마일스톤에 도달할 때 셸 커맨드, HTTP 요청, 프롬프트를 자동으로 실행합니다.
|
||||
|
||||
훅은 Claude Code의 도구 라이프사이클에 자동화를 연결합니다. Claude가 파일을 읽거나, bash 커맨드를 실행하거나, 응답을 완료할 때 설정된 훅이 자동으로 실행됩니다. 코드 스타일 강제, 테스트 실행, 도구 사용 로깅, Claude가 할 수 있는 작업 제어에 훅을 사용하세요.
|
||||
|
||||
## 훅 작동 방식
|
||||
|
||||
훅은 특정 **이벤트**에 바인딩된 커맨드(셸 스크립트, HTTP 엔드포인트, LLM 프롬프트)입니다. 이벤트가 발생하면 Claude Code가 매칭된 모든 훅을 실행하고 종료 코드와 출력을 사용해 다음 동작을 결정합니다.
|
||||
|
||||
각 훅의 입력은 무슨 일이 일어났는지 설명하는 JSON 객체입니다.
|
||||
|
||||
**종료 코드 의미:**
|
||||
| 종료 코드 | 의미 |
|
||||
|----------|------|
|
||||
| `0` | 성공. stdout이 Claude에게 표시될 수 있음(이벤트별 다름) |
|
||||
| `2` | 차단 또는 주입. stderr를 Claude에게 표시하고(`PreToolUse`) 도구 호출 방지 |
|
||||
| 기타 | stderr를 사용자에게만 표시; 실행 계속 |
|
||||
|
||||
## 훅 이벤트
|
||||
|
||||
| 이벤트 | 설명 |
|
||||
|--------|------|
|
||||
| **PreToolUse** | 모든 도구 호출 직전에 발생. 도구 입력 검사, 승인/차단, 입력 수정 가능. 종료코드 `2` → 도구 호출 차단 |
|
||||
| **PostToolUse** | 모든 성공적인 도구 호출 후 발생. 도구 출력 관찰 또는 Claude가 처리할 컨텍스트 주입 가능 |
|
||||
| **PostToolUseFailure** | 도구 호출이 오류로 종료될 때 발생 |
|
||||
| **Stop** | Claude가 응답을 종료하기 직전에 발생. 종료코드 `2` → stderr를 Claude에게 표시하고 대화 계속 |
|
||||
| **SubagentStop** | 서브에이전트가 결론 내리기 직전에 발생 (`Stop`과 동일하지만 서브에이전트용) |
|
||||
| **SubagentStart** | 새 서브에이전트가 시작될 때 발생 |
|
||||
| **SessionStart** | 세션 시작, 재개, `/clear`, `/compact` 후에 발생 |
|
||||
| **UserPromptSubmit** | 사용자가 프롬프트를 제출할 때 발생. 종료코드 `2` → 프롬프트 차단 |
|
||||
| **PreCompact** | 컨텍스트 컴팩션 시작 직전에 발생. 종료코드 `2` → 컴팩션 차단 |
|
||||
| **PostCompact** | 컴팩션 완료 후 발생 |
|
||||
| **Setup** | 저장소 초기화(`init`) 및 주기적 유지보수(`maintenance`) 시 발생 |
|
||||
| **PermissionRequest** | 권한 다이얼로그가 표시될 때 발생. 프로그래밍 방식으로 승인/거부 가능 |
|
||||
| **PermissionDenied** | 도구 호출이 거부된 후 발생 |
|
||||
| **Notification** | 권한 프롬프트, 유휴 프롬프트, 인증 성공 등의 알림 시 발생 |
|
||||
| **CwdChanged** | 작업 디렉토리 변경 후 발생 |
|
||||
| **FileChanged** | 감시 중인 파일이 변경될 때 발생 |
|
||||
| **SessionEnd** | 세션이 종료될 때 발생 |
|
||||
| **ConfigChange** | 세션 중 설정 파일이 변경될 때 발생 |
|
||||
|
||||
## 훅 설정
|
||||
|
||||
세션 내에서 `/hooks`를 실행해 훅 설정 메뉴를 열 수 있습니다. 훅은 설정 파일의 `hooks` 필드에 저장됩니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "prettier --write $CLAUDE_FILE_PATH"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo 'Session complete' >> ~/.claude-log.txt"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
각 이벤트는 **매처 객체** 배열에 매핑됩니다:
|
||||
- `matcher` (선택사항) — 이벤트의 매칭 가능한 필드와 매칭되는 문자열 패턴
|
||||
- `hooks` — 매처가 일치할 때 실행할 훅 커맨드 배열
|
||||
|
||||
빈 또는 없는 `matcher`는 해당 이벤트의 모든 입력과 일치합니다.
|
||||
|
||||
## 훅 커맨드 타입
|
||||
|
||||
**셸 커맨드 (`type: "command"`):**
|
||||
```json
|
||||
{
|
||||
"type": "command",
|
||||
"command": "npm test",
|
||||
"timeout": 60,
|
||||
"shell": "bash",
|
||||
"async": false
|
||||
}
|
||||
```
|
||||
|
||||
필드:
|
||||
- `command` — 실행할 셸 커맨드 (필수)
|
||||
- `timeout` — 타임아웃(초)
|
||||
- `shell` — `"bash"` (기본) 또는 `"powershell"`
|
||||
- `async` — 백그라운드에서 실행 (출력 무시)
|
||||
- `once` — 한 번 실행 후 자동으로 훅 제거
|
||||
- `if` — 조건부로 훅 건너뛰기 위한 권한 규칙 구문
|
||||
- `statusMessage` — 훅 실행 중 스피너에 표시되는 커스텀 메시지
|
||||
|
||||
**HTTP 요청 (`type: "http"`):**
|
||||
```json
|
||||
{
|
||||
"type": "http",
|
||||
"url": "https://hooks.example.com/claude-event",
|
||||
"headers": {
|
||||
"Authorization": "Bearer $MY_TOKEN"
|
||||
},
|
||||
"allowedEnvVars": ["MY_TOKEN"],
|
||||
"timeout": 10
|
||||
}
|
||||
```
|
||||
|
||||
Claude Code가 훅 입력 JSON을 URL에 POST합니다.
|
||||
|
||||
**LLM 프롬프트 (`type: "prompt"`):**
|
||||
```json
|
||||
{
|
||||
"type": "prompt",
|
||||
"prompt": "이 bash 커맨드에 보안 문제가 있는지 확인하세요: $ARGUMENTS. 문제가 있으면 설명하고 코드 2로 종료하세요.",
|
||||
"model": "claude-haiku-4-5",
|
||||
"timeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
**에이전트 훅 (`type: "agent"`):**
|
||||
```json
|
||||
{
|
||||
"type": "agent",
|
||||
"prompt": "단위 테스트가 실행되고 통과했는지 확인하세요.",
|
||||
"timeout": 60
|
||||
}
|
||||
```
|
||||
|
||||
도구 접근 권한이 있는 짧은 에이전틱 루프로 실행됩니다. 파일을 읽거나 커맨드를 실행해야 하는 검증 작업에 유용합니다.
|
||||
|
||||
## 훅 예시
|
||||
|
||||
**파일 편집 후 자동 포맷:**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**위험한 커맨드 차단:**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -q 'rm -rf'; then echo '차단: rm -rf는 허용되지 않습니다' >&2; exit 2; fi"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**모든 도구 사용 로깅:**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) $CLAUDE_TOOL_NAME\" >> ~/.claude-tool-log.txt",
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**디렉토리 변경 시 환경 변수 주입:**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"CwdChanged": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "if [ -f .envrc ]; then grep '^export ' .envrc >> \"$CLAUDE_ENV_FILE\"; fi"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 훅 vs 스킬
|
||||
|
||||
| 기능 | 훅 | 스킬 |
|
||||
|------|-----|------|
|
||||
| 실행 시점 | 도구 이벤트에 자동 | Claude나 사용자가 `/skill-name`으로 명시적 호출 |
|
||||
| 목적 | 부작용, 게이팅, 관찰 | 온디맨드 워크플로우와 기능 |
|
||||
| 설정 | 설정 JSON | `.claude/skills/`의 마크다운 파일 |
|
||||
|
||||
자동으로 발생해야 하는 것(포맷팅, 로깅, 강제)에는 훅을 사용하고, 의도적으로 트리거하려는 반복 가능한 워크플로우에는 스킬을 사용하세요.
|
||||
174
docs/claude-code-docs-main/13_MCP서버.md
Normal file
174
docs/claude-code-docs-main/13_MCP서버.md
Normal file
@@ -0,0 +1,174 @@
|
||||
# MCP 서버
|
||||
|
||||
> Model Context Protocol 서버를 연결해 Claude Code의 기능을 데이터베이스, API, 커스텀 도구로 확장합니다.
|
||||
|
||||
MCP(Model Context Protocol)는 Claude Code가 외부 데이터 소스와 서비스에 연결할 수 있게 하는 오픈 표준입니다. MCP 서버를 추가하면 Claude가 새 도구에 접근할 수 있습니다 — 예를 들어 데이터베이스 쿼리, Jira 티켓 읽기, Slack 워크스페이스 상호작용 등.
|
||||
|
||||
## 서버 추가 방법
|
||||
|
||||
**CLI를 통해:**
|
||||
```bash
|
||||
# 기본 추가
|
||||
claude mcp add <이름> -- <커맨드> [인수...]
|
||||
|
||||
# 예: filesystem MCP 서버 추가
|
||||
claude mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem /tmp
|
||||
|
||||
# 범위 지정
|
||||
claude mcp add --scope project filesystem -- npx -y @modelcontextprotocol/server-filesystem /tmp
|
||||
claude mcp add --scope user my-db -- npx -y @my-org/mcp-server-postgres
|
||||
```
|
||||
|
||||
**`--mcp-config` 플래그:**
|
||||
```bash
|
||||
claude --mcp-config ./my-mcp-config.json
|
||||
```
|
||||
CI 환경이나 설정 파일에 저장하지 않을 독립형 설정에 유용합니다.
|
||||
|
||||
## 설정 파일 형식
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"],
|
||||
"env": {
|
||||
"NODE_ENV": "production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**HTTP 원격 서버:**
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-api": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.example.com/v1",
|
||||
"headers": {
|
||||
"Authorization": "Bearer $MY_API_TOKEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**SSE (Server-Sent Events):**
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"events-server": {
|
||||
"type": "sse",
|
||||
"url": "https://mcp.example.com/sse"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`command`, `args`, `url`, `headers` 값은 `$VAR` 및 `${VAR}` 구문을 지원합니다. 참조 변수가 없으면 Claude Code가 경고를 로그하지만 연결을 시도합니다.
|
||||
|
||||
## 설정 범위
|
||||
|
||||
| 범위 | 위치 | 용도 |
|
||||
|------|------|------|
|
||||
| `project` | 현재 디렉토리의 `.mcp.json` | 팀 공유 서버 설정 |
|
||||
| `user` | `~/.claude.json` (전역 설정) | 모든 곳에서 이용 가능한 개인 서버 |
|
||||
| `local` | 현재 프로젝트의 `.claude/settings.local.json` | 개인 프로젝트별 재정의, VCS에 커밋되지 않음 |
|
||||
|
||||
같은 서버 이름이 여러 범위에 나타나면 `local` > `project` > `user` 순으로 우선합니다.
|
||||
|
||||
## 서버 관리
|
||||
|
||||
**활성화/비활성화:**
|
||||
```
|
||||
/mcp enable <server-name>
|
||||
/mcp disable <server-name>
|
||||
/mcp enable all
|
||||
/mcp disable all
|
||||
```
|
||||
|
||||
비활성화된 서버는 설정에 남아있지만 시작 시 연결되지 않습니다.
|
||||
|
||||
**서버 재연결:**
|
||||
```
|
||||
/mcp reconnect <server-name>
|
||||
```
|
||||
|
||||
**서버 상태 확인:**
|
||||
`/mcp`를 실행해 모든 설정된 서버와 현재 연결 상태를 확인합니다:
|
||||
- **connected** — 서버가 실행 중이고 준비됨
|
||||
- **pending** — 서버가 시작 중
|
||||
- **failed** — 서버 연결 실패(오류 메시지 확인)
|
||||
- **needs-auth** — OAuth 인증 필요
|
||||
- **disabled** — 설정되었지만 꺼짐
|
||||
|
||||
## MCP 도구 호출 승인
|
||||
|
||||
Claude Code는 MCP 도구를 호출하기 전에 권한 프롬프트를 표시합니다. 도구 이름과 입력 인수를 보여줍니다:
|
||||
- **한 번 허용** — 이 특정 호출 승인
|
||||
- **항상 허용** — 이 세션에서 이 도구의 모든 호출 승인
|
||||
- **거부** — 호출 차단; Claude가 오류를 받고 다른 접근을 시도
|
||||
|
||||
> 📝 자동 모드(`--allowedTools`)에서 MCP 도구는 허용 도구 목록에 전체 이름(`mcp__<server-name>__<tool-name>` 형식)을 포함시켜 사전 승인할 수 있습니다.
|
||||
|
||||
## 예시: filesystem 서버
|
||||
|
||||
```bash
|
||||
# 1. 서버 추가
|
||||
claude mcp add --scope project filesystem -- npx -y @modelcontextprotocol/server-filesystem /home/user/projects
|
||||
|
||||
# 2. 연결 확인
|
||||
# /mcp 실행 → filesystem이 connected로 표시되는지 확인
|
||||
|
||||
# 3. 사용
|
||||
# Claude가 이제 mcp__filesystem__read_file과 mcp__filesystem__write_file 도구로
|
||||
# /home/user/projects의 파일을 읽고 쓸 수 있음
|
||||
```
|
||||
|
||||
## 예시: 데이터베이스 서버
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"postgres": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-postgres"],
|
||||
"env": {
|
||||
"POSTGRES_CONNECTION_STRING": "$DATABASE_URL"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Claude Code 시작 전에 환경에서 `DATABASE_URL`을 설정하면 MCP 서버가 자동으로 받습니다.
|
||||
|
||||
## 공식 MCP 레지스트리
|
||||
|
||||
[modelcontextprotocol.io](https://modelcontextprotocol.io)에서 Anthropic과 커뮤니티가 관리하는 MCP 서버 레지스트리를 찾아볼 수 있습니다 — 데이터베이스, 생산성 도구, 클라우드 제공업체 등.
|
||||
|
||||
## 문제 해결
|
||||
|
||||
**서버가 'failed'로 표시됨:**
|
||||
- 커맨드가 존재하고 실행 가능한지 확인: `which npx`
|
||||
- 터미널에서 커맨드를 직접 실행해 오류 없이 시작되는지 확인
|
||||
- 필요한 환경 변수(API 키 등)가 설정되었는지 확인
|
||||
- `claude --debug`로 상세 연결 로그 확인
|
||||
|
||||
**MCP 도구가 나타나지 않음:**
|
||||
연결되었지만 미인증 상태인 서버는 도구를 노출하지 않습니다. `/mcp`에서 **needs-auth** 상태를 확인하고 OAuth 흐름을 따르세요.
|
||||
|
||||
**Windows: npx 실패:**
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-server": {
|
||||
"command": "cmd",
|
||||
"args": ["/c", "npx", "-y", "@my-org/mcp-server"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
115
docs/claude-code-docs-main/14_멀티에이전트.md
Normal file
115
docs/claude-code-docs-main/14_멀티에이전트.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# 멀티에이전트 워크플로우
|
||||
|
||||
> Claude가 서브에이전트를 스폰하고 조율해 복잡한 작업을 병렬화하는 방법.
|
||||
|
||||
Claude Code는 서브에이전트 — 독립적으로 실행되어 병렬로 작업을 완료하는 별도의 Claude 인스턴스 — 를 스폰할 수 있습니다. 단일 대화에서 순차적으로 모든 것을 하는 대신, 동시에 실행하는 특화 에이전트로 분할해서 크고 다단계 작업을 처리할 수 있습니다.
|
||||
|
||||
## 서브에이전트 작동 방식
|
||||
|
||||
Claude가 `Agent` 도구를 사용하면, 자체 컨텍스트, 시스템 프롬프트, 도구 권한을 가진 새 Claude 인스턴스를 시작합니다. 부모 Claude는 에이전트가 완료될 때까지 기다리거나(또는 에이전트가 백그라운드에서 실행 중이면 다른 작업을 계속합니다), 그 후 에이전트의 결과를 단일 메시지로 받습니다.
|
||||
|
||||
각 에이전트는:
|
||||
- 새 컨텍스트 윈도우로 시작 (fork가 아닌 한)
|
||||
- 에이전트 타입에 따라 특화된 시스템 프롬프트 적용
|
||||
- 자체 도구 권한 (에이전트 타입별로 설정 가능)
|
||||
- 추가 서브에이전트를 스폰 가능 (단, 중첩은 제한됨)
|
||||
|
||||
## Agent 도구
|
||||
|
||||
Claude가 `Agent` 도구를 사용해 서브에이전트를 스폰합니다. 이 도구를 직접 호출하는 것이 아니라 Claude가 필요할 때 결정합니다. 터미널에서 에이전트 스폰을 볼 수 있습니다 — 자체 진행 표시기와 함께 나타납니다.
|
||||
|
||||
도구 파라미터:
|
||||
- `description` — 에이전트가 할 일의 3-5단어 요약 (UI에 표시)
|
||||
- `prompt` — 에이전트에 대한 전체 작업 설명
|
||||
- `subagent_type` — 사용할 특화 에이전트 타입 (선택사항; 기본값은 범용)
|
||||
- `run_in_background` — 비동기 실행 여부
|
||||
- `isolation` — `"worktree"`로 격리된 git worktree 제공
|
||||
|
||||
## Claude가 서브에이전트를 사용하는 경우
|
||||
|
||||
작업이 병렬 처리나 특화에 도움이 될 때 에이전트를 스폰합니다:
|
||||
- **독립적 병렬 작업** — 문서 업데이트와 동시에 테스트 작성
|
||||
- **특화 작업** — 보안 감사를 위한 코드 리뷰어 에이전트 사용
|
||||
- **장시간 실행 작업** — 다른 것을 작업하는 동안 백그라운드 리서치
|
||||
- **격리된 탐색** — 메인 컨텍스트를 오염시키지 않고 솔루션 탐색을 위해 자신을 포크
|
||||
|
||||
## 멀티에이전트 워크플로우 요청
|
||||
|
||||
Claude에게 명시적으로 여러 에이전트 사용을 요청할 수 있습니다:
|
||||
|
||||
```
|
||||
linter와 test suite를 병렬로 실행해줘.
|
||||
```
|
||||
|
||||
```
|
||||
세 경쟁 라이브러리가 이 문제를 어떻게 처리하는지 별도의 에이전트로 조사한 후 결과를 요약해줘.
|
||||
```
|
||||
|
||||
```
|
||||
보안 에이전트가 이 코드 변경의 보안 영향을 검토하는 동안 기능 구현을 계속해줘.
|
||||
```
|
||||
|
||||
> 💡 Claude에게 에이전트를 "병렬로" 실행하도록 요청하면, 여러 Agent 도구 호출을 포함하는 단일 메시지를 전송해 모두 동시에 시작합니다.
|
||||
|
||||
## 포그라운드 vs 백그라운드 에이전트
|
||||
|
||||
기본적으로 에이전트는 **포그라운드**에서 실행됩니다 — Claude가 계속하기 전에 각 에이전트가 완료될 때까지 기다립니다. Claude가 결과를 계속 작업하는 데 필요한 경우 포그라운드 에이전트를 사용하세요.
|
||||
|
||||
백그라운드 에이전트는 비동기로 실행됩니다. Claude가 시작하고 다른 작업을 계속합니다. 에이전트가 완료되면 알림을 받습니다.
|
||||
|
||||
```
|
||||
다음 기능을 구현하는 동안 통합 테스트를 백그라운드에서 실행해줘.
|
||||
```
|
||||
|
||||
> ⚠️ 실행 중인 백그라운드 에이전트의 출력 파일을 직접 확인하도록 Claude에게 요청하지 마세요. Claude는 자동으로 완료 알림을 받습니다.
|
||||
|
||||
## 코디네이터 모드
|
||||
|
||||
코디네이터 모드에서 Claude는 모든 구현 작업을 서브에이전트에 위임하고 계획, 라우팅, 종합에 집중합니다. 매우 큰 작업에 유용하며 서브에이전트가 실질적인 작업을 수행합니다.
|
||||
|
||||
## 에이전트 메모리와 컨텍스트 격리
|
||||
|
||||
각 서브에이전트는 **깨끗한 컨텍스트 윈도우**로 시작합니다. 부모 Claude가 에이전트 프롬프트에 전체 작업 설명과 관련 배경을 제공합니다 — 에이전트는 부모의 대화 기록을 자동으로 상속하지 않습니다.
|
||||
|
||||
**영속 에이전트 메모리:**
|
||||
일부 에이전트 타입은 호출 간에 영속 메모리를 가집니다:
|
||||
- **사용자 범위**: `~/.claude/agent-memory/<agent-type>/MEMORY.md`
|
||||
- **프로젝트 범위**: `.claude/agent-memory/<agent-type>/MEMORY.md`
|
||||
- **로컬 범위**: `.claude/agent-memory-local/<agent-type>/MEMORY.md`
|
||||
|
||||
## Worktree 격리
|
||||
|
||||
`isolation: "worktree"`를 설정해 에이전트에게 자체 git worktree를 제공합니다 — 저장소의 격리된 복사본. 에이전트가 만드는 변경 사항은 사용자가 병합하기 전까지 작업 디렉토리에 영향을 주지 않습니다.
|
||||
|
||||
```
|
||||
내가 변경 사항을 검토하고 병합할 수 있도록 격리된 worktree에서 이 기능을 구현해줘.
|
||||
```
|
||||
|
||||
## 효과적인 에이전트 프롬프트 작성
|
||||
|
||||
서브에이전트는 부모 대화의 컨텍스트가 없이 시작합니다. 좋은 에이전트 프롬프트에는 다음이 포함됩니다:
|
||||
- 달성하려는 것과 이유
|
||||
- 관련 파일 경로, 함수 이름, 데이터
|
||||
- 에이전트가 보고해야 할 내용(형식, 길이, 답해야 할 질문)
|
||||
- 에이전트가 하면 안 되는 것(범위 제약)
|
||||
- 이미 시도했거나 배제한 것
|
||||
|
||||
**나쁜 프롬프트:**
|
||||
```
|
||||
버그를 수정해줘.
|
||||
```
|
||||
|
||||
**좋은 프롬프트:**
|
||||
```
|
||||
src/services/user.ts:247의 UserService.getProfile()에 있는 null 참조 버그를 수정해줘.
|
||||
사용자에게 연관된 프로파일 레코드가 없을 때 버그가 발생합니다 — getProfile()이 profile이 null인지 먼저 확인하지 않고 profile.preferences를 호출합니다. null 체크를 추가하고 기본 설정 객체 { theme: 'light', notifications: true }를 반환하세요.
|
||||
그 후 npm test를 실행해 수정 사항이 기존 테스트를 통과하는지 확인하세요.
|
||||
```
|
||||
|
||||
## 제한사항
|
||||
|
||||
- 서브에이전트는 기본적으로 `acceptEdits` 모드를 사용합니다
|
||||
- 에스케이프를 누르면 부모 턴을 취소하지만 실행 중인 백그라운드 에이전트는 취소하지 않습니다 — 작업 패널에서 명시적으로 취소하세요
|
||||
- 서브에이전트는 다른 팀메이트를 스폰할 수 없습니다 (팀 로스터는 플랫)
|
||||
- 포크 에이전트는 자신을 다시 포크할 수 없습니다
|
||||
- 에이전트 결과는 부모에 반환되기 전에 100,000자로 제한됩니다
|
||||
195
docs/claude-code-docs-main/15_스킬.md
Normal file
195
docs/claude-code-docs-main/15_스킬.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# 스킬 (Skills)
|
||||
|
||||
> 슬래시 커맨드로 호출하는 재사용 가능한 온디맨드 기능을 만드는 방법.
|
||||
|
||||
스킬은 재사용 가능한 프롬프트와 워크플로우를 정의하는 마크다운 파일입니다. Claude Code에서 `/skill-name`을 입력하면 Claude가 해당 스킬의 지시사항을 로드하고 설명된 작업을 실행합니다. 세션 간에 반복하는 모든 워크플로우에 유용합니다 — 배포 실행, 변경 내역 작성, PR 검토, 팀 특유의 코딩 컨벤션 적용 등.
|
||||
|
||||
## 스킬 작동 방식
|
||||
|
||||
스킬은 `SKILL.md` 파일이 있는 `.claude/skills/` 안의 디렉토리입니다. `/skill-name`을 입력하면 Claude Code가 해당 스킬의 `SKILL.md`를 그 액션의 프롬프트로 로드합니다. 스킬은 지시사항, 컨텍스트, 제약, 호출 시 실행되는 인라인 셸 커맨드까지 포함할 수 있습니다.
|
||||
|
||||
스킬은 지연 로드됩니다 — 호출될 때만 읽히므로 스킬이 많이 정의되어 있어도 시작 시간이나 컨텍스트 크기에 영향을 주지 않습니다.
|
||||
|
||||
## 스킬 만들기
|
||||
|
||||
**1. 스킬 디렉토리 만들기:**
|
||||
```bash
|
||||
mkdir -p .claude/skills/my-skill
|
||||
```
|
||||
|
||||
스킬은 다음 위치에 있을 수 있습니다:
|
||||
- `.claude/skills/` (프로젝트 레벨, 현재 작업 디렉토리 기준)
|
||||
- `~/.claude/skills/` (사용자 레벨, 모든 프로젝트에서 사용 가능)
|
||||
|
||||
**2. SKILL.md 작성:**
|
||||
```markdown
|
||||
---
|
||||
description: 이 프로젝트의 전체 릴리즈 프로세스 실행
|
||||
argument-hint: 버전 번호 (예: 1.2.3)
|
||||
---
|
||||
|
||||
$ARGUMENTS 버전으로 프로젝트를 릴리즈합니다.
|
||||
|
||||
단계:
|
||||
1. `package.json`의 버전을 $ARGUMENTS로 업데이트
|
||||
2. CHANGELOG.md에 이 버전의 새 섹션 추가
|
||||
3. `npm test` 실행 및 모든 테스트 통과 확인
|
||||
4. "chore: release v$ARGUMENTS" 메시지로 커밋
|
||||
5. `v$ARGUMENTS` git 태그 생성
|
||||
```
|
||||
|
||||
**3. 스킬 호출:**
|
||||
```
|
||||
/my-skill 1.2.3
|
||||
```
|
||||
|
||||
Claude가 스킬을 로드하고 지시사항을 실행합니다 — `1.2.3`이 `$ARGUMENTS`에 대입됩니다.
|
||||
|
||||
## 스킬 프론트매터
|
||||
|
||||
`SKILL.md` 상단의 프론트매터로 스킬 동작을 설정합니다. 모든 필드는 선택사항입니다.
|
||||
|
||||
| 필드 | 설명 |
|
||||
|------|------|
|
||||
| `description` | `/skills`에 표시되고 Claude가 언제 사용할지 결정하는 짧은 설명 |
|
||||
| `argument-hint` | 슬래시 커맨드 자동완성에 표시되는 힌트 |
|
||||
| `allowed-tools` | 이 스킬이 사용할 수 있는 도구 목록(기본값: 모두) |
|
||||
| `when_to_use` | Claude가 언제 이 스킬을 적극적으로 사용해야 하는지 설명 |
|
||||
| `model` | 이 스킬에 사용할 모델 (예: `claude-sonnet-4-6`) |
|
||||
| `user-invocable` | `false`로 설정해 슬래시 커맨드 목록에서 숨김 (Claude는 여전히 사용 가능) |
|
||||
| `context` | `fork`로 격리된 서브에이전트 컨텍스트에서 스킬 실행 |
|
||||
| `paths` | 일치하는 파일이 터치될 때만 스킬 활성화하는 Glob 패턴 |
|
||||
| `version` | 스킬 버전 문자열 |
|
||||
| `hooks` | 이 스킬 실행에 범위가 제한된 훅 |
|
||||
|
||||
## 인수 대입
|
||||
|
||||
`SKILL.md` 어디서나 `$ARGUMENTS`를 사용해 슬래시 커맨드 뒤에 전달된 텍스트를 삽입합니다:
|
||||
|
||||
```markdown
|
||||
$ARGUMENTS라는 이름의 새 React 컴포넌트를 프로젝트 컨벤션에 따라 생성합니다.
|
||||
```
|
||||
|
||||
```
|
||||
/new-component UserProfile
|
||||
```
|
||||
|
||||
명명된 인수의 경우, 프론트매터에 인수를 나열하고 `$name` 구문으로 참조합니다:
|
||||
|
||||
```yaml
|
||||
---
|
||||
arguments: [name, directory]
|
||||
---
|
||||
```
|
||||
|
||||
## 인라인 셸 커맨드
|
||||
|
||||
스킬은 호출 시 실행되는 셸 커맨드를 임베드할 수 있습니다. 출력이 Claude가 보기 전에 프롬프트에 삽입됩니다:
|
||||
|
||||
```markdown
|
||||
---
|
||||
description: 최근 변경 사항 검토
|
||||
---
|
||||
|
||||
컨텍스트를 위한 최근 커밋들:
|
||||
|
||||
!`git log --oneline -20`
|
||||
|
||||
위 변경 사항을 검토하고 무엇이 달성됐는지 요약해주세요.
|
||||
```
|
||||
|
||||
`!` 프리픽스 후 백틱으로 감싼 커맨드가 실행되고 해당 블록이 출력으로 교체됩니다.
|
||||
|
||||
> ⚠️ 인라인 셸 커맨드는 셸과 동일한 권한으로 실행됩니다. 스킬이 로드될 때가 아니라 호출될 때 실행됩니다.
|
||||
|
||||
## 스킬 목록 보기
|
||||
|
||||
```
|
||||
/skills
|
||||
```
|
||||
|
||||
모든 범위(프로젝트, 사용자, Managed)의 사용 가능한 모든 스킬과 설명을 표시합니다.
|
||||
|
||||
## 네임스페이스 스킬
|
||||
|
||||
서브디렉토리의 스킬은 콜론으로 네임스페이스됩니다:
|
||||
|
||||
```
|
||||
.claude/skills/
|
||||
deployment/
|
||||
SKILL.md → /deployment
|
||||
database/
|
||||
migrate/
|
||||
SKILL.md → /database:migrate
|
||||
seed/
|
||||
SKILL.md → /database:seed
|
||||
```
|
||||
|
||||
## 경로 기반 조건부 스킬
|
||||
|
||||
`paths` 프론트매터 필드를 추가해 일치하는 파일 작업 시에만 스킬을 활성화합니다:
|
||||
|
||||
```yaml
|
||||
---
|
||||
description: Django 모델 검토
|
||||
paths: "**/*.py"
|
||||
when_to_use: Django 모델 파일 편집 시 사용
|
||||
---
|
||||
```
|
||||
|
||||
Glob 패턴과 일치하는 파일을 읽거나, 쓰거나, 편집할 때 스킬이 자동으로 Claude의 컨텍스트에 로드됩니다.
|
||||
|
||||
## 사용자 레벨 스킬
|
||||
|
||||
`~/.claude/skills/`의 스킬은 각 저장소에 추가하지 않아도 모든 프로젝트에서 사용할 수 있습니다:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/standup
|
||||
cat > ~/.claude/skills/standup/SKILL.md << 'EOF'
|
||||
---
|
||||
description: 스탠드업 업데이트를 위해 오늘 작업한 내용 요약
|
||||
---
|
||||
|
||||
이 저장소에서 오늘의 git 커밋을 확인하고 스탠드업 형식으로 요약해주세요: 한 일, 다음에 할 일, 막히는 것. 3-4문장으로 유지해주세요.
|
||||
EOF
|
||||
```
|
||||
|
||||
## 스킬 예시: 컴포넌트 생성기
|
||||
|
||||
```markdown
|
||||
---
|
||||
description: 테스트와 함께 새 React 컴포넌트 생성
|
||||
argument-hint: ComponentName
|
||||
allowed-tools: Write, Bash
|
||||
---
|
||||
|
||||
$ARGUMENTS라는 이름의 새 React 컴포넌트를 만듭니다.
|
||||
|
||||
1. `src/components/$ARGUMENTS/$ARGUMENTS.tsx` 생성:
|
||||
- TypeScript를 사용하는 함수형 컴포넌트
|
||||
- `$ARGUMENTSProps`라는 Props 인터페이스
|
||||
- 컴포넌트를 설명하는 JSDoc 주석
|
||||
- default export
|
||||
|
||||
2. `src/components/$ARGUMENTS/$ARGUMENTS.test.tsx` 생성:
|
||||
- React Testing Library를 사용한 최소 하나의 렌더링 테스트
|
||||
- 스냅샷 테스트
|
||||
|
||||
3. 컴포넌트를 re-export하는 `src/components/$ARGUMENTS/index.ts` 생성
|
||||
|
||||
4. `npx tsc --noEmit`을 실행해 타입 오류 없음 확인
|
||||
```
|
||||
|
||||
호출:
|
||||
```
|
||||
/new-component Button
|
||||
```
|
||||
|
||||
## 훅 vs 스킬 비교
|
||||
|
||||
| 기능 | 스킬 | 훅 |
|
||||
|------|------|-----|
|
||||
| 호출 | 명시적: `/skill-name` 또는 Claude가 필요를 인식 | 자동: 도구 이벤트에 발생 |
|
||||
| 용도 | 의도적으로 트리거하려는 반복 가능한 워크플로우 | 부작용, 포맷팅, lint, 차단 |
|
||||
| 설정 | `.claude/skills/`의 `SKILL.md` | 설정 JSON의 `hooks` 필드 |
|
||||
| 컨텍스트 | 파일, 셸 출력, 상세 지시사항 포함 가능 | 이벤트 JSON 수신, 종료 코드와 출력 반환 |
|
||||
90
docs/claude-code-docs-main/16_커맨드개요.md
Normal file
90
docs/claude-code-docs-main/16_커맨드개요.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# 커맨드 개요
|
||||
|
||||
> Claude Code는 두 가지 커맨드 범주를 허용합니다: 실행 시 전달하는 CLI 플래그와 세션 중 입력하는 슬래시 커맨드.
|
||||
|
||||
## 두 가지 커맨드 타입
|
||||
|
||||
| 타입 | 사용 시점 | 예시 |
|
||||
|------|----------|------|
|
||||
| CLI 플래그 | 세션 시작 시 설정 — 모델, 출력 형식, 권한 모드 설정 | `claude --permission-mode acceptEdits "테스트 수정해줘"` |
|
||||
| 슬래시 커맨드 | 실행 중인 세션과 상호작용 — 메모리 관리, 모델 전환, 코드 커밋 | `/commit` |
|
||||
|
||||
CLI 플래그는 한 번 소비되고 세션 중간에 변경할 수 없습니다(실행 중인 설정을 변경하는 `/model`과 `/permissions` 제외).
|
||||
|
||||
## 도움말 확인
|
||||
|
||||
```bash
|
||||
# 모든 CLI 플래그 표시
|
||||
claude --help
|
||||
|
||||
# 세션 내에서 슬래시 커맨드 목록
|
||||
/help
|
||||
```
|
||||
|
||||
`/help`는 현재 세션에서 사용 가능한 모든 슬래시 커맨드를 나열합니다 — 플러그인과 스킬이 추가한 커맨드 포함.
|
||||
|
||||
## CLI 플래그 사용법
|
||||
|
||||
```bash
|
||||
claude [플래그] [프롬프트]
|
||||
```
|
||||
|
||||
```bash
|
||||
# 비대화형: 응답 출력 후 종료
|
||||
claude -p "README.md를 요약해줘" < README.md
|
||||
|
||||
# 세션 모델 설정
|
||||
claude --model opus
|
||||
|
||||
# 파일 편집 자동 승인
|
||||
claude --permission-mode acceptEdits
|
||||
```
|
||||
|
||||
자세한 내용은 [CLI 플래그](./17_CLI플래그.md) 참조.
|
||||
|
||||
## 슬래시 커맨드 사용법
|
||||
|
||||
세션 내에서 입력 프롬프트에 슬래시 커맨드 입력:
|
||||
|
||||
```
|
||||
/command [인수]
|
||||
```
|
||||
|
||||
```
|
||||
/init
|
||||
/compact 최근 세 작업만 요약해줘
|
||||
/model claude-opus-4-5
|
||||
```
|
||||
|
||||
자세한 내용은 [슬래시 커맨드](./18_슬래시커맨드.md) 참조.
|
||||
|
||||
## 키보드 단축키
|
||||
|
||||
모든 대화형 Claude Code 세션에서 작동:
|
||||
|
||||
| 키 | 동작 |
|
||||
|----|------|
|
||||
| `Ctrl+C` | 현재 응답 중단 (Claude가 턴 중간에 멈춤) |
|
||||
| `Ctrl+D` | Claude Code 종료 |
|
||||
| `Ctrl+L` | 터미널 화면 지우기 (대화 기록은 지우지 않음) |
|
||||
| `Up` / `Down` | 입력 기록 탐색 |
|
||||
| `Tab` | 슬래시 커맨드 이름 자동완성 |
|
||||
| `Escape` | 진행 중인 권한 프롬프트 취소 |
|
||||
|
||||
> 📝 `Ctrl+C`는 현재 응답을 중단하지만 대화는 유지합니다. 세션을 완전히 종료하려면 `Ctrl+D` 또는 `/exit`를 사용하세요.
|
||||
|
||||
## 서브커맨드
|
||||
|
||||
메인 `claude` 커맨드 외에도 터미널에서 사용 가능한 서브커맨드:
|
||||
|
||||
| 서브커맨드 | 설명 |
|
||||
|------------|------|
|
||||
| `claude mcp` | MCP 서버 설정 및 관리 |
|
||||
| `claude mcp serve` | Claude Code를 MCP 서버로 시작 |
|
||||
| `claude doctor` | 설치 및 설정 문제 진단 |
|
||||
| `claude update` | Claude Code를 최신 버전으로 업데이트 |
|
||||
|
||||
```bash
|
||||
claude mcp --help
|
||||
claude doctor
|
||||
```
|
||||
187
docs/claude-code-docs-main/17_CLI플래그.md
Normal file
187
docs/claude-code-docs-main/17_CLI플래그.md
Normal file
@@ -0,0 +1,187 @@
|
||||
# CLI 플래그
|
||||
|
||||
> 터미널에서 Claude Code를 실행할 때 전달할 수 있는 모든 옵션.
|
||||
|
||||
```bash
|
||||
claude [플래그] [프롬프트]
|
||||
```
|
||||
|
||||
## 핵심 플래그
|
||||
|
||||
**`-p, --print`**
|
||||
Claude를 비대화형으로 실행. Claude가 프롬프트를 처리하고 응답을 출력한 후 종료합니다. REPL이 시작되지 않습니다.
|
||||
```bash
|
||||
claude -p "src/index.ts의 메인 함수를 설명해줘"
|
||||
echo "이게 뭐야?" | claude -p
|
||||
```
|
||||
> ⚠️ `--print` 모드에서는 작업 공간 신뢰 다이얼로그가 건너뜁니다. 신뢰하는 디렉토리에서만 사용하세요.
|
||||
|
||||
**`--output-format <형식>`** (`--print`와 함께만 작동)
|
||||
| 값 | 설명 |
|
||||
|----|------|
|
||||
| `text` | 일반 텍스트 출력 (기본값) |
|
||||
| `json` | 완전한 결과가 담긴 단일 JSON 객체 |
|
||||
| `stream-json` | 실시간 이벤트를 담은 줄바꿈으로 구분된 JSON 스트림 |
|
||||
|
||||
**`--verbose`**
|
||||
상세 출력 활성화.
|
||||
|
||||
**`-v, --version`**
|
||||
버전 번호 출력 후 종료.
|
||||
|
||||
## 세션 계속 플래그
|
||||
|
||||
**`-c, --continue`**
|
||||
현재 디렉토리의 가장 최근 대화를 재개합니다.
|
||||
```bash
|
||||
claude --continue
|
||||
claude -c "이제 테스트 추가해줘"
|
||||
```
|
||||
|
||||
**`-r, --resume [session-id]`**
|
||||
세션 ID로 대화를 재개합니다. 값 없이 사용하면 지난 세션 목록에서 선택합니다.
|
||||
```bash
|
||||
claude --resume
|
||||
claude --resume 550e8400-e29b-41d4-a716-446655440000
|
||||
claude --resume "auth refactor"
|
||||
```
|
||||
|
||||
**`--fork-session`**
|
||||
`--continue` 또는 `--resume`과 함께 사용해 재개된 대화에서 분기된 새 세션을 만듭니다.
|
||||
|
||||
**`-n, --name <이름>`**
|
||||
세션 표시 이름 설정.
|
||||
|
||||
**`--no-session-persistence`**
|
||||
세션 영속성 비활성화. `--print`와 함께만 작동합니다.
|
||||
|
||||
## 모델 및 기능 플래그
|
||||
|
||||
**`--model <모델>`**
|
||||
세션 모델 설정. 별칭(`sonnet`, `opus`, `haiku`) 또는 전체 모델 ID(`claude-sonnet-4-6`) 허용.
|
||||
```bash
|
||||
claude --model sonnet
|
||||
claude --model opus
|
||||
claude --model claude-sonnet-4-6
|
||||
```
|
||||
|
||||
**`--effort <레벨>`**
|
||||
세션의 effort 레벨 설정: `low`, `medium` (기본), `high`, `max`.
|
||||
```bash
|
||||
claude --effort high "이 아키텍처를 검토해줘"
|
||||
```
|
||||
|
||||
**`--fallback-model <모델>`**
|
||||
기본 모델이 과부하될 때 자동 대체 모델 활성화. `--print`와 함께만 작동합니다.
|
||||
|
||||
## 권한 및 보안 플래그
|
||||
|
||||
**`--permission-mode <모드>`**
|
||||
세션의 권한 모드 설정:
|
||||
| 모드 | 동작 |
|
||||
|------|------|
|
||||
| `default` | 커맨드 실행 및 편집 전에 확인 요청 |
|
||||
| `acceptEdits` | 파일 편집 자동 적용; 셸 커맨드는 여전히 확인 필요 |
|
||||
| `plan` | 계획을 제안하고 실행 전 승인 대기 |
|
||||
| `bypassPermissions` | 프롬프트 없이 모든 작업 실행 — 격리된 샌드박스 환경 전용 |
|
||||
|
||||
**`--dangerously-skip-permissions`**
|
||||
모든 권한 검사를 우회합니다. `--permission-mode bypassPermissions`와 동일.
|
||||
> ⚠️ 인터넷 접근 없는 샌드박스 환경에서만 사용하세요.
|
||||
|
||||
**`--allowed-tools <도구...>`** (별칭: `--allowedTools`)
|
||||
Claude가 사용할 수 있는 도구의 쉼표 또는 공백 구분 목록.
|
||||
```bash
|
||||
claude --allowed-tools "Bash(git:*) Edit Read"
|
||||
```
|
||||
|
||||
**`--disallowed-tools <도구...>`**
|
||||
Claude가 사용할 수 없는 도구 목록.
|
||||
|
||||
**`--tools <도구...>`**
|
||||
세션에 사용 가능한 정확한 내장 도구 집합 지정. `""`는 모든 도구 비활성화.
|
||||
|
||||
## 컨텍스트 및 프롬프트 플래그
|
||||
|
||||
**`--add-dir <디렉토리...>`**
|
||||
도구 접근 컨텍스트에 하나 이상의 디렉토리 추가.
|
||||
```bash
|
||||
claude --add-dir /shared/libs --add-dir /shared/config
|
||||
```
|
||||
|
||||
**`--system-prompt <프롬프트>`**
|
||||
기본 시스템 프롬프트를 커스텀 프롬프트로 교체.
|
||||
|
||||
**`--append-system-prompt <텍스트>`**
|
||||
기본 시스템 프롬프트에 텍스트 추가. `--system-prompt`와 달리 내장 지시사항을 유지합니다.
|
||||
|
||||
**`--mcp-config <설정...>`**
|
||||
하나 이상의 JSON 설정 파일 또는 인라인 JSON 문자열에서 MCP 서버 로드.
|
||||
|
||||
**`--strict-mcp-config`**
|
||||
`--mcp-config`의 MCP 서버만 사용하고 다른 모든 MCP 설정 무시.
|
||||
|
||||
**`--settings <파일-또는-json>`**
|
||||
JSON 파일 경로 또는 인라인 JSON 문자열에서 추가 설정 로드.
|
||||
|
||||
**`--agents <json>`**
|
||||
JSON 객체로 커스텀 에이전트를 인라인으로 정의.
|
||||
|
||||
## 출력 제어 플래그
|
||||
|
||||
**`--max-turns <n>`**
|
||||
비대화형 모드의 에이전틱 턴 수 제한. `--print`와 함께만 작동합니다.
|
||||
|
||||
**`--max-budget-usd <금액>`**
|
||||
API 호출 최대 지출 금액 설정. `--print`와 함께만 작동합니다.
|
||||
|
||||
**`--json-schema <스키마>`**
|
||||
구조화된 출력 검증을 위한 JSON 스키마 제공.
|
||||
|
||||
## Worktree 플래그
|
||||
|
||||
**`-w, --worktree [이름]`**
|
||||
세션에 새 git worktree 생성. PR 번호나 GitHub PR URL 허용.
|
||||
```bash
|
||||
claude --worktree
|
||||
claude --worktree feature-auth
|
||||
claude --worktree "#142"
|
||||
```
|
||||
|
||||
**`--tmux`**
|
||||
worktree와 함께 tmux 세션 생성. `--worktree` 필요.
|
||||
|
||||
## 디버그 플래그
|
||||
|
||||
**`-d, --debug [필터]`**
|
||||
디버그 모드 활성화.
|
||||
```bash
|
||||
claude --debug
|
||||
claude --debug "api,hooks"
|
||||
claude --debug "!file,!1p"
|
||||
```
|
||||
|
||||
**`--debug-file <경로>`**
|
||||
디버그 로그를 인라인 표시 대신 파일에 저장.
|
||||
|
||||
**`--bare`**
|
||||
최소 모드. 훅, LSP, 플러그인 동기화, 어트리뷰션, 자동 메모리, 백그라운드 프리페치, 키체인 읽기, `CLAUDE.md` 자동 발견을 모두 건너뜁니다. 스타트업 지연이 중요하고 이러한 기능이 필요하지 않은 스크립트 파이프라인에 사용하세요.
|
||||
|
||||
## 일반적인 플래그 조합
|
||||
|
||||
```bash
|
||||
# JSON 출력과 함께 비대화형
|
||||
claude -p "모든 내보낸 타입 목록" --output-format json
|
||||
|
||||
# CI에서 권한 우회 (샌드박스 환경 전용)
|
||||
claude -p "전체 테스트 스위트 실행하고 실패 수정해줘" --dangerously-skip-permissions
|
||||
|
||||
# 마지막 세션 재개 후 비대화형으로 계속
|
||||
claude --continue -p "이제 그것에 대한 테스트 작성해줘"
|
||||
|
||||
# 커스텀 MCP 설정으로 엄격한 격리
|
||||
claude --mcp-config ./ci-mcp.json --strict-mcp-config -p "스키마 분석해줘"
|
||||
|
||||
# 시스템 프롬프트를 교체하지 않고 추가
|
||||
claude --append-system-prompt "항상 JavaScript가 아닌 TypeScript를 출력하세요."
|
||||
```
|
||||
171
docs/claude-code-docs-main/18_슬래시커맨드.md
Normal file
171
docs/claude-code-docs-main/18_슬래시커맨드.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# 슬래시 커맨드
|
||||
|
||||
> 실행 중인 Claude Code 세션에서 입력하는 커맨드.
|
||||
|
||||
```
|
||||
/command [인수]
|
||||
```
|
||||
|
||||
세션 내에서 언제든 `/help`를 입력해 모든 커맨드를 볼 수 있습니다.
|
||||
|
||||
## 빠른 참조
|
||||
|
||||
| 커맨드 | 설명 |
|
||||
|--------|------|
|
||||
| `/init` | 프로젝트의 `CLAUDE.md` 파일 및 선택적 스킬/훅 생성 |
|
||||
| `/memory` | Claude 메모리 파일 편집 (전역, 프로젝트, 로컬) |
|
||||
| `/config` | 설정 패널 열기 |
|
||||
| `/hooks` | 도구 이벤트의 훅 설정 보기 |
|
||||
| `/mcp` | MCP 서버 관리 — 활성화, 비활성화, 재연결 |
|
||||
| `/permissions` | 도구의 허용/차단 규칙 관리 |
|
||||
| `/plan` | plan 모드 활성화 또는 현재 세션 계획 열기/설명 |
|
||||
| `/model` | 현재 세션의 AI 모델 설정 |
|
||||
| `/commit` | AI가 생성한 메시지로 git 커밋 생성 |
|
||||
| `/review` | 풀 리퀘스트 검토 |
|
||||
| `/skills` | 사용 가능한 스킬 목록 |
|
||||
| `/compact` | 컨텍스트 사용량 줄이기 위해 대화 기록 요약 |
|
||||
| `/clear` | 대화 기록 지우기 및 컨텍스트 해제 |
|
||||
| `/help` | 도움말 및 사용 가능한 커맨드 표시 |
|
||||
| `/login` | 로그인 또는 Anthropic 계정 전환 |
|
||||
| `/logout` | Anthropic 계정에서 로그아웃 |
|
||||
|
||||
---
|
||||
|
||||
## 프로젝트 및 메모리 커맨드
|
||||
|
||||
### `/init`
|
||||
|
||||
코드베이스를 분석하고 `CLAUDE.md` 파일과 선택적으로 스킬과 훅을 설정합니다. Claude가 주요 프로젝트 파일(매니페스트, CI 설정, 빌드 스크립트, README)을 조사한 후 인터뷰를 통해 빠진 내용을 채우고 출력 파일을 작성합니다.
|
||||
|
||||
설정 내용(사용자 선택에 따라):
|
||||
- **프로젝트 `CLAUDE.md`** — 팀 공유 지시사항, 소스 컨트롤에 커밋
|
||||
- **개인 `CLAUDE.local.md`** — 이 프로젝트의 개인 설정(gitignore됨)
|
||||
- **스킬** — 슬래시 커맨드로 호출하는 온디맨드 워크플로우
|
||||
- **훅** — 도구 이벤트에서 자동으로 실행되는 결정론적 셸 커맨드
|
||||
|
||||
> 💡 언제든 `/init`을 다시 실행하세요. `CLAUDE.md`가 이미 있으면 Claude가 파일을 덮어쓰는 대신 구체적인 변경 사항을 제안합니다.
|
||||
|
||||
### `/memory`
|
||||
|
||||
Claude의 메모리 파일 대화형 에디터를 엽니다. 세 가지 메모리 범위:
|
||||
|
||||
| 범위 | 파일 | 적용 대상 |
|
||||
|------|------|----------|
|
||||
| 전역 | `~/.claude/CLAUDE.md` | 모든 프로젝트의 나 |
|
||||
| 프로젝트 | 프로젝트 루트의 `CLAUDE.md` | 팀 전체 |
|
||||
| 로컬 | 프로젝트 루트의 `CLAUDE.local.md` | 이 프로젝트의 나 (gitignore됨) |
|
||||
|
||||
---
|
||||
|
||||
## 설정 커맨드
|
||||
|
||||
### `/config` (별칭: `/settings`)
|
||||
Claude Code 설정을 보고 편집하는 설정 패널 열기.
|
||||
|
||||
### `/hooks`
|
||||
현재 세션에서 활성화된 훅 설정 표시. 훅을 만들거나 편집하려면 `/init`을 사용하거나 `.claude/settings.json`을 직접 편집하세요.
|
||||
|
||||
### `/mcp [enable|disable [server-name]]`
|
||||
|
||||
현재 세션의 MCP 서버 관리:
|
||||
|
||||
| 인수 | 효과 |
|
||||
|------|------|
|
||||
| (없음) | MCP 관리 패널 열기 |
|
||||
| `enable` | 모든 비활성 MCP 서버 활성화 |
|
||||
| `enable <server-name>` | 특정 서버 활성화 |
|
||||
| `disable` | 모든 활성 MCP 서버 비활성화 |
|
||||
| `disable <server-name>` | 특정 서버 비활성화 |
|
||||
| `reconnect <server-name>` | 특정 서버에 재연결 |
|
||||
|
||||
> 📝 `/mcp enable/disable`로 만든 변경 사항은 현재 세션에만 적용됩니다.
|
||||
|
||||
### `/permissions` (별칭: `/allowed-tools`)
|
||||
도구의 허용 및 차단 규칙을 보고 관리하는 권한 패널 열기.
|
||||
|
||||
### `/model [모델]`
|
||||
세션의 AI 모델 설정:
|
||||
```
|
||||
/model
|
||||
/model sonnet
|
||||
/model claude-opus-4-5
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 세션 관리 커맨드
|
||||
|
||||
### `/plan [open|<설명>]`
|
||||
| 인수 | 효과 |
|
||||
|------|------|
|
||||
| (없음) | plan 모드 토글 |
|
||||
| `open` | 현재 계획 열기 및 표시 |
|
||||
| `<설명>` | 주어진 설명으로 새 계획 생성 |
|
||||
|
||||
plan 모드에서 Claude는 어떤 작업도 실행하기 전에 작성된 계획을 만들고 승인을 기다립니다.
|
||||
|
||||
### `/compact [지시사항]`
|
||||
대화 기록을 요약하고 컨텍스트 윈도우가 가득 차도 작업을 계속할 수 있게 합니다. 선택적 인수로 요약 방법을 지시할 수 있습니다.
|
||||
```
|
||||
/compact
|
||||
/compact 데이터베이스 스키마 변경에만 집중해줘
|
||||
/compact 완료된 최근 세 작업만 요약해줘
|
||||
```
|
||||
|
||||
### `/clear` (별칭: `/reset`, `/new`)
|
||||
전체 대화 기록을 지우고 컨텍스트를 해제해 동일한 작업 디렉토리에서 새 세션을 시작합니다. `/compact`와 달리 요약하는 대신 모든 기록을 제거합니다.
|
||||
|
||||
### `/skills`
|
||||
현재 세션에서 사용 가능한 모든 스킬을 나열합니다.
|
||||
|
||||
---
|
||||
|
||||
## Git 커맨드
|
||||
|
||||
### `/commit`
|
||||
AI가 생성한 커밋 메시지로 git 커밋을 만듭니다. Claude가 현재 git 상태와 diff를 읽고, 스테이징된 변경 사항을 분석하고, "무엇"이 아닌 "왜"에 초점을 맞춘 간결한 커밋 메시지를 작성합니다.
|
||||
|
||||
안전 규칙:
|
||||
- 기존 커밋을 절대 amend하지 않음
|
||||
- 훅을 건너뛰지 않음 (`--no-verify` 사용 안 함)
|
||||
- 시크릿을 포함할 가능성이 있는 파일은 커밋하지 않음
|
||||
- 변경 사항이 없으면 빈 커밋을 만들지 않음
|
||||
|
||||
> 📝 `/commit`은 `git add`, `git status`, `git commit`에만 접근 가능합니다. push, rebase 등의 다른 git 작업은 실행할 수 없습니다.
|
||||
|
||||
### `/review [PR-번호]`
|
||||
GitHub CLI(`gh`)를 사용해 풀 리퀘스트에 AI 코드 리뷰를 실행합니다. PR 번호 없이 사용하면 열린 PR 목록을 표시합니다. 리뷰 내용:
|
||||
- PR이 하는 일 개요
|
||||
- 코드 품질 및 스타일 분석
|
||||
- 구체적인 개선 제안
|
||||
- 잠재적 문제 또는 리스크
|
||||
- 성능, 테스트 커버리지, 보안 고려사항
|
||||
|
||||
> 📝 `/review`는 [GitHub CLI](https://cli.github.com/)(`gh`)가 설치되고 인증되어야 합니다.
|
||||
|
||||
---
|
||||
|
||||
## 계정 및 도움말 커맨드
|
||||
|
||||
### `/help`
|
||||
현재 세션에서 사용 가능한 모든 슬래시 커맨드 목록 표시 — 내장 커맨드, 스킬 커맨드, 설치된 플러그인이 추가한 커맨드 포함.
|
||||
|
||||
### `/login`
|
||||
Anthropic 계정에 로그인하거나 계정을 전환합니다.
|
||||
|
||||
### `/logout`
|
||||
Anthropic 계정에서 로그아웃합니다. 로그아웃 후 다음 세션에서 다시 인증을 요청합니다.
|
||||
|
||||
---
|
||||
|
||||
## 커스텀 스킬 커맨드
|
||||
|
||||
`.claude/skills/<skill-name>/SKILL.md`에 스킬이 생성되면 해당 스킬이 로드된 모든 세션에서 `/<skill-name>`으로 사용할 수 있습니다.
|
||||
|
||||
```
|
||||
/verify
|
||||
/deploy staging
|
||||
/fix-issue 123
|
||||
```
|
||||
|
||||
`/skills`를 실행해 로드된 모든 스킬과 설명을 확인하세요.
|
||||
249
docs/claude-code-docs-main/19_훅레퍼런스.md
Normal file
249
docs/claude-code-docs-main/19_훅레퍼런스.md
Normal file
@@ -0,0 +1,249 @@
|
||||
# 훅 레퍼런스
|
||||
|
||||
> 모든 훅 이벤트, 입력 페이로드, 출력 스키마, 각 종료 코드가 Claude 동작에 미치는 영향에 대한 전체 레퍼런스.
|
||||
|
||||
훅은 Claude의 에이전틱 루프에서 정의된 지점에서 발생하는 셸 커맨드, HTTP 엔드포인트, LLM 프롬프트, 또는 인프로세스 콜백입니다.
|
||||
|
||||
## 설정
|
||||
|
||||
훅은 설정 파일의 최상위 `hooks` 키로 구성됩니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo 'bash 커맨드 실행 예정' >&2"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 매처 설정
|
||||
|
||||
`matcher` 필드는 이벤트별로 다른 필드와 매칭됩니다:
|
||||
|
||||
| 이벤트 | 매칭되는 필드 |
|
||||
|--------|-------------|
|
||||
| `PreToolUse` / `PostToolUse` / `PostToolUseFailure` / `PermissionRequest` / `PermissionDenied` | `tool_name` |
|
||||
| `Notification` | `notification_type` |
|
||||
| `SessionStart` | `source` (`startup`, `resume`, `clear`, `compact`) |
|
||||
| `Setup` | `trigger` (`init`, `maintenance`) |
|
||||
| `SubagentStart` / `SubagentStop` | `agent_type` |
|
||||
| `PreCompact` / `PostCompact` | `trigger` (`manual`, `auto`) |
|
||||
| `ConfigChange` | `source` |
|
||||
| `FileChanged` | 파일 이름 패턴 (예: `".envrc|.env"`) |
|
||||
|
||||
## 훅 타입
|
||||
|
||||
**셸 커맨드:**
|
||||
```json
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq '.tool_name' && my-validator",
|
||||
"timeout": 30,
|
||||
"shell": "bash",
|
||||
"async": false,
|
||||
"once": false,
|
||||
"if": "Bash(git *)",
|
||||
"statusMessage": "검증 중..."
|
||||
}
|
||||
```
|
||||
|
||||
필드:
|
||||
- `command`: 실행할 셸 커맨드 (필수)
|
||||
- `timeout`: 타임아웃(초), 기본 60초
|
||||
- `shell`: `bash` (기본) 또는 `powershell`
|
||||
- `async`: `true`면 백그라운드에서 비블로킹 실행
|
||||
- `asyncRewake`: `true`면 백그라운드 실행, 종료코드 2로 종료 시 모델 깨움
|
||||
- `once`: `true`면 한 번 실행 후 자동 제거
|
||||
- `if`: 조건부로 훅 건너뛰기 위한 권한 규칙 구문
|
||||
- `statusMessage`: 실행 중 스피너에 표시되는 커스텀 메시지
|
||||
|
||||
**LLM 평가:**
|
||||
```json
|
||||
{
|
||||
"type": "prompt",
|
||||
"prompt": "이 bash 커맨드가 안전한지 확인하세요: $ARGUMENTS",
|
||||
"model": "claude-haiku-4-5",
|
||||
"timeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
**에이전틱 검증기:**
|
||||
```json
|
||||
{
|
||||
"type": "agent",
|
||||
"prompt": "단위 테스트가 실행되고 통과했는지 확인하세요.",
|
||||
"model": "claude-haiku-4-5",
|
||||
"timeout": 120
|
||||
}
|
||||
```
|
||||
|
||||
**HTTP 엔드포인트:**
|
||||
```json
|
||||
{
|
||||
"type": "http",
|
||||
"url": "https://my-server.example.com/hook",
|
||||
"headers": {
|
||||
"Authorization": "Bearer $MY_TOKEN"
|
||||
},
|
||||
"allowedEnvVars": ["MY_TOKEN"],
|
||||
"timeout": 10
|
||||
}
|
||||
```
|
||||
|
||||
## 기본 훅 입력
|
||||
|
||||
모든 훅이 stdin에서 받는 공통 필드:
|
||||
|
||||
| 필드 | 타입 | 설명 |
|
||||
|------|------|------|
|
||||
| `hook_event_name` | `string` | 발생한 이벤트 (예: `"PreToolUse"`) |
|
||||
| `session_id` | `string` | 현재 세션 식별자 |
|
||||
| `transcript_path` | `string` | 세션 JSONL 트랜스크립트 파일의 절대 경로 |
|
||||
| `cwd` | `string` | 훅 발생 시점의 현재 작업 디렉토리 |
|
||||
| `permission_mode` | `string` | 활성 권한 모드 |
|
||||
| `agent_id` | `string` | 서브에이전트에서 발생 시 식별자 |
|
||||
|
||||
## 동기 훅 출력 (stdout의 JSON)
|
||||
|
||||
블로킹 훅의 경우 종료 전에 JSON을 stdout에 씁니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"continue": true,
|
||||
"suppressOutput": false,
|
||||
"decision": "approve",
|
||||
"reason": "커맨드가 안전합니다",
|
||||
"systemMessage": "훅이 이 작업을 승인했습니다.",
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"permissionDecision": "allow"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 훅 이벤트 상세
|
||||
|
||||
### `PreToolUse`
|
||||
도구가 실행되기 직전에 발생.
|
||||
|
||||
**입력 필드:** `tool_name`, `tool_input`, `tool_use_id`
|
||||
|
||||
**종료 코드:**
|
||||
| 코드 | 효과 |
|
||||
|------|------|
|
||||
| `0` | stdout/stderr 표시 안 됨. 훅 출력 JSON 적용 |
|
||||
| `2` | stderr를 Claude에게 표시; 도구 호출 **차단** |
|
||||
| 기타 | stderr를 사용자에게만 표시; 도구 호출 계속 |
|
||||
|
||||
**`hookSpecificOutput` 필드:**
|
||||
- `permissionDecision`: `'allow'` | `'deny'` | `'ask'` — 권한 결정 재정의
|
||||
- `updatedInput`: 도구가 받을 교체 입력
|
||||
- `additionalContext`: 이 턴의 Claude 컨텍스트에 주입될 텍스트
|
||||
|
||||
---
|
||||
|
||||
### `PostToolUse`
|
||||
도구가 성공적으로 완료된 후 발생.
|
||||
|
||||
**입력 필드:** `tool_name`, `tool_input`, `tool_response`, `tool_use_id`
|
||||
|
||||
**종료 코드:**
|
||||
| 코드 | 효과 |
|
||||
|------|------|
|
||||
| `0` | stdout이 트랜스크립트 모드에 표시 (Ctrl+O) |
|
||||
| `2` | stderr를 즉시 Claude에게 시스템 메시지로 표시 |
|
||||
| 기타 | stderr를 사용자에게만 표시 |
|
||||
|
||||
---
|
||||
|
||||
### `Stop`
|
||||
Claude가 응답을 종료하기 직전에 발생.
|
||||
|
||||
**입력 필드:** `stop_hook_active`, `last_assistant_message`
|
||||
|
||||
**종료 코드:**
|
||||
| 코드 | 효과 |
|
||||
|------|------|
|
||||
| `0` | stdout/stderr 표시 안 됨 |
|
||||
| `2` | stderr를 시스템 메시지로 주입; Claude **대화 계속** |
|
||||
| 기타 | stderr를 사용자에게만 표시; Claude 중지 |
|
||||
|
||||
> 💡 Stop 훅의 종료코드 2를 사용해 Claude 출력을 확인하고 조건이 충족되지 않으면 대화를 계속하게 합니다 — 예를 들어 테스트가 여전히 실패하는 경우.
|
||||
|
||||
---
|
||||
|
||||
### `SessionStart`
|
||||
세션 시작 시 발생. 초기 컨텍스트 주입이나 환경 설정에 사용.
|
||||
|
||||
**입력 필드:** `source` (`'startup'` | `'resume'` | `'clear'` | `'compact'`), `model`
|
||||
|
||||
**`hookSpecificOutput` 필드:**
|
||||
- `additionalContext`: 세션 시스템 프롬프트에 주입될 컨텍스트
|
||||
- `initialUserMessage`: 세션의 첫 사용자 메시지로 자동 제출
|
||||
- `watchPaths`: `FileChanged` 감시기에 등록할 절대 파일 경로
|
||||
|
||||
---
|
||||
|
||||
### `UserPromptSubmit`
|
||||
사용자가 프롬프트를 제출할 때 발생.
|
||||
|
||||
**입력 필드:** `prompt`
|
||||
|
||||
**종료 코드:**
|
||||
| 코드 | 효과 |
|
||||
|------|------|
|
||||
| `0` | stdout이 Claude에게 추가 컨텍스트로 표시 |
|
||||
| `2` | 처리 **차단**; 원본 프롬프트 지워짐; stderr를 사용자에게 표시 |
|
||||
| 기타 | stderr를 사용자에게만 표시 |
|
||||
|
||||
---
|
||||
|
||||
### `PermissionRequest`
|
||||
권한 다이얼로그가 표시될 때 발생. UI 없이 프로그래밍 방식으로 승인/거부 가능.
|
||||
|
||||
**종료 코드:**
|
||||
| 코드 | 효과 |
|
||||
|------|------|
|
||||
| `0` | `hookSpecificOutput.decision`이 설정된 경우 훅 결정 적용 |
|
||||
| 기타 | stderr를 사용자에게 표시; 일반 다이얼로그로 폴백 |
|
||||
|
||||
---
|
||||
|
||||
### `CwdChanged`
|
||||
작업 디렉토리 변경 후 발생.
|
||||
|
||||
**입력 필드:** `old_cwd`, `new_cwd`
|
||||
|
||||
`CLAUDE_ENV_FILE` 환경 변수가 설정됨 — 환경 변수를 `export KEY=value` 줄로 써서 이후 Bash 도구 호출에 적용합니다.
|
||||
|
||||
---
|
||||
|
||||
### `FileChanged`
|
||||
감시 중인 파일이 수정, 추가, 제거될 때 발생.
|
||||
|
||||
**입력 필드:** `file_path`, `event` (`'change'` | `'add'` | `'unlink'`)
|
||||
|
||||
---
|
||||
|
||||
## 비동기 훅
|
||||
|
||||
백그라운드에서 실행되는 훅은 일반 동기 출력 대신 비동기 확인을 stdout에 출력합니다:
|
||||
|
||||
```json
|
||||
{
|
||||
"async": true,
|
||||
"asyncTimeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
> ⚠️ 비동기 훅은 도구 실행을 차단하거나 컨텍스트를 주입할 수 없습니다. 에이전틱 루프를 느리게 하면 안 되는 알림, 로깅, 메트릭 같은 부작용에 사용하세요.
|
||||
229
docs/claude-code-docs-main/20_SDK개요.md
Normal file
229
docs/claude-code-docs-main/20_SDK개요.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# SDK 개요
|
||||
|
||||
> stdin/stdout 제어 프로토콜을 사용해 자체 도구에 Claude Code를 임베드하는 방법. SDK 세션 API, 메시지 타입, 출력 형식에 대한 레퍼런스.
|
||||
|
||||
Claude Code SDK는 다른 애플리케이션에 Claude Code를 임베드하기 위한 제어 프로토콜입니다 — IDE, 자동화 스크립트, CI/CD 파이프라인, 또는 서브프로세스를 스폰하고 stdin/stdout으로 통신할 수 있는 모든 호스트.
|
||||
|
||||
라이브러리 API를 직접 노출하는 대신, 구조화된 JSON 메시지 스트림을 통해 실행 중인 `claude` 프로세스와 통신합니다. 호스트 프로세스가 사용자 메시지와 제어 요청을 전송하면 CLI 프로세스가 어시스턴트 메시지, 도구 진행 이벤트, 결과 페이로드를 스트리밍합니다.
|
||||
|
||||
## 작동 방식
|
||||
|
||||
1. **Claude Code 프로세스 스폰** — `--output-format stream-json`과 `--print`로 시작 (비대화형 모드). stdin과 stdout을 호스트 프로세스로 파이핑.
|
||||
|
||||
```bash
|
||||
claude --output-format stream-json --print --verbose
|
||||
```
|
||||
|
||||
여러 프롬프트를 받는 영속 세션은 `--print`를 생략하고 세션 초기화 후 stdin에 `SDKUserMessage` 객체를 전송합니다.
|
||||
|
||||
2. **초기화 요청 전송** — stdin에 `control_request` (`subtype: "initialize"`) 작성. CLI가 `SDKControlInitializeResponse`로 응답합니다.
|
||||
|
||||
3. **stdout에서 메시지 스트리밍** — stdout에서 줄바꿈으로 구분된 JSON 읽기. 각 줄이 `SDKMessage` 유니온 타입 중 하나입니다.
|
||||
|
||||
4. **사용자 메시지 전송** — 대화를 계속하려면 stdin에 `SDKUserMessage` 객체 작성.
|
||||
|
||||
## 출력 형식
|
||||
|
||||
| 형식 | 설명 |
|
||||
|------|------|
|
||||
| `text` | 일반 텍스트 응답만. 대화형 모드의 기본값 |
|
||||
| `json` | 완료 시 작성되는 단일 JSON 객체. 일회성 스크립트에 적합 |
|
||||
| `stream-json` | 줄바꿈으로 구분된 JSON 스트림. 이벤트 발생 시 줄당 하나의 메시지. SDK 사용에 필수 |
|
||||
|
||||
## 제어 프로토콜 메시지
|
||||
|
||||
제어 프로토콜은 stdin/stdout에서 양방향으로 흐르는 두 가지 최상위 봉투 타입을 사용합니다.
|
||||
|
||||
### `SDKControlRequest` (호스트 → CLI)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "<고유-문자열>",
|
||||
"request": { "subtype": "...", ...페이로드 }
|
||||
}
|
||||
```
|
||||
|
||||
### `SDKControlResponse` (CLI → 호스트)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "control_response",
|
||||
"response": {
|
||||
"subtype": "success",
|
||||
"request_id": "<에코된-id>",
|
||||
"response": { ...페이로드 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
오류 시 `subtype`은 `"error"`이고 `error` 필드에 메시지가 포함됩니다.
|
||||
|
||||
## 초기화 요청
|
||||
|
||||
`initialize` 요청은 반드시 먼저 보내야 합니다. 세션을 설정하고 사용 가능한 기능을 반환합니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "init-1",
|
||||
"request": {
|
||||
"subtype": "initialize",
|
||||
"systemPrompt": "당신은 CI 자동화 에이전트입니다.",
|
||||
"appendSystemPrompt": "항상 테스트 커버리지를 추가하세요.",
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hookCallbackIds": ["my-hook-id"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"agents": {
|
||||
"CodeReviewer": {
|
||||
"description": "코드 품질과 보안을 검토합니다.",
|
||||
"prompt": "당신은 전문 코드 리뷰어입니다...",
|
||||
"model": "opus"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 초기화 응답
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "control_response",
|
||||
"response": {
|
||||
"subtype": "success",
|
||||
"request_id": "init-1",
|
||||
"response": {
|
||||
"commands": [...],
|
||||
"agents": [...],
|
||||
"output_style": "stream-json",
|
||||
"models": [...],
|
||||
"account": {
|
||||
"email": "user@example.com",
|
||||
"organization": "Acme Corp",
|
||||
"apiProvider": "firstParty"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 사용자 메시지
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "user",
|
||||
"message": {
|
||||
"role": "user",
|
||||
"content": "이 함수를 async/await으로 리팩터링해줘."
|
||||
},
|
||||
"parent_tool_use_id": null
|
||||
}
|
||||
```
|
||||
|
||||
- `parent_tool_use_id`: 이 메시지가 응답하는 도구 사용 ID, 최상위 사용자 메시지는 `null`
|
||||
- `priority`: `'now'` | `'next'` | `'later'` — 비동기 메시지 큐잉 스케줄링 힌트
|
||||
|
||||
## SDK 메시지 스트림 타입
|
||||
|
||||
| 타입 | 설명 |
|
||||
|------|------|
|
||||
| `system` (`subtype: "init"`) | 세션 시작 시 한 번 출력. 활성 모델, 도구 목록, MCP 서버 상태, 권한 모드, 세션 ID 포함 |
|
||||
| `assistant` | 모델이 턴을 생성할 때 출력. `tool_use` 블록 포함 가능 |
|
||||
| `stream_event` | 스트리밍 중 부분 토큰 출력. 점진적 렌더링에 사용 |
|
||||
| `tool_progress` | 몇 초 이상 걸리는 도구의 주기적 상태 업데이트 |
|
||||
| `result` | 각 턴 종료 시 출력. `subtype`은 `"success"` 또는 오류 서브타입 |
|
||||
|
||||
**result 예시:**
|
||||
```json
|
||||
{
|
||||
"type": "result",
|
||||
"subtype": "success",
|
||||
"result": "함수가 리팩터링되었습니다.",
|
||||
"duration_ms": 4200,
|
||||
"total_cost_usd": 0.0042,
|
||||
"num_turns": 3,
|
||||
"is_error": false,
|
||||
"session_id": "abc123"
|
||||
}
|
||||
```
|
||||
|
||||
## 기타 제어 요청
|
||||
|
||||
| `subtype` | 방향 | 설명 |
|
||||
|-----------|------|------|
|
||||
| `interrupt` | 호스트 → CLI | 현재 턴 중단 |
|
||||
| `set_permission_mode` | 호스트 → CLI | 활성 권한 모드 변경 |
|
||||
| `set_model` | 호스트 → CLI | 세션 중간에 모델 전환 |
|
||||
| `can_use_tool` | CLI → 호스트 | 도구 호출 권한 요청 |
|
||||
| `mcp_status` | 호스트 → CLI | MCP 서버 연결 상태 가져오기 |
|
||||
| `get_context_usage` | 호스트 → CLI | 컨텍스트 윈도우 사용량 가져오기 |
|
||||
| `rewind_files` | 호스트 → CLI | 특정 메시지 이후 파일 변경 사항 되돌리기 |
|
||||
| `hook_callback` | CLI → 호스트 | SDK에 등록된 훅 이벤트 전달 |
|
||||
|
||||
## 세션 관리 API
|
||||
|
||||
스크립팅 시나리오를 위해 SDK가 `~/.claude/`에 저장된 세션 트랜스크립트를 조작하는 함수를 내보냅니다:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
query,
|
||||
listSessions,
|
||||
getSessionInfo,
|
||||
getSessionMessages,
|
||||
forkSession,
|
||||
renameSession,
|
||||
tagSession,
|
||||
} from '@anthropic-ai/claude-code'
|
||||
```
|
||||
|
||||
**`query` — 프롬프트 실행 (주요 SDK 진입점):**
|
||||
```typescript
|
||||
for await (const message of query({
|
||||
prompt: '이 디렉토리에 어떤 파일이 있나요?',
|
||||
options: { cwd: '/my/project' }
|
||||
})) {
|
||||
if (message.type === 'result') {
|
||||
console.log(message.result)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**`listSessions` — 저장된 세션 목록:**
|
||||
```typescript
|
||||
const sessions = await listSessions({ dir: '/my/project', limit: 50 })
|
||||
```
|
||||
|
||||
**`getSessionMessages` — 트랜스크립트 읽기:**
|
||||
```typescript
|
||||
const messages = await getSessionMessages(sessionId, {
|
||||
dir: '/my/project',
|
||||
includeSystemMessages: false,
|
||||
})
|
||||
```
|
||||
|
||||
**`forkSession` — 대화 분기:**
|
||||
```typescript
|
||||
const { sessionId: newId } = await forkSession(originalSessionId, {
|
||||
upToMessageId: 'msg-uuid',
|
||||
title: '실험적 분기',
|
||||
})
|
||||
```
|
||||
|
||||
## 사용 사례
|
||||
|
||||
**IDE 통합:** IDE가 영속 Claude Code 프로세스를 스폰하고 제어 프로토콜을 통해 메시지를 라우팅합니다. `PreToolUse` 훅 콜백으로 파일 편집을 가로채 적용 전에 IDE 네이티브 UI에 diff를 표시합니다.
|
||||
|
||||
**CI/CD 자동화:**
|
||||
```bash
|
||||
result=$(echo "diff를 검토하고 pass/fail을 출력해줘" | \
|
||||
claude --output-format json --print \
|
||||
--permission-mode bypassPermissions)
|
||||
```
|
||||
|
||||
**헤드리스 에이전트:** TypeScript SDK에서 스트리밍 출력 형식으로 `query()`를 사용합니다. 지속 데몬 프로세스를 유지하면서 크론 스케줄로 작업을 실행합니다.
|
||||
54
docs/claude-code-docs-main/README.md
Normal file
54
docs/claude-code-docs-main/README.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Claude Code Docs (KO/EN)
|
||||
|
||||
> 2026년 3월, Claude Code의 npm 소스맵을 통해 내부 TypeScript 소스코드가 유출되는 사건이 발생했습니다.
|
||||
> 이 레포는 그 과정에서 공개된 내부 구조 분석 문서를 한국어로 번역·정리한 아카이브입니다.
|
||||
|
||||
---
|
||||
|
||||
## 배경
|
||||
|
||||
2026년 3월 31일, Claude Code npm 패키지에 포함된 `.map` 파일이 Anthropic의 내부 R2 버킷에 있는 unobfuscated TypeScript 소스 zip을 가리키고 있음이 발견되었습니다. 이를 통해 약 1,900개 파일, 512,000줄 규모의 Claude Code 원본 소스가 외부에 노출되었습니다.
|
||||
|
||||
유출된 소스를 분석한 커뮤니티([@VineeTagarwaL](https://github.com/VineeTagarwaL-code))는 내부 아키텍처를 문서화하여 Mintlify 사이트로 공개했습니다. 이 레포는 해당 문서를 한국어로 번역한 것입니다.
|
||||
|
||||
---
|
||||
|
||||
## 주요 발견 사항
|
||||
|
||||
유출 소스 분석을 통해 드러난 Claude Code의 실제 아키텍처:
|
||||
|
||||
- **런타임**: Bun + React/Ink (터미널 UI 렌더링)
|
||||
- **에이전틱 루프**: `query.ts`가 구동하는 연속 루프 — 도구 호출 → 권한 확인 → 결과 수집 → 반복
|
||||
- **컨텍스트 조립**: `context.ts`의 `getSystemContext()` / `getUserContext()`가 git 상태, CLAUDE.md, 현재 날짜를 조립
|
||||
- **도구 시스템**: ~40개 내장 도구 (`BashTool`, `FileEditTool`, `AgentTool` 등)
|
||||
- **멀티에이전트**: `coordinator/`에서 팀 레벨 병렬 오케스트레이션
|
||||
- **스킬 시스템**: `.claude/skills/`의 마크다운 파일 기반 온디맨드 기능
|
||||
- **피처 플래그**: Bun 빌드타임 dead code elimination (`PROACTIVE`, `KAIROS`, `BRIDGE_MODE`, `DAEMON` 등)
|
||||
|
||||
---
|
||||
|
||||
## 구조
|
||||
|
||||
```
|
||||
/ (root) — 한국어 번역본 (21개)
|
||||
en/ — 영어 원본 (26개)
|
||||
concepts/
|
||||
configuration/
|
||||
guides/
|
||||
reference/
|
||||
commands/
|
||||
sdk/
|
||||
tools/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 출처
|
||||
|
||||
- 원본 문서: https://vineetagarwal-code-claude-code.mintlify.app
|
||||
- 관련 레포: https://github.com/instructkr/claw-code
|
||||
- 최초 발견: [@Fried_rice (Chaofan Shou)](https://x.com/shouc001) — npm 소스맵 경유 R2 버킷 접근
|
||||
|
||||
---
|
||||
|
||||
> ℹ️ 이 레포는 공개된 분석 문서의 번역 아카이브입니다. Anthropic의 독점 소스코드를 포함하지 않습니다.
|
||||
126
docs/claude-code-docs-main/en/concepts/how-it-works.md
Normal file
126
docs/claude-code-docs-main/en/concepts/how-it-works.md
Normal file
@@ -0,0 +1,126 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# How Claude Code works
|
||||
|
||||
> The agentic loop, context loading, tool execution model, and conversation lifecycle under the hood.
|
||||
|
||||
Claude Code is a terminal-based coding agent that runs a continuous agentic loop: it reads your request, reasons about what to do, calls tools, observes results, and repeats until the task is complete or it needs your input.
|
||||
|
||||
## The agentic loop
|
||||
|
||||
Every interaction follows the same fundamental cycle:
|
||||
|
||||
<Steps>
|
||||
<Step title="User sends a message">
|
||||
You type a message in the terminal (interactive mode) or pass one via `--print` / stdin (non-interactive / headless mode). The message is appended to the conversation history.
|
||||
</Step>
|
||||
|
||||
<Step title="Context is assembled">
|
||||
Before calling the model, Claude Code assembles a system prompt that includes: the current date, git status (branch, recent commits, working-tree status), any loaded CLAUDE.md memory files, and the list of available tools. This context is built once per conversation and memoized — see [`context.ts`](/concepts/memory-context).
|
||||
</Step>
|
||||
|
||||
<Step title="Claude reasons and selects tools">
|
||||
The assembled conversation is sent to the Anthropic API. The model reasons about the task and emits one or more `tool_use` blocks — each specifying a tool name and structured JSON input.
|
||||
</Step>
|
||||
|
||||
<Step title="Permission check">
|
||||
Before executing each tool call, Claude Code evaluates the current permission mode and any allow/deny rules. Depending on the mode, it either auto-approves, prompts you for confirmation, or blocks the call entirely. See [Permissions](/concepts/permissions).
|
||||
</Step>
|
||||
|
||||
<Step title="Tool executes and returns a result">
|
||||
Approved tool calls run. Results — file contents, command output, search hits — are appended to the conversation as `tool_result` blocks.
|
||||
</Step>
|
||||
|
||||
<Step title="Loop continues">
|
||||
The model receives the tool results and either calls more tools or produces a final text response. The loop repeats until no tool calls remain in a model turn.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
The loop runs entirely in your terminal process. There is no remote execution server — your files, shell, and credentials never leave your machine unless a tool explicitly sends them (e.g., `WebFetch`, `WebSearch`, or an MCP server).
|
||||
</Note>
|
||||
|
||||
## Context loading
|
||||
|
||||
At the start of each conversation, Claude Code builds two context blocks that are prepended to every API call:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="System context">
|
||||
Assembled by `getSystemContext()` in `context.ts`. Contains:
|
||||
|
||||
* **Git status** — current branch, default/main branch, git username, `git status --short` output (truncated to 2 000 characters if larger), and the last 5 commits from `git log --oneline`.
|
||||
* **Cache-breaking injection** — an optional ephemeral string used internally to bust the server-side prompt cache during debugging.
|
||||
|
||||
Git status is skipped when `CLAUDE_CODE_REMOTE=1` is set (remote/cloud mode) or when git instructions are disabled in settings.
|
||||
</Tab>
|
||||
|
||||
<Tab title="User context">
|
||||
Assembled by `getUserContext()` in `context.ts`. Contains:
|
||||
|
||||
* **CLAUDE.md memory** — all memory files discovered by the 4-level hierarchy (managed → user → project → local). Disabled by `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` or in bare mode without explicit `--add-dir`. See [Memory & context](/concepts/memory-context).
|
||||
* **Current date** — injected as `Today's date is YYYY-MM-DD` so the model always knows the date.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Both context blocks are **memoized** for the duration of the conversation using `lodash/memoize`. Calling `setSystemPromptInjection()` clears the caches immediately.
|
||||
|
||||
## Tool execution model
|
||||
|
||||
Claude Code does not execute tool calls autonomously by default. Each tool has a `checkPermissions` method, and the result determines what happens next:
|
||||
|
||||
| Permission result | What happens |
|
||||
| ----------------- | ------------------------------------------------------ |
|
||||
| `allow` | Tool runs immediately, result appended to conversation |
|
||||
| `ask` | Claude Code pauses and renders a confirmation dialog |
|
||||
| `deny` | Tool call is rejected; Claude receives an error result |
|
||||
|
||||
The permission behavior is controlled by the active [permission mode](/concepts/permissions) and any configured allow/deny rules. In `bypassPermissions` mode all checks are skipped. In `acceptEdits` mode file-edit tools are auto-approved but bash commands still prompt.
|
||||
|
||||
Tool calls that are safe and read-only (e.g., `Read`, `Glob`, `Grep`) are generally auto-approved across all modes.
|
||||
|
||||
## Interactive vs. non-interactive (task) mode
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Interactive (REPL) mode" icon="terminal">
|
||||
The default experience. Claude Code renders a live terminal UI using React/Ink. You see streaming output, tool-use confirmations, and spinner animations as the agent works. Messages persist across the session until you exit.
|
||||
</Card>
|
||||
|
||||
<Card title="Non-interactive / print mode" icon="file-code">
|
||||
Activated with `--print` or by piping stdin. No UI is rendered. Output is written to stdout so it can be captured by scripts or CI pipelines. Useful for one-shot automation tasks.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### Sub-agents (Task tool)
|
||||
|
||||
Claude can spawn sub-agents via the `Task` tool (`AgentTool`). Each sub-agent runs its own nested agentic loop with an isolated conversation and, optionally, a restricted tool set. Sub-agents can run locally (in-process) or on remote compute. Results are returned to the parent agent when the sub-agent completes. See [Tools](/concepts/tools) for details.
|
||||
|
||||
## Conversation storage and resumption
|
||||
|
||||
Conversations are stored as JSON transcript files on disk (in `~/.claude/` by default). Each conversation has a unique session ID. You can resume a previous conversation with `--resume <session-id>` or pick from the list with `--resume` alone.
|
||||
|
||||
When a conversation is resumed:
|
||||
|
||||
* The full message history is loaded from disk.
|
||||
* Memory files are re-discovered and may differ from when the conversation was first started.
|
||||
* The permission mode resets to the configured default unless it was persisted in the session.
|
||||
|
||||
<Tip>
|
||||
Long conversations are periodically **compacted** — the oldest messages are summarised to keep the context window manageable. The full raw transcript is always preserved on disk; compaction only affects what is sent to the API.
|
||||
</Tip>
|
||||
|
||||
## The query engine
|
||||
|
||||
Under the hood, each "turn" in the agentic loop is driven by a **query** — a call to `query.ts` that sends the current message list to the Anthropic API and streams back the response. The query engine handles:
|
||||
|
||||
* Streaming token output to the terminal in real time.
|
||||
* Dispatching `tool_use` blocks to the appropriate tool handlers.
|
||||
* Enforcing per-turn token and tool-call budgets.
|
||||
* Collecting tool results and appending them before the next model call.
|
||||
* Triggering compaction when the context window fills up.
|
||||
|
||||
Each tool has a `maxResultSizeChars` property. When a result exceeds this limit the content is saved to a temporary file and the model receives a preview with the file path, preventing context-window overflow from large outputs.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
206
docs/claude-code-docs-main/en/concepts/memory-context.md
Normal file
206
docs/claude-code-docs-main/en/concepts/memory-context.md
Normal file
@@ -0,0 +1,206 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Memory and context (CLAUDE.md)
|
||||
|
||||
> How Claude Code discovers, loads, and prioritises CLAUDE.md memory files to give Claude persistent, project-aware instructions.
|
||||
|
||||
Claude Code supports a layered memory system based on plain Markdown files. By writing instructions into `CLAUDE.md` files at different levels of your filesystem, you can customise Claude's behaviour globally, per-project, or per-user — and keep some instructions private while committing others to source control.
|
||||
|
||||
## The 4-level memory hierarchy
|
||||
|
||||
Memory files are loaded in the following order (from lowest to highest priority). Files loaded **later** take precedence because the model pays more attention to instructions that appear later in the context window.
|
||||
|
||||
<Steps>
|
||||
<Step title="Managed memory (lowest priority)">
|
||||
**Path:** `/etc/claude-code/CLAUDE.md` (or the platform equivalent configured by your organisation)
|
||||
|
||||
System-wide instructions set by an administrator or deployment tool. Applies to all users on the machine. Also supports a `rules/` subdirectory at `managed claude rules dir`. Cannot be overridden by user or project files when enforced via policy settings.
|
||||
</Step>
|
||||
|
||||
<Step title="User memory">
|
||||
**Path:** `~/.claude/CLAUDE.md` and `~/.claude/rules/*.md`
|
||||
|
||||
Your private global instructions that apply to every project. A good place for personal preferences like preferred code style, default language, or your git username. This file is never committed to any repository.
|
||||
</Step>
|
||||
|
||||
<Step title="Project memory">
|
||||
**Paths (checked in each ancestor directory, from root down to CWD):**
|
||||
|
||||
* `CLAUDE.md`
|
||||
* `.claude/CLAUDE.md`
|
||||
* `.claude/rules/*.md`
|
||||
|
||||
Instructions checked into the codebase and shared with the whole team. Ideal for project conventions, architecture notes, testing commands, and anything that every contributor should follow. Committed to source control.
|
||||
</Step>
|
||||
|
||||
<Step title="Local memory (highest priority)">
|
||||
**Path:** `CLAUDE.local.md` (checked in each ancestor directory)
|
||||
|
||||
Private project-specific overrides. This file should be added to `.gitignore`. Use it for personal workflow preferences that apply only to this project — local environment paths, personal shortcuts, or instructions you don't want to share.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Info>
|
||||
Files closer to the current working directory are loaded **later** and therefore have **higher priority**. A `CLAUDE.md` in your project root outweighs one in a parent directory.
|
||||
</Info>
|
||||
|
||||
## File discovery algorithm
|
||||
|
||||
When Claude Code starts, it walks the filesystem from the current working directory **up to the filesystem root**, collecting memory files at each level. The walk is performed by `getMemoryFiles()` in `utils/claudemd.ts`.
|
||||
|
||||
The discovery order ensures lower-priority files appear first in the assembled context:
|
||||
|
||||
1. Managed files are loaded first.
|
||||
2. User files are loaded next.
|
||||
3. Project and local files are loaded by iterating the path from the **root downward to CWD** — so ancestor directories come before child directories.
|
||||
|
||||
<Note>
|
||||
The full list of discovered files is memoised for the duration of the conversation. Use `/memory` to open the memory editor and force a reload, or restart the session to pick up changes made outside Claude Code.
|
||||
</Note>
|
||||
|
||||
## The `@include` directive
|
||||
|
||||
Memory files can reference other files using `@` notation. The referenced file is inserted into the context as a separate entry before the including file.
|
||||
|
||||
```markdown theme={null}
|
||||
# My project CLAUDE.md
|
||||
|
||||
@./docs/architecture.md
|
||||
@./docs/conventions/typescript.md
|
||||
|
||||
Always run `bun test` before committing.
|
||||
```
|
||||
|
||||
**Supported path forms:**
|
||||
|
||||
| Syntax | Resolves to |
|
||||
| ------------------ | ------------------------------------------------- |
|
||||
| `@filename` | Relative path from the including file's directory |
|
||||
| `@./relative/path` | Explicit relative path |
|
||||
| `@~/home/path` | Path relative to the user's home directory |
|
||||
| `@/absolute/path` | Absolute path |
|
||||
|
||||
**Rules:**
|
||||
|
||||
* `@include` paths inside fenced code blocks and inline code spans are **ignored** — only plain text nodes are processed.
|
||||
* Circular references are detected and skipped.
|
||||
* Non-existent files are silently ignored.
|
||||
* Maximum include depth is **5 levels**.
|
||||
* Only text-based file types are included (`.md`, `.ts`, `.py`, `.json`, etc.). Binary files such as images and PDFs are skipped.
|
||||
|
||||
<Warning>
|
||||
By default, `@include` paths that point outside the current project directory require explicit approval. Claude Code will display a warning and ask for confirmation the first time an external include is detected.
|
||||
</Warning>
|
||||
|
||||
## `.claude/rules/*.md` — granular rule files
|
||||
|
||||
Instead of putting everything in one large `CLAUDE.md`, you can split instructions across multiple Markdown files inside `.claude/rules/`:
|
||||
|
||||
```
|
||||
my-project/
|
||||
├── CLAUDE.md
|
||||
└── .claude/
|
||||
└── rules/
|
||||
├── testing.md
|
||||
├── typescript-style.md
|
||||
└── git-workflow.md
|
||||
```
|
||||
|
||||
All `.md` files in `.claude/rules/` (and subdirectories) are loaded automatically for the project and user memory levels. Rules files also support **path-scoped frontmatter**:
|
||||
|
||||
```markdown theme={null}
|
||||
---
|
||||
paths:
|
||||
- "src/api/**"
|
||||
- "src/services/**"
|
||||
---
|
||||
|
||||
Always use dependency injection. Never import concrete implementations directly.
|
||||
```
|
||||
|
||||
When `paths` is set, the rule file is only injected into context when Claude is working on a file that matches one of the glob patterns. This keeps context lean for large projects.
|
||||
|
||||
## Maximum file size
|
||||
|
||||
The recommended maximum for any single memory file is **40 000 characters** (`MAX_MEMORY_CHARACTER_COUNT`). Files that exceed this limit are flagged, and Claude may not read the full content. Keep memory files focused and concise.
|
||||
|
||||
## How memory affects Claude's behaviour
|
||||
|
||||
When memory files are loaded, they are assembled into a single context block prefixed with:
|
||||
|
||||
> *"Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."*
|
||||
|
||||
This means instructions in CLAUDE.md files take precedence over Claude's built-in defaults. Use this to enforce project conventions, restrict certain operations, or inject domain knowledge.
|
||||
|
||||
## When to use each level
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Use managed memory for…">
|
||||
Organisation-wide policies, security guardrails, or deployment-specific configuration that every user on a machine must follow. Managed by system administrators, not individual developers.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Use user memory (~/.claude/CLAUDE.md) for…">
|
||||
Personal preferences that apply across all projects: your preferred language for responses, commit message style, editor shortcuts, or personal aliases. This is private and never committed.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Use project memory (CLAUDE.md) for…">
|
||||
Project conventions shared with your team: how to run tests, build commands, architecture decisions, naming conventions, PR checklist items, or links to internal documentation. Commit this file.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Use local memory (CLAUDE.local.md) for…">
|
||||
Your personal overrides for a specific project: local environment paths, personal debugging notes, or workflow preferences that differ from the team defaults. Add this to `.gitignore`.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Example CLAUDE.md
|
||||
|
||||
```markdown theme={null}
|
||||
# My Project
|
||||
|
||||
## Commands
|
||||
|
||||
- Build: `bun run build`
|
||||
- Test: `bun test`
|
||||
- Lint: `bun run lint`
|
||||
- Type check: `bun run typecheck`
|
||||
|
||||
## Architecture
|
||||
|
||||
This is a monorepo. Core logic lives in `packages/core`. The CLI entrypoint is `src/index.ts`.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Use `zod/v4` for all schema validation.
|
||||
- Never use `any` — prefer `unknown` with a type guard.
|
||||
- All async functions must handle errors explicitly; never swallow exceptions.
|
||||
- Tests go in `__tests__/` next to the source file they test.
|
||||
|
||||
## Git
|
||||
|
||||
- Branch names: `feat/<ticket>-short-description`
|
||||
- Always run `bun test && bun run typecheck` before committing.
|
||||
- Do not include `console.log` statements in committed code.
|
||||
|
||||
@./docs/api-conventions.md
|
||||
```
|
||||
|
||||
## The `/memory` command
|
||||
|
||||
Run `/memory` inside the Claude Code REPL to open the memory file editor. It shows you which memory files are currently loaded, lets you edit them directly, and reloads the context when you save.
|
||||
|
||||
<Tip>
|
||||
You can ask Claude directly: *"Add a rule to CLAUDE.md that we always use 2-space indentation."* Claude will locate the appropriate memory file and write the instruction for you.
|
||||
</Tip>
|
||||
|
||||
## Disabling memory loading
|
||||
|
||||
| Method | Effect |
|
||||
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `CLAUDE_CODE_DISABLE_CLAUDE_MDS=1` | Disables all memory file loading entirely |
|
||||
| `--bare` flag | Skips auto-discovery of memory files from the CWD walk; only loads files from explicitly provided `--add-dir` directories |
|
||||
| `claudeMdExcludes` setting | Glob patterns of memory file paths to skip (e.g., to exclude a noisy ancestor `CLAUDE.md`) |
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
222
docs/claude-code-docs-main/en/concepts/permissions.md
Normal file
222
docs/claude-code-docs-main/en/concepts/permissions.md
Normal file
@@ -0,0 +1,222 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Permissions
|
||||
|
||||
> How Claude Code controls which operations Claude can perform automatically versus which require your explicit approval.
|
||||
|
||||
Claude Code runs tools on your local machine — executing shell commands, editing files, fetching URLs. The permission system gives you precise control over which operations Claude performs automatically and which require your explicit approval.
|
||||
|
||||
## What permissions control
|
||||
|
||||
Permissions apply to three categories of operations:
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="File operations" icon="file">
|
||||
Reading, editing, and writing files on your local filesystem via the `Read`, `Edit`, and `Write` tools.
|
||||
</Card>
|
||||
|
||||
<Card title="Bash commands" icon="terminal">
|
||||
Any shell command executed through the `Bash` tool, including installs, builds, git operations, and arbitrary scripts.
|
||||
</Card>
|
||||
|
||||
<Card title="MCP tool calls" icon="plug">
|
||||
Tools exposed by connected MCP servers, which may include database queries, API calls, or browser automation.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Permission modes
|
||||
|
||||
The permission mode determines the default behaviour when no specific allow/deny rule matches a tool call. Set the mode once and it applies for the entire session.
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="default — ask for potentially dangerous operations">
|
||||
The standard mode. Claude Code evaluates each tool call and prompts you for confirmation on operations that could have side effects: running shell commands, editing files, making network requests. Read-only operations (file reads, searches) are auto-approved.
|
||||
|
||||
This is the recommended mode for everyday use.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="acceptEdits — auto-approve file edits">
|
||||
File edit and write operations (`Edit`, `Write`) are automatically approved without prompting. Bash commands still require confirmation.
|
||||
|
||||
Useful when you trust Claude to make file changes freely but still want to review shell commands.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="plan — read-only planning mode">
|
||||
Claude can read files, search the codebase, and discuss changes, but cannot execute any write or bash operations. All mutating tool calls are blocked.
|
||||
|
||||
Use this mode when you want Claude to analyse a problem and produce a plan before you authorise any changes. The model can exit plan mode and request permission to proceed via the `ExitPlanMode` tool.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="bypassPermissions — skip all permission checks">
|
||||
All permission checks are disabled. Every tool call is executed immediately without any confirmation prompts.
|
||||
|
||||
<Warning>
|
||||
This mode is intended for automated, fully-scripted workflows where you have audited what Claude will do in advance. Never use `bypassPermissions` in an interactive session where Claude might take unexpected actions.
|
||||
</Warning>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="dontAsk — suppress prompts">
|
||||
Similar to `bypassPermissions` but uses a slightly different internal path. Tool calls that would normally prompt are auto-approved. Intended for scripted/non-interactive scenarios.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="auto — transcript-classifier mode (feature-gated)">
|
||||
An experimental mode that uses a secondary AI classifier to evaluate each proposed tool call against the conversation transcript. The classifier decides whether the operation is within the scope of what was requested, and either auto-approves or escalates to a human prompt.
|
||||
|
||||
This mode is only available when the `TRANSCRIPT_CLASSIFIER` feature flag is enabled.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Setting the permission mode
|
||||
|
||||
<Tabs>
|
||||
<Tab title="CLI flag">
|
||||
Pass `--permission-mode` when starting Claude Code:
|
||||
|
||||
```bash theme={null}
|
||||
claude --permission-mode acceptEdits
|
||||
claude --permission-mode bypassPermissions
|
||||
claude --permission-mode plan
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="/permissions command">
|
||||
Change the mode mid-session without restarting:
|
||||
|
||||
```
|
||||
/permissions
|
||||
```
|
||||
|
||||
An interactive menu lets you select the new mode. The change takes effect for the remainder of the session.
|
||||
</Tab>
|
||||
|
||||
<Tab title="settings.json">
|
||||
Set a persistent default in your user or project settings:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"defaultMode": "acceptEdits"
|
||||
}
|
||||
```
|
||||
|
||||
Valid values: `"default"`, `"acceptEdits"`, `"bypassPermissions"`, `"plan"`, `"dontAsk"`.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Permission rules (allow/deny lists)
|
||||
|
||||
Beyond the global mode, you can create fine-grained rules that always allow or always deny specific tool calls — regardless of the active mode.
|
||||
|
||||
Rules have three components:
|
||||
|
||||
| Field | Description |
|
||||
| ------------- | -------------------------------------------------------------------------------------- |
|
||||
| `toolName` | The name of the tool the rule applies to (e.g., `"Bash"`, `"Edit"`, `"mcp__myserver"`) |
|
||||
| `ruleContent` | An optional pattern that must match the tool's input (e.g., a command prefix for Bash) |
|
||||
| `behavior` | `"allow"`, `"deny"`, or `"ask"` |
|
||||
|
||||
Rules are evaluated **before** the permission mode. If a matching rule exists, its behavior is applied immediately.
|
||||
|
||||
### Rule sources and persistence
|
||||
|
||||
Rules can originate from different sources and are stored accordingly:
|
||||
|
||||
| Source | Where stored | Scope |
|
||||
| ----------------- | ----------------------------- | --------------------------------- |
|
||||
| `userSettings` | `~/.claude/settings.json` | All projects for the current user |
|
||||
| `projectSettings` | `.claude/settings.json` | All users of this project |
|
||||
| `localSettings` | `.claude/settings.local.json` | Current user, this project only |
|
||||
| `session` | In-memory | Current session only |
|
||||
| `cliArg` | CLI flags | Current invocation only |
|
||||
|
||||
### Example: always allow specific git commands
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git status)",
|
||||
"Bash(git diff *)",
|
||||
"Bash(git log *)",
|
||||
"Read(*)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(rm -rf *)",
|
||||
"Bash(sudo *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## How bash permissions work
|
||||
|
||||
Bash command permission checking deserves special attention because shell commands can be complex and ambiguous.
|
||||
|
||||
### Pattern matching
|
||||
|
||||
A `Bash` permission rule with a `ruleContent` string is matched against the command using wildcard pattern matching:
|
||||
|
||||
* `git status` — exact match only
|
||||
* `git *` — matches any `git` subcommand
|
||||
* `npm run *` — matches any `npm run` script
|
||||
* `*` — matches any bash command (use with extreme caution)
|
||||
|
||||
### Compound commands
|
||||
|
||||
When a bash command contains multiple sub-commands joined by `&&`, `||`, `;`, or pipes (`|`), each sub-command is checked independently. The overall permission is the most restrictive result: if any sub-command is denied, the entire compound command is blocked.
|
||||
|
||||
### Operator restrictions
|
||||
|
||||
Certain shell constructs are flagged for extra scrutiny regardless of rules:
|
||||
|
||||
* Output redirections (`>`, `>>`) to paths outside the project directory
|
||||
* Commands that change the current directory (`cd`) to outside the working tree
|
||||
* `sed -i` edit-in-place commands (handled specially to track file modifications)
|
||||
|
||||
### Safety checks
|
||||
|
||||
Regardless of the active permission mode, certain operations are always blocked or escalated:
|
||||
|
||||
* Commands targeting `.claude/` or `.git/` configuration directories
|
||||
* Modifications to shell config files (`.bashrc`, `.zshrc`, etc.)
|
||||
* Attempts to bypass path restrictions using cross-platform path tricks
|
||||
|
||||
<Note>
|
||||
In `auto` mode (feature-gated), safety checks marked `classifierApprovable: true` are sent to the transcript classifier rather than forcing a prompt. The classifier has visibility into the full conversation context and can decide whether the operation is appropriate.
|
||||
</Note>
|
||||
|
||||
## MCP tool permissions
|
||||
|
||||
MCP tools follow the same rule system as built-in tools. You can allow or deny an entire MCP server or individual tools within a server:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"deny": [
|
||||
"mcp__myserver"
|
||||
],
|
||||
"allow": [
|
||||
"mcp__myserver__read_database"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Using `mcp__servername` as the rule (without a specific tool name) blanket-denies all tools from that server — they are filtered out of the tool list before the model even sees them.
|
||||
|
||||
## Safety recommendations
|
||||
|
||||
<Warning>
|
||||
`bypassPermissions` and `dontAsk` modes remove all safeguards. Only use them in isolated environments (containers, CI sandboxes) where Claude's actions are constrained by the environment itself, not by permission prompts.
|
||||
</Warning>
|
||||
|
||||
* **Start with `default` mode** for any interactive session.
|
||||
* **Use `plan` mode** when exploring an unfamiliar codebase or designing a large change — review the plan before enabling writes.
|
||||
* **Use `acceptEdits`** for coding sessions where you trust Claude to edit files freely but want to review shell commands.
|
||||
* **Prefer granular allow rules** over broad mode escalation. Allowing `Bash(git *)` is safer than switching to `bypassPermissions`.
|
||||
* **Scope deny rules tightly.** A blanket `Bash(*)` deny prevents Claude from running any shell command, including safe read-only operations.
|
||||
* **Review project settings files** (`.claude/settings.json`) when cloning unfamiliar repositories — they may pre-configure permission rules.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
208
docs/claude-code-docs-main/en/concepts/tools.md
Normal file
208
docs/claude-code-docs-main/en/concepts/tools.md
Normal file
@@ -0,0 +1,208 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Tools
|
||||
|
||||
> Reference for every built-in tool Claude Code can use, including file operations, shell execution, web access, and sub-agent spawning.
|
||||
|
||||
Claude Code gives Claude a set of built-in tools it can call to interact with your machine. Each tool call is subject to the active [permission mode and rules](/concepts/permissions). Below is a reference for every tool available by default.
|
||||
|
||||
## File tools
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Read" icon="file-lines">
|
||||
**Read a file from the local filesystem.**
|
||||
|
||||
Reads up to 2 000 lines by default. Supports an `offset` and `limit` for targeted reads of large files. Returns content in `cat -n` format with line numbers.
|
||||
|
||||
Also supports reading images (PNG, JPG, etc.) as visual input, PDF files (up to 20 pages at a time), and Jupyter notebooks (`.ipynb`).
|
||||
|
||||
Read-only. Always auto-approved in `default` mode.
|
||||
</Card>
|
||||
|
||||
<Card title="Edit" icon="file-pen">
|
||||
**Perform exact string replacements in a file.**
|
||||
|
||||
Requires a prior `Read` call on the file in the same conversation. Replaces `old_string` with `new_string` — the match must be unique in the file. Use `replace_all: true` to rename across the entire file.
|
||||
|
||||
Fails if `old_string` appears more than once (unless `replace_all` is set). This precision prevents unintended edits.
|
||||
</Card>
|
||||
|
||||
<Card title="Write" icon="file-arrow-up">
|
||||
**Create a new file or completely overwrite an existing one.**
|
||||
|
||||
For existing files, a prior `Read` call is required in the same conversation. Prefer `Edit` for modifying existing files — `Write` sends the entire file content and is better suited for new files or full rewrites.
|
||||
</Card>
|
||||
|
||||
<Card title="Glob" icon="folder-magnifying-glass">
|
||||
**Find files by name pattern.**
|
||||
|
||||
Fast pattern matching that works on any codebase size. Returns matching file paths sorted by modification time (most recently modified first).
|
||||
|
||||
Supports patterns like `**/*.ts`, `src/**/*.test.js`, `**/CLAUDE.md`. For open-ended multi-step searches, use the `Task` tool instead.
|
||||
|
||||
Read-only. Always auto-approved.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Shell tool
|
||||
|
||||
<Card title="Bash" icon="terminal">
|
||||
**Execute a shell command in a persistent shell session.**
|
||||
|
||||
Runs the command in a shell that persists across tool calls within a conversation — environment variables and working-directory changes carry over between calls. Supports a `timeout` parameter (default and max values are configurable).
|
||||
|
||||
Key behaviours:
|
||||
|
||||
* **Compound commands** (`&&`, `||`, `;`, `|`) are parsed and each sub-command is permission-checked independently.
|
||||
* **Background execution** — pass `run_in_background: true` to run a long-running command without blocking. You are notified when it completes.
|
||||
* **Output limits** — stdout/stderr is truncated if it exceeds the per-tool result size budget; a preview and file path are returned instead.
|
||||
* **Search commands** (`find`, `grep`, `rg`) — for content search, prefer the dedicated `Grep` tool, which has optimised permissions and access.
|
||||
|
||||
Subject to permission prompts in `default` mode. Auto-approved in `acceptEdits` mode only for commands covered by an allow rule.
|
||||
</Card>
|
||||
|
||||
## Search tools
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Grep" icon="magnifying-glass">
|
||||
**Search file contents using regular expressions.**
|
||||
|
||||
Built on ripgrep. Supports full regex syntax (`log.*Error`, `function\s+\w+`), file-type filtering (`*.ts`, `**/*.py`), and three output modes:
|
||||
|
||||
* `files_with_matches` (default) — returns only file paths
|
||||
* `content` — returns matching lines with context
|
||||
* `count` — returns match counts per file
|
||||
|
||||
Multiline patterns are supported with `multiline: true`.
|
||||
|
||||
Read-only. Always auto-approved.
|
||||
</Card>
|
||||
|
||||
<Card title="LS" icon="list">
|
||||
**List directory contents.**
|
||||
|
||||
Returns files and subdirectories in a structured format. Useful for exploring project structure before reading or editing files.
|
||||
|
||||
Read-only. Always auto-approved.
|
||||
|
||||
<Note>In bare-minimum mode (`CLAUDE_CODE_SIMPLE=1`) only `Bash`, `Read`, and `Edit` are available — use `ls` via `Bash` instead.</Note>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Web tools
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="WebFetch" icon="globe">
|
||||
**Fetch a URL and extract information from it.**
|
||||
|
||||
Takes a URL and a prompt describing what to extract. Converts HTML to Markdown, then passes the content through a secondary model to produce a focused answer.
|
||||
|
||||
Features:
|
||||
|
||||
* HTTP URLs are automatically upgraded to HTTPS.
|
||||
* Includes a 15-minute self-cleaning cache — repeated fetches of the same URL are fast.
|
||||
* When a URL redirects to a different host, the tool returns the redirect URL for a follow-up request.
|
||||
* For GitHub URLs, prefer the `gh` CLI via `Bash` (e.g., `gh pr view`, `gh api`).
|
||||
|
||||
Read-only. Prompts for approval in `default` mode.
|
||||
</Card>
|
||||
|
||||
<Card title="WebSearch" icon="magnifying-glass-arrow-right">
|
||||
**Search the web and return results.**
|
||||
|
||||
Returns search results with titles, snippets, and URLs formatted as Markdown links. Useful for accessing information beyond the model's training cutoff.
|
||||
|
||||
After answering, Claude automatically appends a `Sources:` section listing all referenced URLs.
|
||||
|
||||
Domain filtering is supported to include or exclude specific sites. Currently only available in the US.
|
||||
|
||||
Prompts for approval in `default` mode.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Agent and task tools
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Task (Agent)" icon="robot">
|
||||
**Spawn a sub-agent to complete a task.**
|
||||
|
||||
Starts a nested agentic loop in a separate context. The sub-agent has its own conversation history, its own tool set (optionally restricted), and runs to completion before returning a result to the parent agent.
|
||||
|
||||
Sub-agents can run:
|
||||
|
||||
* **Locally** — in-process, sharing the parent's filesystem and shell
|
||||
* **Remotely** — on separate compute when remote agent eligibility criteria are met
|
||||
|
||||
Use `Task` for open-ended multi-step searches, parallel workstreams, or delegating distinct sub-problems to isolated agents.
|
||||
|
||||
The parent agent receives the sub-agent's final output as a tool result.
|
||||
</Card>
|
||||
|
||||
<Card title="TodoWrite" icon="list-check">
|
||||
**Create and manage a structured task list.**
|
||||
|
||||
Writes a list of todo items with statuses (`pending`, `in_progress`, `completed`) to a persistent panel in the terminal UI. Helps Claude track progress on complex multi-step tasks and shows you what it is working on.
|
||||
|
||||
Use proactively for tasks with 3 or more distinct steps. Not necessary for simple single-step requests.
|
||||
|
||||
Results are rendered in the todo panel, not the conversation transcript.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## MCP tools
|
||||
|
||||
MCP (Model Context Protocol) servers can expose additional tools to Claude Code. Connected tools appear in the tool list alongside built-in tools and follow the same permission system.
|
||||
|
||||
MCP tools are named with a `mcp__` prefix:
|
||||
|
||||
```
|
||||
mcp__<server-name>__<tool-name>
|
||||
```
|
||||
|
||||
For example, a tool named `query` on a server named `mydb` appears as `mcp__mydb__query`.
|
||||
|
||||
Common MCP tool categories include:
|
||||
|
||||
* Database query and management tools
|
||||
* Browser and web automation tools
|
||||
* Cloud provider APIs (AWS, GCP, Azure)
|
||||
* Issue tracker integrations (GitHub, Linear, Jira)
|
||||
* Internal company tools and APIs
|
||||
|
||||
<Info>
|
||||
MCP servers are configured in `~/.claude/mcp_servers.json` or `.claude/mcp_servers.json`. Tools from a connected server are automatically included in Claude's context once the server is running.
|
||||
</Info>
|
||||
|
||||
To deny all tools from a specific MCP server, add a deny rule for the server prefix:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"deny": ["mcp__untrusted-server"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Notebook tool
|
||||
|
||||
<Card title="NotebookEdit" icon="book">
|
||||
**Edit cells in a Jupyter notebook.**
|
||||
|
||||
Allows Claude to insert, replace, or delete cells in a `.ipynb` file with line-level precision. Read notebooks using the standard `Read` tool, which returns all cells and their outputs.
|
||||
</Card>
|
||||
|
||||
## Tool availability
|
||||
|
||||
Not all tools are available in every context. The active tool set is determined at startup and can be affected by:
|
||||
|
||||
* `CLAUDE_CODE_SIMPLE=1` — restricts to `Bash`, `Read`, and `Edit` only
|
||||
* Permission deny rules — tools blanket-denied by a rule are removed from the tool list before the model sees them
|
||||
* `isEnabled()` checks — each tool can self-disable based on environment conditions (e.g., `WebSearch` is gated by region)
|
||||
* MCP server connection state — MCP tools are only available when the server is running and connected
|
||||
|
||||
You can inspect the active tool set with the `/tools` command in the REPL.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
209
docs/claude-code-docs-main/en/configuration/claudemd.md
Normal file
209
docs/claude-code-docs-main/en/configuration/claudemd.md
Normal file
@@ -0,0 +1,209 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# CLAUDE.md
|
||||
|
||||
> How to write and organize CLAUDE.md files to give Claude persistent, project-specific instructions.
|
||||
|
||||
`CLAUDE.md` files let you encode project knowledge that Claude loads at the start of every session. Instead of explaining your project's conventions, build system, and architecture every time, you write them once and Claude reads them automatically.
|
||||
|
||||
## What belongs in CLAUDE.md
|
||||
|
||||
Write instructions that would cause mistakes if missing. Everything else is noise.
|
||||
|
||||
**Include:**
|
||||
|
||||
* Build, test, and lint commands (exact invocations, not just tool names)
|
||||
* Architecture decisions that affect how code should be written or organized
|
||||
* Coding conventions specific to your project (naming patterns, file structure rules)
|
||||
* Environment setup requirements (required env vars, expected services)
|
||||
* Common pitfalls or patterns Claude should know to avoid
|
||||
* Monorepo structure and which packages own which responsibilities
|
||||
|
||||
**Omit:**
|
||||
|
||||
* Things Claude already knows (standard TypeScript syntax, common library APIs)
|
||||
* Obvious reminders ("write clean code", "add comments")
|
||||
* Sensitive data — API keys, passwords, tokens, or secrets of any kind
|
||||
* Information that changes frequently and will become stale
|
||||
|
||||
<Tip>
|
||||
The test: would removing this line cause Claude to make a mistake on your codebase? If not, cut it.
|
||||
</Tip>
|
||||
|
||||
## File locations
|
||||
|
||||
Claude discovers memory files by traversing from your current directory up to the filesystem root. Files closer to your current directory have higher priority (they are loaded later, so the model pays more attention to them).
|
||||
|
||||
| File | Type | Purpose |
|
||||
| ----------------------------------- | ------- | ------------------------------------------------------------- |
|
||||
| `/etc/claude-code/CLAUDE.md` | Managed | System-wide instructions for all users, set by administrators |
|
||||
| `~/.claude/CLAUDE.md` | User | Your personal global instructions, applied to every project |
|
||||
| `~/.claude/rules/*.md` | User | Modular global rules, each file loaded separately |
|
||||
| `CLAUDE.md` (project root) | Project | Shared team instructions, checked into source control |
|
||||
| `.claude/CLAUDE.md` (project root) | Project | Alternative location for shared project instructions |
|
||||
| `.claude/rules/*.md` (project root) | Project | Modular project rules, organized by topic |
|
||||
| `CLAUDE.local.md` (project root) | Local | Your private project-specific instructions, not checked in |
|
||||
|
||||
<Note>
|
||||
`.claude/rules/` directories support subdirectories. All `.md` files found recursively are loaded as separate memory entries.
|
||||
</Note>
|
||||
|
||||
## Loading order and priority
|
||||
|
||||
Files are loaded in the following order. Because the model attends more to content that appears later in context, later files have higher effective priority.
|
||||
|
||||
<Steps>
|
||||
<Step title="Managed memory">
|
||||
`/etc/claude-code/CLAUDE.md` and `/etc/claude-code/rules/*.md` — global policy set by administrators. Always loaded; cannot be excluded by users.
|
||||
</Step>
|
||||
|
||||
<Step title="User memory">
|
||||
`~/.claude/CLAUDE.md` and `~/.claude/rules/*.md` — your personal global instructions for all projects.
|
||||
</Step>
|
||||
|
||||
<Step title="Project memory (root-to-CWD)">
|
||||
`CLAUDE.md`, `.claude/CLAUDE.md`, and `.claude/rules/*.md` files in each directory from the filesystem root down to your current directory. Files in directories closer to your CWD are loaded later (higher priority).
|
||||
</Step>
|
||||
|
||||
<Step title="Local memory">
|
||||
`CLAUDE.local.md` in each directory from root to CWD. Same traversal order. Gitignored by default.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## The @include directive
|
||||
|
||||
Memory files can include other files using `@` notation. Included files are processed recursively and inserted before the file that references them.
|
||||
|
||||
```markdown theme={null}
|
||||
# CLAUDE.md
|
||||
|
||||
@./docs/architecture.md
|
||||
@~/shared/style-guide.md
|
||||
@/etc/company-standards.md
|
||||
```
|
||||
|
||||
**Supported path formats:**
|
||||
|
||||
| Syntax | Resolves to |
|
||||
| ------------------ | ---------------------------------------------------------------- |
|
||||
| `@filename` | Relative to the current file's directory (same as `@./filename`) |
|
||||
| `@./relative/path` | Relative to the current file's directory |
|
||||
| `@~/path/in/home` | Path under your home directory |
|
||||
| `@/absolute/path` | Absolute filesystem path |
|
||||
|
||||
**Behavior:**
|
||||
|
||||
* Paths with a fragment (`#heading`) have the fragment stripped before resolving
|
||||
* Non-existent files are silently ignored
|
||||
* Circular references are detected and prevented
|
||||
* Includes nest up to 5 levels deep
|
||||
* Only text file formats are supported — binary files (images, PDFs) are skipped
|
||||
* `@include` inside code blocks is not processed
|
||||
|
||||
<Warning>
|
||||
External includes (files outside the project directory) require explicit approval the first time they are loaded. Claude will prompt you to confirm before fetching content from outside your project.
|
||||
</Warning>
|
||||
|
||||
## Frontmatter path targeting
|
||||
|
||||
Files in `.claude/rules/` can use YAML frontmatter to restrict which file paths they apply to. This lets you load rules conditionally based on the file Claude is working with.
|
||||
|
||||
```markdown theme={null}
|
||||
---
|
||||
paths:
|
||||
- "src/api/**"
|
||||
- "*.graphql"
|
||||
---
|
||||
|
||||
# API conventions
|
||||
|
||||
All API handlers must validate input using the shared `validate()` helper.
|
||||
GraphQL resolvers must not perform direct database queries — use the data layer.
|
||||
```
|
||||
|
||||
Rules without frontmatter apply unconditionally. Rules with `paths` frontmatter only apply when Claude is working in files matching the glob patterns.
|
||||
|
||||
## Example CLAUDE.md for a TypeScript project
|
||||
|
||||
```markdown theme={null}
|
||||
# Project: Payments API
|
||||
|
||||
## Build and test
|
||||
|
||||
- Build: `bun run build`
|
||||
- Tests: `bun test` (uses Bun's built-in test runner — do not use Jest)
|
||||
- Lint: `bun run lint` (biome, not eslint)
|
||||
- Type check: `bun run typecheck`
|
||||
|
||||
Always run `bun run typecheck` before considering a change complete.
|
||||
|
||||
## Architecture
|
||||
|
||||
- `src/handlers/` — HTTP handlers, one file per route group
|
||||
- `src/services/` — Business logic, no direct DB access
|
||||
- `src/db/` — Database layer (Drizzle ORM); all queries live here
|
||||
- `src/schemas/` — Zod schemas shared between handler validation and DB types
|
||||
|
||||
Handlers call services. Services call the DB layer. Never skip layers.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Use `z.object().strict()` for all input validation schemas
|
||||
- Errors propagate as `Result<T, AppError>` — never throw in service code
|
||||
- All monetary values are integers in cents
|
||||
- Timestamps are Unix seconds (number), not Date objects
|
||||
|
||||
## Environment
|
||||
|
||||
Required env vars: `DATABASE_URL`, `STRIPE_SECRET_KEY`, `JWT_SECRET`
|
||||
Local dev: copy `.env.example` to `.env.local` and fill in values
|
||||
|
||||
## Common mistakes to avoid
|
||||
|
||||
- Do not use `new Date()` directly — use `getCurrentTimestamp()` from `src/utils/time.ts`
|
||||
- Do not add `console.log` — use the `logger` from `src/utils/logger.ts`
|
||||
- Do not write raw SQL — use the Drizzle query builder
|
||||
```
|
||||
|
||||
## Generating CLAUDE.md with /init
|
||||
|
||||
Run `/init` in any Claude Code session to automatically generate a `CLAUDE.md` for your project. Claude analyzes your codebase and produces a file containing the commands and context most relevant to the project.
|
||||
|
||||
```
|
||||
/init
|
||||
```
|
||||
|
||||
The generated file is a starting point. Review it, trim anything that isn't genuinely useful, and add project-specific knowledge that Claude couldn't infer from the code.
|
||||
|
||||
## Editing CLAUDE.md with /memory
|
||||
|
||||
Run `/memory` to open the memory editor, which lists all currently loaded memory files and lets you edit them directly within the session.
|
||||
|
||||
```
|
||||
/memory
|
||||
```
|
||||
|
||||
Changes take effect immediately — Claude reloads the updated file and applies the new instructions to the current session.
|
||||
|
||||
## Excluding files
|
||||
|
||||
If you have CLAUDE.md files you want to prevent Claude from loading (for example, in vendored dependencies or generated code), add exclusion patterns to your settings:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"claudeMdExcludes": [
|
||||
"/absolute/path/to/vendor/CLAUDE.md",
|
||||
"**/generated/**",
|
||||
"**/third-party/.claude/rules/**"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Patterns are matched against absolute paths using picomatch. Only User, Project, and Local memory types can be excluded — Managed (administrator) files are always loaded.
|
||||
|
||||
See [Settings](/configuration/settings) for full documentation on the `claudeMdExcludes` option.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
@@ -0,0 +1,261 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Environment variables
|
||||
|
||||
> Environment variables that Claude Code reads to configure authentication, API access, behavior, and runtime options.
|
||||
|
||||
Claude Code reads environment variables at startup. These variables let you configure authentication, point to custom API endpoints, tune runtime behavior, and control which features are active — without modifying settings files.
|
||||
|
||||
## Authentication
|
||||
|
||||
<ParamField path="ANTHROPIC_API_KEY" type="string">
|
||||
API key for authenticating directly with the Anthropic API. When set, Claude Code uses this key instead of (or in addition to) OAuth credentials. Takes priority over OAuth when present in most contexts.
|
||||
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_API_KEY="sk-ant-..."
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="ANTHROPIC_AUTH_TOKEN" type="string">
|
||||
Alternative authentication token. Used in contexts where `ANTHROPIC_API_KEY` is not applicable.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="ANTHROPIC_BASE_URL" type="string">
|
||||
Override the Anthropic API base URL. Useful for pointing Claude Code at a proxy, staging environment, or compatible third-party endpoint.
|
||||
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_BASE_URL="https://my-proxy.example.com"
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_API_BASE_URL" type="string">
|
||||
Claude Code-specific API base URL override. Takes precedence over `ANTHROPIC_BASE_URL` when set.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="ANTHROPIC_BEDROCK_BASE_URL" type="string">
|
||||
Base URL for AWS Bedrock API access. Set this when routing Claude Code through a Bedrock endpoint.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="ANTHROPIC_VERTEX_PROJECT_ID" type="string">
|
||||
Google Cloud project ID for Vertex AI access. Required when using Claude Code through Google Cloud's Vertex AI platform.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_USE_BEDROCK" type="string">
|
||||
Set to `1` or `true` to use AWS Bedrock as the API provider.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_USE_FOUNDRY" type="string">
|
||||
Set to `1` or `true` to use Anthropic Foundry as the API provider.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_OAUTH_TOKEN" type="string">
|
||||
OAuth access token to use for authentication directly, bypassing the interactive login flow. Useful for automated environments.
|
||||
</ParamField>
|
||||
|
||||
## Configuration paths
|
||||
|
||||
<ParamField path="CLAUDE_CONFIG_DIR" type="string" default="~/.claude">
|
||||
Override the directory where Claude Code stores its configuration, settings, and transcripts. Defaults to `~/.claude` in your home directory.
|
||||
|
||||
```bash theme={null}
|
||||
export CLAUDE_CONFIG_DIR="/opt/claude-config"
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_MANAGED_SETTINGS_PATH" type="string">
|
||||
Override the path to the managed settings file. Useful in enterprise environments where the default platform path is not appropriate.
|
||||
</ParamField>
|
||||
|
||||
## Model selection
|
||||
|
||||
<ParamField path="ANTHROPIC_MODEL" type="string">
|
||||
Default model to use. Overridden by the `model` setting in settings files and by explicit `--model` flags.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_SUBAGENT_MODEL" type="string">
|
||||
Model to use for sub-agent tasks spawned by the main agent. When not set, sub-agents use the same model as the main session.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_AUTO_MODE_MODEL" type="string">
|
||||
Model to use when running in auto mode. Defaults to the main session model when not specified.
|
||||
</ParamField>
|
||||
|
||||
## Behavior toggles
|
||||
|
||||
<ParamField path="CLAUDE_CODE_REMOTE" type="string">
|
||||
Set to `1` or `true` to enable remote/container mode. In this mode, Claude Code adjusts its behavior for non-interactive environments — extended API timeouts (120s vs. 300s), suppressed interactive prompts, and adapted output formatting.
|
||||
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_REMOTE=1
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_SIMPLE" type="string">
|
||||
Set to `1` or `true` (or pass `--bare`) to run in bare mode. Bare mode skips hooks, LSP integration, plugin sync, skill directory walks, attribution, background prefetches, and all keychain/credential reads. Authentication must be provided via `ANTHROPIC_API_KEY` or `apiKeyHelper` in `--settings`. Useful for lightweight scripted use.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="DISABLE_AUTO_COMPACT" type="string">
|
||||
Set to `1` or `true` to disable automatic context compaction. When set, Claude Code will not compact the conversation context even when it approaches the model's context limit.
|
||||
|
||||
```bash theme={null}
|
||||
export DISABLE_AUTO_COMPACT=1
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_DISABLE_BACKGROUND_TASKS" type="boolean">
|
||||
Set to `1` or `true` to disable background task execution. When enabled, the `run_in_background` parameter is removed from Bash and PowerShell tools, and Claude cannot run shell commands as background processes.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_DISABLE_THINKING" type="string">
|
||||
Set to `1` or `true` to disable extended thinking for all API calls, regardless of model support.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_DISABLE_AUTO_MEMORY" type="string">
|
||||
Set to `1` or `true` to disable automatic memory. When disabled, Claude does not read from or write to the auto-memory directory. Set to `0` or `false` to explicitly enable it (useful when other conditions would disable it, such as bare mode).
|
||||
|
||||
Auto-memory is also disabled automatically in bare mode (`CLAUDE_CODE_SIMPLE`) and remote mode (`CLAUDE_CODE_REMOTE`) unless explicitly enabled.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_DISABLE_CLAUDE_MDS" type="string">
|
||||
Set to `1` or `true` to completely disable loading of all `CLAUDE.md` memory files. Claude will not read any CLAUDE.md, CLAUDE.local.md, or `.claude/rules/*.md` files.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" type="string">
|
||||
Set to `1` or `true` to suppress analytics, telemetry, and other non-essential network requests.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD" type="string">
|
||||
Set to `1` or `true` to load `CLAUDE.md` files from directories added via `--add-dir`. By default, additional directories do not have their CLAUDE.md files loaded.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR" type="string">
|
||||
Set to `1` or `true` to reset the working directory back to the original project root after each Bash command. Prevents one command from changing the CWD for subsequent commands.
|
||||
</ParamField>
|
||||
|
||||
## Resource limits
|
||||
|
||||
<ParamField path="CLAUDE_CODE_MAX_OUTPUT_TOKENS" type="number">
|
||||
Override the maximum number of output tokens per API response. When not set, Claude Code uses the model's default maximum. Useful for controlling costs in automated workflows.
|
||||
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_MAX_CONTEXT_TOKENS" type="number">
|
||||
Override the maximum context window size. When set, Claude Code uses this value instead of the model's reported context limit.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="BASH_MAX_OUTPUT_LENGTH" type="number">
|
||||
Maximum number of characters captured from Bash command output. Output exceeding this limit is truncated. Useful for preventing very large command outputs from consuming context.
|
||||
|
||||
```bash theme={null}
|
||||
export BASH_MAX_OUTPUT_LENGTH=50000
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="API_TIMEOUT_MS" type="number">
|
||||
Override the API request timeout in milliseconds. Defaults to 300,000ms (5 minutes) for standard mode and 120,000ms (2 minutes) in remote mode.
|
||||
|
||||
```bash theme={null}
|
||||
export API_TIMEOUT_MS=60000
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
## Telemetry and observability
|
||||
|
||||
<ParamField path="CLAUDE_CODE_ENABLE_TELEMETRY" type="string">
|
||||
Set to `1` or `true` to enable OpenTelemetry export of traces, metrics, and logs. Requires additional OTEL configuration (endpoint, headers, etc.) to be set via standard OpenTelemetry environment variables.
|
||||
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_ENABLE_TELEMETRY=1
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT="https://otel.example.com"
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CLAUDE_CODE_JSONL_TRANSCRIPT" type="string">
|
||||
Path to a file where Claude Code writes a JSONL transcript of the session. Each line is a JSON object representing a conversation event.
|
||||
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_JSONL_TRANSCRIPT="/tmp/session.jsonl"
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
## Node.js runtime
|
||||
|
||||
<ParamField path="NODE_OPTIONS" type="string">
|
||||
Standard Node.js options passed to the runtime. Claude Code reads this to detect flags like `--max-old-space-size` and adjusts its behavior accordingly. Claude Code itself sets this internally to configure heap size for large sessions.
|
||||
|
||||
```bash theme={null}
|
||||
export NODE_OPTIONS="--max-old-space-size=4096"
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Avoid setting `NODE_OPTIONS` to values that include code execution flags. Claude Code validates shell environments and treats some `NODE_OPTIONS` values as requiring confirmation before running Bash commands.
|
||||
</Warning>
|
||||
</ParamField>
|
||||
|
||||
## Host platform override
|
||||
|
||||
<ParamField path="CLAUDE_CODE_HOST_PLATFORM" type="string">
|
||||
Override the reported host platform for analytics. Accepts `"win32"`, `"darwin"`, or `"linux"`. Useful when Claude Code runs in a container (where `process.platform` reports the container OS) but the actual host platform differs.
|
||||
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_HOST_PLATFORM=darwin
|
||||
```
|
||||
</ParamField>
|
||||
|
||||
## Cloud provider region overrides
|
||||
|
||||
Claude Code supports per-model Vertex AI region overrides. Set the corresponding environment variable to route a specific model to a different region.
|
||||
|
||||
| Model prefix | Environment variable |
|
||||
| ------------------- | --------------------------------- |
|
||||
| `claude-haiku-4-5` | `VERTEX_REGION_CLAUDE_HAIKU_4_5` |
|
||||
| `claude-3-5-haiku` | `VERTEX_REGION_CLAUDE_3_5_HAIKU` |
|
||||
| `claude-3-5-sonnet` | `VERTEX_REGION_CLAUDE_3_5_SONNET` |
|
||||
| `claude-3-7-sonnet` | `VERTEX_REGION_CLAUDE_3_7_SONNET` |
|
||||
| `claude-opus-4-1` | `VERTEX_REGION_CLAUDE_4_1_OPUS` |
|
||||
| `claude-opus-4` | `VERTEX_REGION_CLAUDE_4_0_OPUS` |
|
||||
| `claude-sonnet-4-6` | `VERTEX_REGION_CLAUDE_4_6_SONNET` |
|
||||
| `claude-sonnet-4-5` | `VERTEX_REGION_CLAUDE_4_5_SONNET` |
|
||||
| `claude-sonnet-4` | `VERTEX_REGION_CLAUDE_4_0_SONNET` |
|
||||
|
||||
```bash theme={null}
|
||||
# Route Opus 4 to a specific Vertex region
|
||||
export VERTEX_REGION_CLAUDE_4_0_OPUS="us-central1"
|
||||
```
|
||||
|
||||
The default Vertex region is controlled by `CLOUD_ML_REGION` (defaults to `us-east5`).
|
||||
|
||||
## AWS credentials
|
||||
|
||||
For Bedrock access, Claude Code respects standard AWS credential environment variables:
|
||||
|
||||
<ParamField path="AWS_REGION" type="string">
|
||||
AWS region for Bedrock API calls. Falls back to `AWS_DEFAULT_REGION`, then defaults to `us-east-1`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="AWS_DEFAULT_REGION" type="string">
|
||||
Fallback AWS region when `AWS_REGION` is not set.
|
||||
</ParamField>
|
||||
|
||||
## Setting environment variables for all sessions
|
||||
|
||||
You can set environment variables that apply to every Claude Code session using the `env` field in your settings file, rather than setting them in your shell profile:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"env": {
|
||||
"DISABLE_AUTO_COMPACT": "1",
|
||||
"BASH_MAX_OUTPUT_LENGTH": "30000"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See [Settings](/configuration/settings) for documentation on the `env` field.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
439
docs/claude-code-docs-main/en/configuration/settings.md
Normal file
439
docs/claude-code-docs-main/en/configuration/settings.md
Normal file
@@ -0,0 +1,439 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Settings
|
||||
|
||||
> Configure Claude Code behavior through JSON settings files at the user, project, and managed levels.
|
||||
|
||||
Claude Code reads settings from JSON files at multiple scopes. Settings merge from lowest to highest priority, so more specific scopes override broader ones.
|
||||
|
||||
## Settings files
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Global (user)">
|
||||
**Location:** `~/.claude/settings.json`
|
||||
|
||||
Applies to every Claude Code session you run, across all projects. This is where you set personal preferences like your preferred model, theme, and cleanup policy.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"model": "claude-opus-4-5",
|
||||
"cleanupPeriodDays": 30,
|
||||
"permissions": {
|
||||
"defaultMode": "acceptEdits"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Project (shared)">
|
||||
**Location:** `.claude/settings.json` in your project root
|
||||
|
||||
Checked into source control. Use this for settings that should apply to everyone working on the project — permission rules, hook configurations, MCP servers, and environment variables.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"allow": ["Bash(npm run *)", "Bash(git *)"],
|
||||
"deny": ["Bash(rm -rf *)"]
|
||||
},
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [{ "type": "command", "command": "npm run lint" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Local (personal project)">
|
||||
**Location:** `.claude/settings.local.json` in your project root
|
||||
|
||||
Not checked into source control (automatically added to `.gitignore`). Use this for personal overrides within a specific project — your own permission preferences or environment variables that shouldn't be shared.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"defaultMode": "bypassPermissions"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Managed (enterprise)">
|
||||
**Location:** Platform-specific system path
|
||||
|
||||
Set by administrators via MDM, registry (Windows), plist (macOS), or a managed settings file. Managed settings take highest priority and cannot be overridden by users or projects.
|
||||
|
||||
See [Managed settings](#managed-settings-enterprise) below for details.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Opening settings
|
||||
|
||||
Run `/config` inside any Claude Code session to open the settings UI. This opens the **Config** tab of the settings panel, where you can browse and edit the currently active settings for each scope.
|
||||
|
||||
You can also edit the JSON files directly. Claude Code reloads settings automatically when it detects file changes.
|
||||
|
||||
## Settings precedence
|
||||
|
||||
Settings merge from lowest to highest priority. Later sources override earlier ones for scalar values; arrays are concatenated and deduplicated.
|
||||
|
||||
```
|
||||
Plugin defaults → User settings → Project settings → Local settings → Managed (policy) settings
|
||||
```
|
||||
|
||||
<Note>
|
||||
Managed (policy) settings always take final precedence. An administrator setting `permissions.defaultMode` to `"default"` cannot be overridden by users or project files.
|
||||
</Note>
|
||||
|
||||
## Settings reference
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="model">
|
||||
**Type:** `string` | **Scope:** Any
|
||||
|
||||
Override the default model used by Claude Code. Accepts any model ID supported by your configured provider.
|
||||
|
||||
```json theme={null}
|
||||
{ "model": "claude-opus-4-5" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="permissions">
|
||||
**Type:** `object` | **Scope:** Any
|
||||
|
||||
Controls which tools Claude can use and in what mode. See [Permissions](/concepts/permissions) for full documentation on rule syntax.
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------------------------ | ----------- | ----------------------------------------------------------------------------------------- |
|
||||
| `allow` | `string[]` | Rules for operations Claude may perform without asking |
|
||||
| `deny` | `string[]` | Rules for operations Claude is always blocked from |
|
||||
| `ask` | `string[]` | Rules for operations that always prompt for confirmation |
|
||||
| `defaultMode` | `string` | Default permission mode: `"default"`, `"acceptEdits"`, `"plan"`, or `"bypassPermissions"` |
|
||||
| `disableBypassPermissionsMode` | `"disable"` | Prevent users from entering bypass permissions mode |
|
||||
| `additionalDirectories` | `string[]` | Extra directories Claude may access |
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"defaultMode": "acceptEdits",
|
||||
"allow": ["Bash(npm run *)", "Bash(git log *)"],
|
||||
"deny": ["Bash(curl *)"]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="hooks">
|
||||
**Type:** `object` | **Scope:** Any
|
||||
|
||||
Run custom shell commands before or after tool executions. See [Hooks](/guides/hooks) for full documentation.
|
||||
|
||||
Supported hook events: `PreToolUse`, `PostToolUse`, `Notification`, `UserPromptSubmit`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStop`, `PreCompact`, `PostCompact`.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [{ "type": "command", "command": "prettier --write $CLAUDE_FILE_PATHS" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="cleanupPeriodDays">
|
||||
**Type:** `integer` (non-negative) | **Default:** `30` | **Scope:** Any
|
||||
|
||||
Number of days to retain chat transcripts. Setting to `0` disables session persistence entirely — no transcripts are written and existing ones are deleted at startup.
|
||||
|
||||
```json theme={null}
|
||||
{ "cleanupPeriodDays": 7 }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="env">
|
||||
**Type:** `object` | **Scope:** Any
|
||||
|
||||
Environment variables to inject into every Claude Code session. Values are coerced to strings.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"env": {
|
||||
"NODE_ENV": "development",
|
||||
"MY_API_URL": "https://api.example.com"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="availableModels">
|
||||
**Type:** `string[]` | **Scope:** Managed
|
||||
|
||||
Enterprise allowlist of models users can select. Accepts family aliases (`"opus"` allows any Opus version), version prefixes, or full model IDs. If `undefined`, all models are available. If an empty array, only the default model is available.
|
||||
|
||||
```json theme={null}
|
||||
{ "availableModels": ["claude-opus-4-5", "claude-sonnet-4"] }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="allowedMcpServers / deniedMcpServers">
|
||||
**Type:** `object[]` | **Scope:** Any
|
||||
|
||||
Enterprise allowlist and denylist for MCP servers. Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`. The denylist takes precedence — if a server matches both lists, it is blocked.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
{ "serverName": "my-db-server" },
|
||||
{ "serverUrl": "https://mcp.example.com/*" }
|
||||
],
|
||||
"deniedMcpServers": [
|
||||
{ "serverCommand": ["npx", "malicious-server"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="worktree">
|
||||
**Type:** `object` | **Scope:** Any
|
||||
|
||||
Configuration for `--worktree` flag behavior.
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------------------- | ---------- | --------------------------------------------------------------------------------- |
|
||||
| `symlinkDirectories` | `string[]` | Directories to symlink from the main repo into worktrees (e.g., `"node_modules"`) |
|
||||
| `sparsePaths` | `string[]` | Paths to check out in sparse mode, for faster worktrees in large monorepos |
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"worktree": {
|
||||
"symlinkDirectories": ["node_modules", ".cache"],
|
||||
"sparsePaths": ["src/", "packages/my-service/"]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="attribution">
|
||||
**Type:** `object` | **Scope:** Any
|
||||
|
||||
Customize the attribution text Claude appends to commits and pull request descriptions.
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | -------- | -------------------------------------------------------------------------------- |
|
||||
| `commit` | `string` | Attribution text (including any git trailers). Empty string removes attribution. |
|
||||
| `pr` | `string` | Attribution text for PR descriptions. Empty string removes attribution. |
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "Co-Authored-By: Claude <noreply@anthropic.com>",
|
||||
"pr": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="language">
|
||||
**Type:** `string` | **Scope:** Any
|
||||
|
||||
Preferred language for Claude responses and voice dictation. Accepts plain language names.
|
||||
|
||||
```json theme={null}
|
||||
{ "language": "japanese" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="sandbox">
|
||||
**Type:** `object` | **Scope:** Any
|
||||
|
||||
Sandbox configuration for isolating Claude's tool executions. Contact your administrator for sandbox setup details.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="alwaysThinkingEnabled">
|
||||
**Type:** `boolean` | **Default:** `true` | **Scope:** Any
|
||||
|
||||
When `false`, extended thinking is disabled. When absent or `true`, thinking is enabled automatically for models that support it.
|
||||
|
||||
```json theme={null}
|
||||
{ "alwaysThinkingEnabled": false }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="effortLevel">
|
||||
**Type:** `"low" | "medium" | "high"` | **Scope:** Any
|
||||
|
||||
Persisted effort level for models that support adjustable thinking budgets.
|
||||
|
||||
```json theme={null}
|
||||
{ "effortLevel": "high" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="autoMemoryEnabled">
|
||||
**Type:** `boolean` | **Scope:** User, local
|
||||
|
||||
Enable or disable auto-memory for this project. When `false`, Claude does not read from or write to the auto-memory directory.
|
||||
|
||||
```json theme={null}
|
||||
{ "autoMemoryEnabled": false }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="autoMemoryDirectory">
|
||||
**Type:** `string` | **Scope:** User, local
|
||||
|
||||
Custom path for auto-memory storage. Supports `~/` for home directory expansion. Ignored if set in project settings (`.claude/settings.json`) for security reasons. Defaults to `~/.claude/projects/<sanitized-cwd>/memory/`.
|
||||
|
||||
```json theme={null}
|
||||
{ "autoMemoryDirectory": "~/my-memory-store" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="claudeMdExcludes">
|
||||
**Type:** `string[]` | **Scope:** Any
|
||||
|
||||
Glob patterns or absolute paths of `CLAUDE.md` files to exclude from loading. Patterns are matched against absolute paths using picomatch. Only applies to User, Project, and Local memory types — Managed files cannot be excluded.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"claudeMdExcludes": [
|
||||
"/home/user/monorepo/vendor/CLAUDE.md",
|
||||
"**/third-party/.claude/rules/**"
|
||||
]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="disableAllHooks">
|
||||
**Type:** `boolean` | **Scope:** Any
|
||||
|
||||
Set to `true` to disable all hook and `statusLine` execution.
|
||||
|
||||
```json theme={null}
|
||||
{ "disableAllHooks": true }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="respectGitignore">
|
||||
**Type:** `boolean` | **Default:** `true` | **Scope:** Any
|
||||
|
||||
Whether the file picker respects `.gitignore` files. `.ignore` files are always respected regardless of this setting.
|
||||
|
||||
```json theme={null}
|
||||
{ "respectGitignore": false }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="defaultShell">
|
||||
**Type:** `"bash" | "powershell"` | **Default:** `"bash"` | **Scope:** Any
|
||||
|
||||
Default shell for `!` commands in the input box.
|
||||
|
||||
```json theme={null}
|
||||
{ "defaultShell": "powershell" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="forceLoginMethod">
|
||||
**Type:** `"claudeai" | "console"` | **Scope:** Managed
|
||||
|
||||
Force a specific login method. Use `"claudeai"` for Claude Pro/Max accounts, or `"console"` for Anthropic Console billing.
|
||||
|
||||
```json theme={null}
|
||||
{ "forceLoginMethod": "console" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="apiKeyHelper">
|
||||
**Type:** `string` | **Scope:** User, managed
|
||||
|
||||
Path to a script that outputs authentication values. The script is called to retrieve credentials dynamically instead of reading a static API key.
|
||||
|
||||
```json theme={null}
|
||||
{ "apiKeyHelper": "/usr/local/bin/get-claude-key.sh" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="syntaxHighlightingDisabled">
|
||||
**Type:** `boolean` | **Scope:** Any
|
||||
|
||||
Disable syntax highlighting in diffs.
|
||||
|
||||
```json theme={null}
|
||||
{ "syntaxHighlightingDisabled": true }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="prefersReducedMotion">
|
||||
**Type:** `boolean` | **Scope:** Any
|
||||
|
||||
Reduce or disable animations (spinner shimmer, flash effects, etc.) for accessibility.
|
||||
|
||||
```json theme={null}
|
||||
{ "prefersReducedMotion": true }
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Managed settings (enterprise)
|
||||
|
||||
Administrators can push settings to all users via platform-native mechanisms. Managed settings take precedence over all user and project settings.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="macOS">
|
||||
Deploy a plist file to `/Library/Preferences/` or via MDM (Jamf, Kandji, etc.) targeting `com.anthropic.claudecode`.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Windows">
|
||||
Write settings to the `HKLM\Software\Anthropic\Claude Code` registry key (machine-wide) or `HKCU\Software\Anthropic\Claude Code` (per-user, lower priority than HKLM).
|
||||
</Tab>
|
||||
|
||||
<Tab title="File-based">
|
||||
Place a `managed-settings.json` file at the platform-specific managed path. For drop-in configuration fragments, create a `managed-settings.d/` directory alongside it. Files in that directory are sorted alphabetically and merged on top of the base file — later filenames win.
|
||||
|
||||
```
|
||||
managed-settings.json # base settings (lowest precedence)
|
||||
managed-settings.d/
|
||||
10-security.json # merged first
|
||||
20-model-policy.json # merged second (wins over 10-)
|
||||
```
|
||||
|
||||
This convention matches systemd/sudoers drop-ins: independent teams can ship policy fragments without coordinating edits to a single file.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
The following managed-only settings lock down user customization surfaces:
|
||||
|
||||
| Setting | Description |
|
||||
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `allowManagedHooksOnly` | When `true`, only hooks defined in managed settings run. User, project, and local hooks are ignored. |
|
||||
| `allowManagedPermissionRulesOnly` | When `true`, only permission rules from managed settings are respected. |
|
||||
| `allowManagedMcpServersOnly` | When `true`, the `allowedMcpServers` allowlist is only read from managed settings. |
|
||||
| `strictPluginOnlyCustomization` | Lock specific customization surfaces (`"skills"`, `"agents"`, `"hooks"`, `"mcp"`) to plugin-only sources. Pass `true` to lock all four, or an array of surface names. |
|
||||
|
||||
<Warning>
|
||||
`allowManagedPermissionRulesOnly` ignores permission rules from user settings, project settings, local settings, and CLI arguments. Make sure your managed rules are comprehensive before enabling this.
|
||||
</Warning>
|
||||
|
||||
## JSON schema
|
||||
|
||||
Add `$schema` to your settings file for editor autocompletion and validation:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"$schema": "https://schemas.anthropic.com/claude-code/settings.json"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
206
docs/claude-code-docs-main/en/guides/authentication.md
Normal file
206
docs/claude-code-docs-main/en/guides/authentication.md
Normal file
@@ -0,0 +1,206 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Authentication
|
||||
|
||||
> Configure how Claude Code authenticates with the Anthropic API, AWS Bedrock, or GCP Vertex AI.
|
||||
|
||||
Claude Code supports several authentication methods. The method you use depends on how you're accessing the API — directly through Anthropic, through a cloud provider, or via an API key helper script.
|
||||
|
||||
## Claude.ai OAuth (default)
|
||||
|
||||
When you run `claude` for the first time without any API key configured, Claude Code starts an OAuth flow using your claude.ai account.
|
||||
|
||||
<Steps>
|
||||
<Step title="Run Claude Code">
|
||||
Open your terminal and run:
|
||||
|
||||
```bash theme={null}
|
||||
claude
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Follow the login prompt">
|
||||
Claude Code will display a URL and prompt you to open it in your browser. Visit the URL, sign in to your claude.ai account, and grant authorization.
|
||||
</Step>
|
||||
|
||||
<Step title="Return to the terminal">
|
||||
After authorizing in the browser, Claude Code receives the OAuth token automatically and stores it in secure storage (macOS Keychain on macOS, or a credentials file on other platforms). You're now authenticated.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
OAuth tokens are refreshed automatically before they expire. You do not need to re-authenticate unless you explicitly log out or revoke access.
|
||||
</Note>
|
||||
|
||||
## API key
|
||||
|
||||
You can authenticate using an Anthropic API key instead of OAuth.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Environment variable">
|
||||
Set the `ANTHROPIC_API_KEY` environment variable in your shell profile or before running `claude`:
|
||||
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
|
||||
When this variable is set, Claude Code uses it directly and does not prompt for OAuth.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Settings file">
|
||||
Add the `apiKeyHelper` setting to `~/.claude/settings.json` to run a shell command that outputs your API key. Claude Code executes this command and caches the result for 5 minutes (configurable with `CLAUDE_CODE_API_KEY_HELPER_TTL_MS`):
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"apiKeyHelper": "cat ~/.anthropic/api-key"
|
||||
}
|
||||
```
|
||||
|
||||
The `apiKeyHelper` command must print only the API key to stdout and exit with code 0. Any stderr output is treated as an error.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Warning>
|
||||
When `ANTHROPIC_API_KEY` is set or `apiKeyHelper` is configured, the OAuth flow is disabled. Claude Code will not attempt to use your claude.ai account.
|
||||
</Warning>
|
||||
|
||||
## AWS Bedrock
|
||||
|
||||
To use Claude through Amazon Bedrock, set the `CLAUDE_CODE_USE_BEDROCK` environment variable and configure your AWS credentials.
|
||||
|
||||
<Steps>
|
||||
<Step title="Enable Bedrock mode">
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_USE_BEDROCK=1
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure AWS credentials">
|
||||
Claude Code uses the standard AWS credential chain. Any of the following work:
|
||||
|
||||
* AWS credentials file (`~/.aws/credentials`)
|
||||
* Environment variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`
|
||||
* IAM roles (EC2 instance profiles, ECS task roles, etc.)
|
||||
* AWS SSO (`aws sso login`)
|
||||
</Step>
|
||||
|
||||
<Step title="Set your region and model (optional)">
|
||||
```bash theme={null}
|
||||
export AWS_REGION=us-east-1
|
||||
```
|
||||
|
||||
Claude Code selects a Claude model automatically based on your Bedrock configuration.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Automated AWS credential refresh
|
||||
|
||||
If your AWS session expires mid-session (for example, with short-lived SSO tokens), configure `awsAuthRefresh` in your settings to run a command that refreshes credentials automatically:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"awsAuthRefresh": "aws sso login --profile my-profile"
|
||||
}
|
||||
```
|
||||
|
||||
Claude Code runs this command when it detects that credentials have expired and streams the output so you can complete any browser-based flows.
|
||||
|
||||
To export credentials from a command (for example, `aws sts assume-role`), use `awsCredentialExport`:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"awsCredentialExport": "aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyRole --role-session-name claude-code --query Credentials --output json"
|
||||
}
|
||||
```
|
||||
|
||||
The command must output valid AWS STS JSON (with `Credentials.AccessKeyId`, `Credentials.SecretAccessKey`, and `Credentials.SessionToken`).
|
||||
|
||||
## GCP Vertex AI
|
||||
|
||||
To use Claude through Google Cloud Vertex AI, set the `CLAUDE_CODE_USE_VERTEX` environment variable and configure Application Default Credentials.
|
||||
|
||||
<Steps>
|
||||
<Step title="Enable Vertex mode">
|
||||
```bash theme={null}
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Configure GCP credentials">
|
||||
Claude Code uses Google Application Default Credentials (ADC). Any of the following work:
|
||||
|
||||
* `gcloud auth application-default login` (for interactive use)
|
||||
* Service account key file via `GOOGLE_APPLICATION_CREDENTIALS`
|
||||
* Workload Identity (for GKE)
|
||||
</Step>
|
||||
|
||||
<Step title="Set your GCP project and region (optional)">
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_VERTEX_PROJECT_ID=my-gcp-project
|
||||
export CLOUD_ML_REGION=us-central1
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### Automated GCP credential refresh
|
||||
|
||||
Similar to Bedrock, configure `gcpAuthRefresh` to run a command when credentials expire:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"gcpAuthRefresh": "gcloud auth application-default login"
|
||||
}
|
||||
```
|
||||
|
||||
Claude Code checks whether your current GCP credentials are valid before running the command, so it only refreshes when necessary.
|
||||
|
||||
## Switching accounts
|
||||
|
||||
### Log in to a different account
|
||||
|
||||
Run the `/login` command from within Claude Code to start a new OAuth flow. This replaces any stored tokens with those for the new account:
|
||||
|
||||
```
|
||||
/login
|
||||
```
|
||||
|
||||
### Log out
|
||||
|
||||
Run the `/logout` command to remove stored credentials:
|
||||
|
||||
```
|
||||
/logout
|
||||
```
|
||||
|
||||
After logging out, Claude Code will prompt you to authenticate on the next run.
|
||||
|
||||
## Token expiry and refresh
|
||||
|
||||
OAuth tokens expire automatically. Claude Code handles refresh silently:
|
||||
|
||||
* Before each API request, Claude Code checks whether the access token is expired.
|
||||
* If it is, Claude Code acquires a lock and refreshes using the stored refresh token.
|
||||
* Multiple concurrent Claude Code instances coordinate via a lock file to avoid redundant refreshes.
|
||||
* If a `401` response arrives from the API (for example, due to a clock skew between when the token was issued and the local check), Claude Code forces an immediate refresh without waiting for the local expiry time.
|
||||
|
||||
You do not need to do anything when tokens refresh. If refresh fails (for example, because you revoked access in the claude.ai settings), Claude Code will prompt you to run `/login`.
|
||||
|
||||
## Authentication priority
|
||||
|
||||
When multiple authentication sources are configured, Claude Code resolves them in this order:
|
||||
|
||||
1. `ANTHROPIC_AUTH_TOKEN` environment variable
|
||||
2. `CLAUDE_CODE_OAUTH_TOKEN` environment variable
|
||||
3. OAuth token from file descriptor (for managed deployments)
|
||||
4. `apiKeyHelper` from settings
|
||||
5. Stored claude.ai OAuth tokens (keychain or credentials file)
|
||||
6. `ANTHROPIC_API_KEY` environment variable
|
||||
|
||||
<Tip>
|
||||
For CI and non-interactive environments, use `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN`. These are checked before any interactive flows.
|
||||
</Tip>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
436
docs/claude-code-docs-main/en/guides/hooks.md
Normal file
436
docs/claude-code-docs-main/en/guides/hooks.md
Normal file
@@ -0,0 +1,436 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Hooks
|
||||
|
||||
> Run shell commands, HTTP requests, or prompts automatically when Claude uses tools or reaches session milestones.
|
||||
|
||||
Hooks let you attach automation to Claude Code's tool lifecycle. When Claude reads a file, runs a bash command, or finishes a response, your configured hooks execute automatically. Use hooks to enforce code style, run tests, log tool usage, or gate what Claude is allowed to do.
|
||||
|
||||
## How hooks work
|
||||
|
||||
A hook is a command (shell script, HTTP endpoint, or LLM prompt) bound to a specific **event**. When that event fires, Claude Code runs every matching hook and uses the exit code and output to decide what to do next.
|
||||
|
||||
The input to each hook is a JSON object on stdin describing what happened — for example, the tool name and its arguments for `PreToolUse`, or the tool name and response for `PostToolUse`.
|
||||
|
||||
### Exit code semantics
|
||||
|
||||
Exit code behavior varies by event. The full table is documented in each event's description, but the general pattern is:
|
||||
|
||||
| Exit code | Meaning |
|
||||
| --------- | ------------------------------------------------------------------------------------ |
|
||||
| `0` | Success. Stdout may be shown to Claude (event-specific). |
|
||||
| `2` | Block or inject. Show stderr to Claude and (for `PreToolUse`) prevent the tool call. |
|
||||
| Other | Show stderr to the user only; execution continues. |
|
||||
|
||||
## Hook events
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="PreToolUse — before tool execution">
|
||||
Fires before every tool call. The hook input contains the tool name and arguments as JSON.
|
||||
|
||||
* Exit `0`: tool proceeds normally (stdout not shown)
|
||||
* Exit `2`: block the tool call and show stderr to Claude so it can respond
|
||||
* Other: show stderr to the user but allow the tool call to continue
|
||||
|
||||
Use matchers to restrict this hook to specific tools (e.g., `Bash`, `Write`).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="PostToolUse — after tool execution">
|
||||
Fires after every successful tool call. The hook input contains `inputs` (the tool arguments) and `response` (the tool result).
|
||||
|
||||
* Exit `0`: stdout is shown in transcript mode (Ctrl+O)
|
||||
* Exit `2`: show stderr to Claude immediately (Claude can respond)
|
||||
* Other: show stderr to the user only
|
||||
|
||||
Use this to run formatters, linters, or test runners after file edits.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="PostToolUseFailure — after a tool error">
|
||||
Fires when a tool call results in an error. Input contains `tool_name`, `tool_input`, `error`, `error_type`, `is_interrupt`, and `is_timeout`.
|
||||
|
||||
Same exit code semantics as `PostToolUse`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Stop — before Claude concludes a response">
|
||||
Fires just before Claude's turn ends. No matcher support.
|
||||
|
||||
* Exit `0`: no output shown
|
||||
* Exit `2`: show stderr to Claude and continue the conversation (Claude gets another turn)
|
||||
* Other: show stderr to the user only
|
||||
|
||||
Use this to check that all required tasks are complete before Claude finishes.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SubagentStop — before a subagent concludes">
|
||||
Like `Stop`, but fires when a subagent (launched via the Agent tool) finishes. Input includes `agent_id`, `agent_type`, and `agent_transcript_path`. Same exit code semantics as `Stop`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SubagentStart — when a subagent starts">
|
||||
Fires when a new subagent is launched. Input includes `agent_id` and `agent_type`.
|
||||
|
||||
* Exit `0`: stdout is shown to the subagent's initial prompt
|
||||
* Other: show stderr to user only
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SessionStart — when a session begins">
|
||||
Fires at the start of every session (startup, resume, `/clear`, or `/compact`). Input contains the start `source`.
|
||||
|
||||
* Exit `0`: stdout is shown to Claude
|
||||
* Other: show stderr to user only (blocking errors are ignored)
|
||||
|
||||
Match on `source` values: `startup`, `resume`, `clear`, `compact`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="UserPromptSubmit — when you submit a prompt">
|
||||
Fires when you press Enter to submit a prompt. Input contains your original prompt text.
|
||||
|
||||
* Exit `0`: stdout is shown to Claude (can prepend context)
|
||||
* Exit `2`: block the prompt and show stderr to the user only
|
||||
* Other: show stderr to user only
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="PreCompact — before conversation compaction">
|
||||
Fires before Claude Code compacts the conversation (auto or manual). Input contains compaction details.
|
||||
|
||||
* Exit `0`: stdout is appended as custom compact instructions
|
||||
* Exit `2`: block the compaction
|
||||
* Other: show stderr to user but proceed
|
||||
|
||||
Match on `trigger`: `manual` or `auto`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="PostCompact — after conversation compaction">
|
||||
Fires after compaction completes. Input contains compaction details and the summary.
|
||||
|
||||
* Exit `0`: stdout shown to user
|
||||
* Other: show stderr to user only
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Setup — repository setup and maintenance">
|
||||
Fires with `trigger: init` (project onboarding) or `trigger: maintenance` (periodic). Use this for one-time setup scripts or periodic maintenance tasks.
|
||||
|
||||
* Exit `0`: stdout shown to Claude
|
||||
* Other: show stderr to user only
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="PermissionRequest — when a permission dialog appears">
|
||||
Fires when Claude Code would show a permission prompt. Output JSON with `hookSpecificOutput.decision` to approve or deny programmatically.
|
||||
|
||||
* Exit `0`: use the hook's decision if provided
|
||||
* Other: show stderr to user only
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="PermissionDenied — after auto mode denies a tool call">
|
||||
Fires when the auto mode classifier denies a tool call. Return `{"hookSpecificOutput":{"hookEventName":"PermissionDenied","retry":true}}` to tell Claude it may retry.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Notification — when notifications are sent">
|
||||
Fires for permission prompts, idle prompts, auth success, and elicitation events. Match on `notification_type`.
|
||||
|
||||
* Exit `0`: no output shown
|
||||
* Other: show stderr to user only
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="CwdChanged — after working directory changes">
|
||||
Fires after the working directory changes. Input includes `old_cwd` and `new_cwd`. The `CLAUDE_ENV_FILE` environment variable is set — write bash export lines to that file to apply new env vars to subsequent Bash tool calls.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="FileChanged — when a watched file changes">
|
||||
Fires when a file matching the hook's `matcher` pattern changes on disk. The matcher specifies filename patterns to watch (e.g., `.envrc|.env`). Like `CwdChanged`, supports `CLAUDE_ENV_FILE` for injecting environment.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="SessionEnd — when a session ends">
|
||||
Fires when the session is ending (clear, logout, or exit). Match on `reason`: `clear`, `logout`, `prompt_input_exit`, or `other`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ConfigChange — when config files change">
|
||||
Fires when settings files change during a session. Match on `source`: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`.
|
||||
|
||||
* Exit `0`: allow the change
|
||||
* Exit `2`: block the change from being applied
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="InstructionsLoaded — when a CLAUDE.md file is loaded">
|
||||
Fires when any instruction file (CLAUDE.md or rule) is loaded. Observability-only — does not support blocking.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="WorktreeCreate / WorktreeRemove — worktree lifecycle">
|
||||
`WorktreeCreate` fires when an isolated worktree needs to be created. Stdout should contain the absolute path of the created worktree. `WorktreeRemove` fires when a worktree should be cleaned up.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Task events — task lifecycle">
|
||||
`TaskCreated` and `TaskCompleted` fire when tasks are created or marked complete. Input includes `task_id`, `task_subject`, `task_description`, `teammate_name`, and `team_name`. Exit `2` prevents the state change.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="TeammateIdle — when a teammate is about to go idle">
|
||||
Fires before a teammate goes idle. Exit `2` to send stderr to the teammate and prevent it from going idle.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Elicitation / ElicitationResult — MCP elicitation">
|
||||
`Elicitation` fires when an MCP server requests user input. Return JSON in `hookSpecificOutput` to provide the response programmatically. `ElicitationResult` fires after the user responds, allowing you to modify or block the response.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Configuring hooks
|
||||
|
||||
Run `/hooks` inside Claude Code to open the hooks configuration menu. The menu shows all configured hooks grouped by event and lets you add, edit, or remove them interactively.
|
||||
|
||||
Hooks are stored in the `hooks` field of settings files:
|
||||
|
||||
* `~/.claude/settings.json` — user-level hooks (apply everywhere)
|
||||
* `.claude/settings.json` — project-level hooks (apply for this project)
|
||||
* `.claude/settings.local.json` — local hooks (not checked into VCS)
|
||||
|
||||
### Configuration format
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "prettier --write $CLAUDE_FILE_PATH"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo 'Session complete' >> ~/.claude-log.txt"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each event maps to an array of **matcher objects**. Each matcher object has:
|
||||
|
||||
* `matcher` (optional) — a string pattern to match against the event's matchable field (for example, `tool_name` for `PreToolUse`/`PostToolUse`, `trigger` for `Setup`, `source` for `SessionStart`)
|
||||
* `hooks` — an array of hook commands to run when the matcher matches
|
||||
|
||||
### Hook command types
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Shell command">
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "command",
|
||||
"command": "npm test",
|
||||
"timeout": 60,
|
||||
"shell": "bash"
|
||||
}
|
||||
```
|
||||
|
||||
Fields:
|
||||
|
||||
* `command` — the shell command to run (required)
|
||||
* `timeout` — timeout in seconds (default: no limit)
|
||||
* `shell` — `"bash"` (default) or `"powershell"`
|
||||
* `statusMessage` — custom spinner text shown while the hook runs
|
||||
* `async` — run in background without blocking (`true`/`false`)
|
||||
* `once` — run once and remove the hook automatically
|
||||
* `if` — permission rule syntax to conditionally skip the hook (e.g., `"Bash(git *)"`)
|
||||
</Tab>
|
||||
|
||||
<Tab title="HTTP request">
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "http",
|
||||
"url": "https://hooks.example.com/claude-event",
|
||||
"headers": {
|
||||
"Authorization": "Bearer $MY_TOKEN"
|
||||
},
|
||||
"allowedEnvVars": ["MY_TOKEN"],
|
||||
"timeout": 10
|
||||
}
|
||||
```
|
||||
|
||||
Claude Code POSTs the hook input JSON to the URL. Headers support `$VAR` expansion for variables listed in `allowedEnvVars`.
|
||||
</Tab>
|
||||
|
||||
<Tab title="LLM prompt">
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "prompt",
|
||||
"prompt": "Review this tool call for security issues: $ARGUMENTS. If you find a problem, output an explanation and exit with code 2.",
|
||||
"model": "claude-haiku-4-5",
|
||||
"timeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
The hook prompt is evaluated by an LLM. `$ARGUMENTS` is replaced with the hook input JSON. The LLM's response becomes the hook output.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Agent hook">
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "agent",
|
||||
"prompt": "Verify that the unit tests in $ARGUMENTS passed and all assertions are meaningful.",
|
||||
"timeout": 60
|
||||
}
|
||||
```
|
||||
|
||||
Like a prompt hook, but runs as a full agent with tool access. Useful for verification tasks that require reading files or running commands.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Matcher patterns
|
||||
|
||||
For events that support matching (like `PreToolUse`, `PostToolUse`, `SessionStart`), the `matcher` field filters which inputs trigger the hook.
|
||||
|
||||
* An empty or absent `matcher` matches all inputs for that event.
|
||||
* For tool events, the `matcher` is matched against the `tool_name` (e.g., `"Bash"`, `"Write"`, `"Read"`).
|
||||
* For `SessionStart`, it matches `source` (e.g., `"startup"`, `"compact"`).
|
||||
* For `Setup`, it matches `trigger` (e.g., `"init"`, `"maintenance"`).
|
||||
* For `FileChanged`, the `matcher` specifies filename patterns to watch (e.g., `".envrc|.env"`).
|
||||
|
||||
## Example hooks
|
||||
|
||||
### Auto-format files after editing
|
||||
|
||||
Run Prettier after every file write:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Run tests after bash commands
|
||||
|
||||
Run the test suite after any bash command that touches source files:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "if git diff --name-only HEAD | grep -q '\\.ts$'; then npm test; fi",
|
||||
"timeout": 120,
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Log all tool usage
|
||||
|
||||
Append every tool call to a log file:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) $CLAUDE_TOOL_NAME\" >> ~/.claude-tool-log.txt",
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Block dangerous commands
|
||||
|
||||
Use `PreToolUse` to prevent `rm -rf` from being called:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -q 'rm -rf'; then echo 'Blocked: rm -rf is not allowed' >&2; exit 2; fi"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Inject environment on directory change
|
||||
|
||||
Use `CwdChanged` with `CLAUDE_ENV_FILE` to load `.envrc` when you change directories:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"CwdChanged": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "if [ -f .envrc ]; then grep '^export ' .envrc >> \"$CLAUDE_ENV_FILE\"; fi"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Hook timeout configuration
|
||||
|
||||
Set a per-hook timeout in seconds using the `timeout` field:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "command",
|
||||
"command": "npm run integration-tests",
|
||||
"timeout": 300
|
||||
}
|
||||
```
|
||||
|
||||
Hooks without a `timeout` run until they exit naturally. For long-running hooks that should not block Claude, use `"async": true`.
|
||||
|
||||
## Hooks vs. skills
|
||||
|
||||
| Feature | Hooks | Skills |
|
||||
| ------------- | ----------------------------------- | -------------------------------------------------- |
|
||||
| When they run | Automatically on tool events | When Claude or you explicitly invoke `/skill-name` |
|
||||
| Purpose | Side effects, gating, observability | On-demand workflows and capabilities |
|
||||
| Configuration | Settings JSON | Markdown files in `.claude/skills/` |
|
||||
| Input | JSON from the tool event | The arguments you pass to the skill |
|
||||
|
||||
Use hooks for things that should happen automatically every time (formatting, logging, enforcement). Use skills for repeatable workflows that you want to trigger on demand.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
282
docs/claude-code-docs-main/en/guides/mcp-servers.md
Normal file
282
docs/claude-code-docs-main/en/guides/mcp-servers.md
Normal file
@@ -0,0 +1,282 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# MCP servers
|
||||
|
||||
> Extend Claude Code with Model Context Protocol servers to connect databases, APIs, and custom tools.
|
||||
|
||||
Model Context Protocol (MCP) is an open standard that lets Claude Code connect to external data sources and services. When you add an MCP server, Claude gains access to new tools — for example, querying a database, reading Jira tickets, or interacting with a Slack workspace.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Extend Claude's capabilities" icon="plug">
|
||||
Connect Claude to any service that exposes an MCP server: databases, APIs, file systems, and more.
|
||||
</Card>
|
||||
|
||||
<Card title="Project or user scope" icon="folder">
|
||||
Save server configs per-project in `.mcp.json` or globally in your user settings.
|
||||
</Card>
|
||||
|
||||
<Card title="Enable and disable at runtime" icon="toggle-right">
|
||||
Turn individual servers on and off with `/mcp enable` and `/mcp disable` without editing config files.
|
||||
</Card>
|
||||
|
||||
<Card title="Permission gating" icon="shield">
|
||||
Claude Code prompts before calling any MCP tool, giving you control over what actions are taken.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Adding a server
|
||||
|
||||
The primary way to add an MCP server is via the `claude mcp add` CLI command, or by editing a config file directly.
|
||||
|
||||
### Via the CLI
|
||||
|
||||
Run `/mcp` to open the MCP management panel where you can enable, disable, and reconnect servers.
|
||||
|
||||
To add a server from the command line using the `claude` CLI:
|
||||
|
||||
```bash theme={null}
|
||||
claude mcp add <name> -- <command> [args...]
|
||||
```
|
||||
|
||||
For example, to add the official filesystem MCP server:
|
||||
|
||||
```bash theme={null}
|
||||
claude mcp add filesystem -- npx -y @modelcontextprotocol/server-filesystem /tmp
|
||||
```
|
||||
|
||||
Specify the scope with `--scope`:
|
||||
|
||||
```bash theme={null}
|
||||
# Save to .mcp.json in the current directory (shared with your team)
|
||||
claude mcp add --scope project filesystem -- npx -y @modelcontextprotocol/server-filesystem /tmp
|
||||
|
||||
# Save to your user config (available in all projects)
|
||||
claude mcp add --scope user my-db -- npx -y @my-org/mcp-server-postgres
|
||||
```
|
||||
|
||||
### Via the `--mcp-config` flag
|
||||
|
||||
Pass a JSON config file when starting Claude Code:
|
||||
|
||||
```bash theme={null}
|
||||
claude --mcp-config ./my-mcp-config.json
|
||||
```
|
||||
|
||||
This is useful for CI environments or when you want a self-contained configuration that is not persisted to any settings file.
|
||||
|
||||
## Config file format
|
||||
|
||||
MCP server configurations use JSON with a top-level `mcpServers` key. Each server entry has a name and a configuration object.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Stdio (local process)">
|
||||
Most MCP servers run as a local subprocess communicating over stdin/stdout:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"],
|
||||
"env": {
|
||||
"NODE_ENV": "production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Fields:
|
||||
|
||||
* `command` — the executable to run (required)
|
||||
* `args` — array of command-line arguments
|
||||
* `env` — environment variables to pass to the process
|
||||
</Tab>
|
||||
|
||||
<Tab title="HTTP (remote server)">
|
||||
For servers hosted as HTTP endpoints:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-api": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.example.com/v1",
|
||||
"headers": {
|
||||
"Authorization": "Bearer $MY_API_TOKEN"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Fields:
|
||||
|
||||
* `type` — set to `"http"`
|
||||
* `url` — the server URL (required)
|
||||
* `headers` — HTTP headers; values support `$VAR` environment variable expansion
|
||||
</Tab>
|
||||
|
||||
<Tab title="SSE (server-sent events)">
|
||||
For servers using the SSE transport:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"mcpServers": {
|
||||
"events-server": {
|
||||
"type": "sse",
|
||||
"url": "https://mcp.example.com/sse"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Server names may only contain letters, numbers, hyphens, and underscores.
|
||||
|
||||
### Environment variable expansion
|
||||
|
||||
Values in `command`, `args`, `url`, and `headers` support `$VAR` and `${VAR}` syntax. Variables are expanded at startup from the shell environment. If a referenced variable is missing, Claude Code logs a warning but still attempts to connect.
|
||||
|
||||
## Configuration scopes
|
||||
|
||||
MCP configs are stored in different places depending on scope:
|
||||
|
||||
| Scope | Location | Use case |
|
||||
| --------- | ------------------------------------------------------------------------ | ---------------------------------------------------- |
|
||||
| `project` | `.mcp.json` in the current directory (and parent directories up to root) | Team-shared server configs |
|
||||
| `user` | `~/.claude.json` (global config) | Personal servers available everywhere |
|
||||
| `local` | `.claude/settings.local.json` in the current project | Per-project personal overrides, not committed to VCS |
|
||||
|
||||
When the same server name appears in multiple scopes, `local` takes precedence over `project`, which takes precedence over `user`.
|
||||
|
||||
## Managing servers
|
||||
|
||||
### Enable and disable
|
||||
|
||||
```
|
||||
/mcp enable <server-name>
|
||||
/mcp disable <server-name>
|
||||
/mcp enable all
|
||||
/mcp disable all
|
||||
```
|
||||
|
||||
Disabled servers remain in the config but are not connected at startup. This is useful for servers you want to keep configured but not always running.
|
||||
|
||||
### Reconnect a server
|
||||
|
||||
If a server fails to connect or you need to force a reconnection:
|
||||
|
||||
```
|
||||
/mcp reconnect <server-name>
|
||||
```
|
||||
|
||||
### View server status
|
||||
|
||||
Run `/mcp` to see a list of all configured servers and their current connection status:
|
||||
|
||||
* **connected** — server is running and ready to use
|
||||
* **pending** — server is starting up
|
||||
* **failed** — server could not connect (check the error message)
|
||||
* **needs-auth** — server requires OAuth authorization
|
||||
* **disabled** — server is configured but turned off
|
||||
|
||||
## Approving MCP tool calls
|
||||
|
||||
Claude Code displays a permission prompt before calling any MCP tool. The prompt shows the tool name and its input arguments, so you can review what Claude is about to do before it executes.
|
||||
|
||||
You can:
|
||||
|
||||
* **Allow once** — approve this specific call
|
||||
* **Allow always** — approve all calls to this tool in this session
|
||||
* **Deny** — block the call; Claude receives an error and can try a different approach
|
||||
|
||||
<Note>
|
||||
In auto mode (`--allowedTools`), MCP tools can be pre-approved by including their full name (formatted as `mcp__<server-name>__<tool-name>`) in the allowed tools list.
|
||||
</Note>
|
||||
|
||||
## Example: filesystem server
|
||||
|
||||
The official filesystem MCP server gives Claude the ability to read and write files in directories you specify.
|
||||
|
||||
<Steps>
|
||||
<Step title="Add the server">
|
||||
```bash theme={null}
|
||||
claude mcp add --scope project filesystem -- npx -y @modelcontextprotocol/server-filesystem /home/user/projects
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Verify the connection">
|
||||
Run `/mcp` and confirm `filesystem` shows as **connected**.
|
||||
</Step>
|
||||
|
||||
<Step title="Use it">
|
||||
Claude can now read and write files in `/home/user/projects` using the `mcp__filesystem__read_file` and `mcp__filesystem__write_file` tools.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Example: database server
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"mcpServers": {
|
||||
"postgres": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-postgres"],
|
||||
"env": {
|
||||
"POSTGRES_CONNECTION_STRING": "$DATABASE_URL"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Set `DATABASE_URL` in your environment before starting Claude Code, and the MCP server will receive it automatically.
|
||||
|
||||
## Official MCP registry
|
||||
|
||||
Anthropic and the community maintain an MCP server registry at [modelcontextprotocol.io](https://modelcontextprotocol.io). Browse available servers for databases, productivity tools, cloud providers, and more.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Server shows as 'failed'">
|
||||
* Check that the command exists and is executable: `which npx`
|
||||
* Run the command manually in your terminal to see if it starts without errors
|
||||
* Check that required environment variables (like API keys) are set
|
||||
* Run `claude --debug` to see detailed connection logs
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="MCP tools not appearing">
|
||||
A server that is connected but unauthenticated will not expose any tools. Look for a **needs-auth** status in `/mcp` and follow the OAuth flow to authorize.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Environment variable not expanded">
|
||||
Claude Code expands variables from the process environment at startup. If a variable is not set in your shell profile, it will not be available. Verify with `echo $YOUR_VAR` in the same terminal before starting `claude`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Windows: npx fails to start">
|
||||
On Windows, `npx` requires a `cmd /c` wrapper:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-server": {
|
||||
"command": "cmd",
|
||||
"args": ["/c", "npx", "-y", "@my-org/mcp-server"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Server works locally but not in CI">
|
||||
Use the `--mcp-config` flag to pass a config file explicitly, and ensure all referenced environment variables are set in the CI environment. For stdio servers, make sure the command (e.g., `npx`, `node`) is available in the CI PATH.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
195
docs/claude-code-docs-main/en/guides/multi-agent.md
Normal file
195
docs/claude-code-docs-main/en/guides/multi-agent.md
Normal file
@@ -0,0 +1,195 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Multi-agent workflows
|
||||
|
||||
> Parallelize complex tasks by having Claude spawn and coordinate sub-agents.
|
||||
|
||||
Claude Code can spawn sub-agents — separate Claude instances that run independently to complete tasks in parallel. This lets you tackle large, multi-step work by dividing it across specialized agents that run concurrently, rather than doing everything sequentially in a single conversation.
|
||||
|
||||
## How sub-agents work
|
||||
|
||||
When Claude uses the `Agent` tool, it launches a new Claude instance with its own context, system prompt, and tool permissions. The parent Claude waits for the agent to complete (or continues other work if the agent is running in the background), then receives the agent's result as a single message.
|
||||
|
||||
Each agent:
|
||||
|
||||
* Starts with a fresh context window (unless it's a fork)
|
||||
* Gets a specialized system prompt based on its agent type
|
||||
* Has its own tool permissions (configurable per agent type)
|
||||
* Can itself spawn further sub-agents, though nesting is limited
|
||||
|
||||
## The Agent tool
|
||||
|
||||
Claude uses the `Agent` tool to spawn sub-agents. As a user, you don't call this tool directly — Claude decides when to use it. You can see when Claude spawns agents: they appear in the terminal with their own progress indicators.
|
||||
|
||||
The tool accepts:
|
||||
|
||||
* `description` — a 3-5 word summary of what the agent will do (shown in the UI)
|
||||
* `prompt` — the full task description for the agent
|
||||
* `subagent_type` — which specialized agent type to use (optional; defaults to general-purpose)
|
||||
* `run_in_background` — whether to run asynchronously so Claude can continue other work
|
||||
* `isolation` — `"worktree"` to give the agent an isolated git worktree
|
||||
|
||||
## When Claude uses sub-agents
|
||||
|
||||
Claude spawns agents when a task benefits from parallelism or specialization:
|
||||
|
||||
* **Independent parallel tasks** — writing tests while also updating documentation
|
||||
* **Specialized work** — using a code-reviewer agent for a security audit
|
||||
* **Long-running tasks** — background research while Claude works on something else
|
||||
* **Isolated exploration** — forking itself to explore a solution without polluting the main context
|
||||
|
||||
Claude does not spawn agents for simple tasks, small file reads, or anything it can complete directly in a few tool calls.
|
||||
|
||||
## Requesting multi-agent workflows
|
||||
|
||||
You can ask Claude to use multiple agents explicitly:
|
||||
|
||||
```
|
||||
Run the linter and the test suite in parallel.
|
||||
```
|
||||
|
||||
```
|
||||
Use separate agents to research how three competing libraries handle this problem,
|
||||
then summarize the findings.
|
||||
```
|
||||
|
||||
```
|
||||
Have an agent review the security implications of this code change while you
|
||||
continue implementing the feature.
|
||||
```
|
||||
|
||||
<Tip>
|
||||
When asking Claude to run agents "in parallel", it will send a single message with multiple Agent tool calls, launching all of them simultaneously. Be explicit about what should run in parallel vs. what must be sequential.
|
||||
</Tip>
|
||||
|
||||
## Foreground vs. background agents
|
||||
|
||||
By default, agents run in the **foreground**: Claude waits for each agent to complete before proceeding. Use foreground agents when Claude needs the results to continue its work.
|
||||
|
||||
Background agents run asynchronously. Claude launches them and continues with other work. You receive a notification when the agent completes.
|
||||
|
||||
```
|
||||
Run the integration tests in the background while you implement the next feature.
|
||||
```
|
||||
|
||||
Claude will not poll or check on background agents — it continues working and receives the result as a notification when the agent finishes.
|
||||
|
||||
<Note>
|
||||
Background agents are shown in a tasks panel alongside the main conversation. You can see their progress and cancel them if needed.
|
||||
</Note>
|
||||
|
||||
## Coordinator mode
|
||||
|
||||
In coordinator mode, Claude acts as an orchestrator that delegates all implementation work to sub-agents and focuses on planning, routing, and synthesis. This is useful for very large tasks where you want Claude to manage the overall workflow while sub-agents do the hands-on work.
|
||||
|
||||
Coordinator mode is primarily used in multi-agent team setups. In a standard single-user session, Claude decides for itself when to delegate.
|
||||
|
||||
## Agent memory and context isolation
|
||||
|
||||
Each sub-agent starts with a **clean context window**. The parent Claude provides the full task description and any relevant background in the agent's prompt — the agent does not automatically inherit the parent's conversation history.
|
||||
|
||||
This means:
|
||||
|
||||
* Agents are independent; they cannot read the parent's conversation
|
||||
* The parent must provide sufficient context in the prompt for the agent to succeed
|
||||
* Results from agents are returned as a single response, not streamed turn by turn
|
||||
|
||||
### Persistent agent memory
|
||||
|
||||
Some agent types have persistent memory across invocations. Memory is stored in markdown files:
|
||||
|
||||
* **User scope**: `~/.claude/agent-memory/<agent-type>/MEMORY.md` — shared across all projects
|
||||
* **Project scope**: `.claude/agent-memory/<agent-type>/MEMORY.md` — shared with your team
|
||||
* **Local scope**: `.claude/agent-memory-local/<agent-type>/MEMORY.md` — local only, not committed
|
||||
|
||||
When an agent type has memory configured, it reads and writes this file to remember things across sessions. This is useful for agents that learn your preferences over time.
|
||||
|
||||
## Worktree isolation
|
||||
|
||||
Set `isolation: "worktree"` to give an agent its own git worktree — an isolated copy of the repository. Changes the agent makes do not affect your working directory until you merge them.
|
||||
|
||||
```
|
||||
Implement this feature in an isolated worktree so I can review the changes before merging.
|
||||
```
|
||||
|
||||
If the agent makes changes, the worktree path and branch are returned in the result so you can inspect them. If the agent makes no changes, the worktree is cleaned up automatically.
|
||||
|
||||
## Monitoring sub-agent progress
|
||||
|
||||
While agents run, you can see:
|
||||
|
||||
* The agent's description and elapsed time in the progress display
|
||||
* Tool calls the agent is making (shown in transcript mode with Ctrl+O)
|
||||
* A notification when the agent completes
|
||||
|
||||
For background agents, progress updates appear in the tasks panel. Claude summarizes the agent's findings when reporting back to you.
|
||||
|
||||
<Warning>
|
||||
Do not ask Claude to check on a running background agent's output file directly. Claude receives a completion notification automatically. Polling the output file mid-run pulls the agent's internal tool noise into Claude's context, which is counterproductive.
|
||||
</Warning>
|
||||
|
||||
## Writing effective agent prompts
|
||||
|
||||
Sub-agents start with zero context from the parent conversation. Claude should — and you can prompt Claude to — write agent prompts that are self-contained briefs.
|
||||
|
||||
A good agent prompt includes:
|
||||
|
||||
* What the agent is trying to accomplish and why
|
||||
* Relevant file paths, function names, or data
|
||||
* What the agent should report back (format, length, specific questions to answer)
|
||||
* What the agent should *not* do (scope constraints)
|
||||
* What has already been tried or ruled out
|
||||
|
||||
A weak prompt:
|
||||
|
||||
```
|
||||
Based on your findings, fix the bug.
|
||||
```
|
||||
|
||||
A stronger prompt:
|
||||
|
||||
```
|
||||
Fix the null reference bug in UserService.getProfile() in src/services/user.ts:247.
|
||||
The bug occurs when the user has no associated profile record — getProfile() calls
|
||||
profile.preferences without checking if profile is null first. Add a null check and
|
||||
return a default preferences object { theme: 'light', notifications: true }.
|
||||
Run npm test afterward to confirm the fix passes existing tests.
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Give agents independent, parallelizable tasks">
|
||||
Agents are most valuable when their work does not depend on each other's output. If task B requires the result of task A, they must be sequential — but tasks A and C can run in parallel while B waits for A.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Provide complete context in the prompt">
|
||||
Paste relevant code snippets, file paths, function signatures, or error messages directly into the agent prompt. Never assume the agent will infer what it needs from minimal instructions.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Be specific about the expected output format">
|
||||
If you need a concise summary, say "report in under 200 words." If you need structured output, describe the format. Vague prompts produce vague results.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Use worktree isolation for risky changes">
|
||||
When an agent will make significant file changes, use `isolation: "worktree"` so you can review before merging. This is especially useful for refactoring or large feature work.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Don't over-parallelize">
|
||||
Spawning many agents for small tasks adds overhead without benefit. Claude decides when agents are worthwhile; trust its judgment unless you have a specific parallel structure in mind.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Limitations and safety
|
||||
|
||||
* Sub-agents have their own permission modes. By default, they use `acceptEdits` mode.
|
||||
* Agents can be denied by permission rules using `Agent(AgentName)` syntax in deny rules.
|
||||
* Background agents are not linked to the parent's abort controller — pressing Escape cancels the parent turn but not running background agents. Use the tasks panel to cancel background agents explicitly.
|
||||
* Sub-agents cannot spawn other teammates (the team roster is flat). They can spawn further sub-agents using the Agent tool.
|
||||
* Fork agents (agents that inherit the parent's context) cannot themselves fork — Claude prevents recursive forking.
|
||||
* Agent results are capped at 100,000 characters before being returned to the parent.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
245
docs/claude-code-docs-main/en/guides/skills.md
Normal file
245
docs/claude-code-docs-main/en/guides/skills.md
Normal file
@@ -0,0 +1,245 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Skills
|
||||
|
||||
> Create reusable on-demand capabilities that Claude invokes with a slash command.
|
||||
|
||||
Skills are markdown files that define reusable prompts and workflows. When you type `/skill-name` in Claude Code, Claude loads that skill's instructions and executes the described task. Skills are useful for any workflow you repeat across sessions — running a deployment, writing a changelog, reviewing a PR, or applying your team's specific coding conventions.
|
||||
|
||||
## How skills work
|
||||
|
||||
A skill is a directory inside `.claude/skills/` with a `SKILL.md` file. When you invoke `/skill-name`, Claude Code loads the skill's `SKILL.md` as the prompt for that action. The skill can include instructions, context, constraints, and even inline shell commands that run at invocation time.
|
||||
|
||||
Skills load lazily — they are only read when invoked, so having many skills defined doesn't affect startup time or context size.
|
||||
|
||||
## Creating a skill
|
||||
|
||||
<Steps>
|
||||
<Step title="Create the skill directory">
|
||||
Skills live in a `skills` subdirectory inside any `.claude/` directory:
|
||||
|
||||
```bash theme={null}
|
||||
mkdir -p .claude/skills/my-skill
|
||||
```
|
||||
|
||||
You can put skills in:
|
||||
|
||||
* `.claude/skills/` (project-level, relative to your working directory)
|
||||
* `~/.claude/skills/` (user-level, available in all projects)
|
||||
</Step>
|
||||
|
||||
<Step title="Write SKILL.md">
|
||||
Create `.claude/skills/my-skill/SKILL.md` with your skill's instructions:
|
||||
|
||||
```markdown theme={null}
|
||||
---
|
||||
description: Run the full release process for this project
|
||||
argument-hint: version number (e.g. 1.2.3)
|
||||
---
|
||||
|
||||
Release the project at version $ARGUMENTS.
|
||||
|
||||
Steps:
|
||||
1. Update the version in `package.json` to $ARGUMENTS
|
||||
2. Update CHANGELOG.md with a new section for this version
|
||||
3. Run `npm test` and confirm all tests pass
|
||||
4. Commit with message "chore: release v$ARGUMENTS"
|
||||
5. Create a git tag `v$ARGUMENTS`
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Invoke the skill">
|
||||
```
|
||||
/my-skill 1.2.3
|
||||
```
|
||||
|
||||
Claude loads the skill and executes the instructions, with `1.2.3` substituted for `$ARGUMENTS`.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Skill frontmatter
|
||||
|
||||
The frontmatter at the top of `SKILL.md` configures how the skill behaves. All fields are optional.
|
||||
|
||||
```yaml theme={null}
|
||||
---
|
||||
description: A short description shown in /skills and used by Claude to decide when to use it
|
||||
argument-hint: what to pass as the argument (shown in autocomplete)
|
||||
allowed-tools: Bash, Write, Read
|
||||
when_to_use: Use this skill when the user asks to create a new component
|
||||
model: claude-sonnet-4-6
|
||||
user-invocable: true
|
||||
context: fork
|
||||
---
|
||||
```
|
||||
|
||||
| Field | Description |
|
||||
| ---------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `description` | Short description shown in `/skills` and used by Claude to decide when to invoke the skill |
|
||||
| `argument-hint` | Hint shown in slash command autocomplete describing what argument to pass |
|
||||
| `allowed-tools` | Comma-separated list of tools this skill is permitted to use (defaults to all) |
|
||||
| `when_to_use` | Prose description of when Claude should use this skill proactively |
|
||||
| `model` | Model to use for this skill (e.g., `claude-sonnet-4-6`); defaults to the session model |
|
||||
| `user-invocable` | Set to `false` to hide the skill from the slash command list (still available to Claude) |
|
||||
| `context` | `fork` to run the skill in an isolated subagent context |
|
||||
| `paths` | Glob patterns; skill only activates when matching files are touched |
|
||||
| `version` | Skill version string |
|
||||
| `hooks` | Hooks scoped to this skill's execution (same format as settings hooks) |
|
||||
|
||||
## Argument substitution
|
||||
|
||||
Use `$ARGUMENTS` anywhere in `SKILL.md` to insert the text passed after the slash command:
|
||||
|
||||
```markdown theme={null}
|
||||
Create a new React component named $ARGUMENTS following the project's conventions.
|
||||
```
|
||||
|
||||
```
|
||||
/new-component UserProfile
|
||||
```
|
||||
|
||||
For named arguments, use `$ARG_NAME` syntax by listing arguments in frontmatter:
|
||||
|
||||
```yaml theme={null}
|
||||
---
|
||||
arguments: [name, directory]
|
||||
---
|
||||
```
|
||||
|
||||
Then reference them as `$name` and `$directory` in the body.
|
||||
|
||||
## Inline shell commands
|
||||
|
||||
Skills can embed shell commands that execute at invocation time using backtick injection syntax. The output is inserted into the prompt before Claude sees it:
|
||||
|
||||
```markdown theme={null}
|
||||
---
|
||||
description: Review recent changes
|
||||
---
|
||||
|
||||
Here are the recent commits for context:
|
||||
|
||||
!`git log --oneline -20`
|
||||
|
||||
Review the changes above and summarize what was accomplished.
|
||||
```
|
||||
|
||||
The `!` prefix followed by a backtick-quoted command runs the command and replaces the block with its output. This is useful for injecting live project state into the skill prompt.
|
||||
|
||||
<Warning>
|
||||
Inline shell commands execute with the same permissions as your shell. They run when you invoke the skill, not when the skill is loaded at startup.
|
||||
</Warning>
|
||||
|
||||
## Listing skills
|
||||
|
||||
Run `/skills` to see all available skills:
|
||||
|
||||
```
|
||||
/skills
|
||||
```
|
||||
|
||||
This shows skills from all scopes (project, user, managed) along with their descriptions.
|
||||
|
||||
## Namespaced skills
|
||||
|
||||
Skills in subdirectories are namespaced with colons:
|
||||
|
||||
```
|
||||
.claude/skills/
|
||||
deployment/
|
||||
SKILL.md → /deployment
|
||||
database/
|
||||
migrate/
|
||||
SKILL.md → /database:migrate
|
||||
seed/
|
||||
SKILL.md → /database:seed
|
||||
```
|
||||
|
||||
## Conditional skills (path-based activation)
|
||||
|
||||
Add a `paths` frontmatter field to activate a skill only when you work with matching files:
|
||||
|
||||
```yaml theme={null}
|
||||
---
|
||||
description: Django model review
|
||||
paths: "**/*.py"
|
||||
when_to_use: Use when editing Django model files
|
||||
---
|
||||
```
|
||||
|
||||
The skill is loaded into Claude's context automatically when you read, write, or edit a file matching the glob pattern. This keeps skills out of context until they're relevant.
|
||||
|
||||
## Bundled skills
|
||||
|
||||
Claude Code ships with built-in skills that are always available. These are compiled into the binary and register themselves at startup. You can see them in `/skills` — they appear with source `bundled`.
|
||||
|
||||
Bundled skills include capabilities like:
|
||||
|
||||
* Project onboarding assistance
|
||||
* Common code review workflows
|
||||
* Agentic search and analysis patterns
|
||||
|
||||
Bundled skills follow the same interface as user-defined skills and can include reference files that are extracted to disk on first invocation.
|
||||
|
||||
## User-level skills
|
||||
|
||||
Skills in `~/.claude/skills/` are available in every project without needing to add them to each repository. This is a good place for personal workflows that span projects.
|
||||
|
||||
```bash theme={null}
|
||||
mkdir -p ~/.claude/skills/standup
|
||||
cat > ~/.claude/skills/standup/SKILL.md << 'EOF'
|
||||
---
|
||||
description: Summarize what I worked on today for a standup update
|
||||
---
|
||||
|
||||
Look at my git commits from today across this repository and summarize them in standup format: what I did, what I'm doing next, and any blockers. Keep it to 3-4 sentences.
|
||||
EOF
|
||||
```
|
||||
|
||||
## Skills vs. hooks
|
||||
|
||||
| Feature | Skills | Hooks |
|
||||
| ------------- | ---------------------------------------------------------------- | ------------------------------------------------- |
|
||||
| Invocation | Explicit: `/skill-name` or by Claude when it recognizes the need | Automatic: fires on tool events |
|
||||
| When to use | Repeatable workflows you want to trigger intentionally | Side effects, formatting, linting, blocking |
|
||||
| Configuration | `SKILL.md` in `.claude/skills/` | `hooks` field in settings JSON |
|
||||
| Context | Can include files, shell output, and detailed instructions | Receives event JSON, returns exit code and output |
|
||||
|
||||
Use skills when you want a named, repeatable action. Use hooks when you want something to happen automatically every time a specific event occurs.
|
||||
|
||||
## Example: custom component generator
|
||||
|
||||
```markdown theme={null}
|
||||
---
|
||||
description: Generate a new React component with tests
|
||||
argument-hint: ComponentName
|
||||
allowed-tools: Write, Bash
|
||||
---
|
||||
|
||||
Create a new React component named $ARGUMENTS.
|
||||
|
||||
1. Create `src/components/$ARGUMENTS/$ARGUMENTS.tsx` with:
|
||||
- A functional component using TypeScript
|
||||
- Props interface named `$ARGUMENTSProps`
|
||||
- JSDoc comment describing the component
|
||||
- Default export
|
||||
|
||||
2. Create `src/components/$ARGUMENTS/$ARGUMENTS.test.tsx` with:
|
||||
- At least one rendering test using React Testing Library
|
||||
- A snapshot test
|
||||
|
||||
3. Create `src/components/$ARGUMENTS/index.ts` that re-exports the component.
|
||||
|
||||
4. Run `npx tsc --noEmit` to confirm no type errors.
|
||||
```
|
||||
|
||||
Invoke with:
|
||||
|
||||
```
|
||||
/new-component Button
|
||||
```
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
270
docs/claude-code-docs-main/en/installation.md
Normal file
270
docs/claude-code-docs-main/en/installation.md
Normal file
@@ -0,0 +1,270 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Installation
|
||||
|
||||
> Install Claude Code on macOS, Linux, or Windows (via WSL). Requires Node.js 18 or higher.
|
||||
|
||||
## Requirements
|
||||
|
||||
* **Node.js 18 or higher** — Claude Code checks the Node.js version at startup and exits with an error if it is below 18.
|
||||
* **npm** — included with Node.js.
|
||||
|
||||
Check your current version:
|
||||
|
||||
```bash theme={null}
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Install Claude Code
|
||||
|
||||
Install globally with npm:
|
||||
|
||||
```bash theme={null}
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
After installation, verify it works:
|
||||
|
||||
```bash theme={null}
|
||||
claude --version
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Platform-specific notes
|
||||
|
||||
<Tabs>
|
||||
<Tab title="macOS">
|
||||
npm global installs work out of the box on macOS. If you get a permissions error when running `npm install -g`, you have two options:
|
||||
|
||||
**Option A: Fix npm permissions (recommended)**
|
||||
|
||||
Configure npm to use a directory in your home folder:
|
||||
|
||||
```bash theme={null}
|
||||
mkdir -p ~/.npm-global
|
||||
npm config set prefix ~/.npm-global
|
||||
```
|
||||
|
||||
Add the following to your shell profile (`~/.zshrc` or `~/.bash_profile`):
|
||||
|
||||
```bash theme={null}
|
||||
export PATH=~/.npm-global/bin:$PATH
|
||||
```
|
||||
|
||||
Then reload your profile and install:
|
||||
|
||||
```bash theme={null}
|
||||
source ~/.zshrc
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
**Option B: Use a Node version manager**
|
||||
|
||||
Tools like [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm) install Node.js in your home directory, which avoids global permission issues entirely:
|
||||
|
||||
```bash theme={null}
|
||||
# Using nvm
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Linux">
|
||||
On most Linux distributions, `npm install -g` requires either `sudo` or a corrected npm prefix. Using `sudo` is not recommended because it can create permission problems later.
|
||||
|
||||
**Recommended: Use a Node version manager**
|
||||
|
||||
```bash theme={null}
|
||||
# Install nvm
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
|
||||
|
||||
# Reload your shell, then install Node.js
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
|
||||
# Install Claude Code
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
**Alternative: Fix npm global prefix**
|
||||
|
||||
```bash theme={null}
|
||||
mkdir -p ~/.npm-global
|
||||
npm config set prefix ~/.npm-global
|
||||
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Windows (WSL)">
|
||||
Claude Code runs on Windows through the Windows Subsystem for Linux (WSL). Running it directly in Command Prompt or PowerShell is not supported.
|
||||
|
||||
**Step 1: Install WSL**
|
||||
|
||||
Open PowerShell as Administrator and run:
|
||||
|
||||
```powershell theme={null}
|
||||
wsl --install
|
||||
```
|
||||
|
||||
Restart your machine when prompted. This installs WSL 2 with Ubuntu by default.
|
||||
|
||||
**Step 2: Open a WSL terminal**
|
||||
|
||||
Launch Ubuntu from the Start menu, or run `wsl` from PowerShell.
|
||||
|
||||
**Step 3: Install Node.js inside WSL**
|
||||
|
||||
```bash theme={null}
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
|
||||
source ~/.bashrc
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
```
|
||||
|
||||
**Step 4: Install Claude Code**
|
||||
|
||||
```bash theme={null}
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
<Note>
|
||||
Always run `claude` from within your WSL terminal, not from Windows CMD or PowerShell. Your project files should live inside the WSL filesystem (e.g., `~/projects/`) for best performance. Accessing Windows files via `/mnt/c/...` works but is slower.
|
||||
</Note>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
***
|
||||
|
||||
## Updating
|
||||
|
||||
Update Claude Code to the latest version with:
|
||||
|
||||
```bash theme={null}
|
||||
npm update -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
Or use Claude Code's built-in update command:
|
||||
|
||||
```bash theme={null}
|
||||
claude update
|
||||
```
|
||||
|
||||
To check what version you're running:
|
||||
|
||||
```bash theme={null}
|
||||
claude --version
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Uninstalling
|
||||
|
||||
Remove Claude Code with:
|
||||
|
||||
```bash theme={null}
|
||||
npm uninstall -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
This removes the `claude` binary. Your configuration files in `~/.claude/` are not removed automatically. To delete them:
|
||||
|
||||
```bash theme={null}
|
||||
rm -rf ~/.claude
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="'claude' command not found after installation">
|
||||
This usually means the npm global bin directory is not on your `PATH`.
|
||||
|
||||
Find where npm installs global binaries:
|
||||
|
||||
```bash theme={null}
|
||||
npm config get prefix
|
||||
```
|
||||
|
||||
The `bin` subdirectory of that path needs to be on your `PATH`. For example, if the output is `/home/you/.npm-global`, add this to your shell profile:
|
||||
|
||||
```bash theme={null}
|
||||
export PATH=/home/you/.npm-global/bin:$PATH
|
||||
```
|
||||
|
||||
Reload your shell (`source ~/.zshrc` or open a new terminal) and try again.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Node.js version is below 18">
|
||||
Claude Code requires Node.js 18 or higher. If you see this error at startup:
|
||||
|
||||
```
|
||||
Error: Claude Code requires Node.js version 18 or higher.
|
||||
```
|
||||
|
||||
Upgrade Node.js using your version manager:
|
||||
|
||||
```bash theme={null}
|
||||
# nvm
|
||||
nvm install --lts
|
||||
nvm use --lts
|
||||
|
||||
# fnm
|
||||
fnm install --lts
|
||||
fnm use --lts
|
||||
```
|
||||
|
||||
Or download the latest LTS release from [nodejs.org](https://nodejs.org).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Permission denied when running npm install -g">
|
||||
Do not use `sudo npm install -g` — it can leave files owned by root and cause further issues. Instead, fix your npm prefix to point to a user-writable directory:
|
||||
|
||||
```bash theme={null}
|
||||
mkdir -p ~/.npm-global
|
||||
npm config set prefix ~/.npm-global
|
||||
export PATH=~/.npm-global/bin:$PATH
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
Add the `export PATH` line to your shell profile so it persists across sessions.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Authentication fails on first run">
|
||||
If the browser-based OAuth flow fails or you cannot use a browser, set your API key directly as an environment variable instead:
|
||||
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
claude
|
||||
```
|
||||
|
||||
You can add this to your shell profile to make it permanent. API keys are available in the [Anthropic Console](https://console.anthropic.com).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Running inside Docker or a CI environment">
|
||||
In non-interactive environments, authenticate with an API key via the environment variable:
|
||||
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
|
||||
Use the `-p` flag to run non-interactively:
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "run the test suite and report any failures"
|
||||
```
|
||||
|
||||
If you need Claude Code to operate without permission prompts in a sandboxed container, use the `--dangerously-skip-permissions` flag. This flag only works in environments that pass Claude Code's sandbox safety checks (no internet access and not running as root outside a container).
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
103
docs/claude-code-docs-main/en/introduction.md
Normal file
103
docs/claude-code-docs-main/en/introduction.md
Normal file
@@ -0,0 +1,103 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Introduction
|
||||
|
||||
> Claude Code is an AI coding agent that runs in your terminal — reading, editing, and executing code across your entire codebase.
|
||||
|
||||
Claude Code is a terminal-based AI agent built on Claude. It has direct access to your filesystem, shell, and tools, so you can describe a task in plain language and Claude handles the implementation end-to-end — no copy-pasting, no context switching.
|
||||
|
||||
## What Claude Code can do
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Read and edit files" icon="file-code" href="/reference/tools/file-operations">
|
||||
Claude reads source files, writes new content, and makes targeted edits. It shows diffs before applying changes so you stay in control.
|
||||
</Card>
|
||||
|
||||
<Card title="Run shell commands" icon="square-terminal" href="/reference/tools/bash">
|
||||
Execute tests, build scripts, git operations, and any shell command — with configurable permission controls to keep you safe.
|
||||
</Card>
|
||||
|
||||
<Card title="Search your codebase" icon="magnifying-glass" href="/reference/tools/search">
|
||||
Find files by glob pattern, search content with regular expressions, and navigate large codebases without reading every file manually.
|
||||
</Card>
|
||||
|
||||
<Card title="Fetch from the web" icon="globe" href="/reference/tools/web">
|
||||
Pull documentation, read API specs, or search the web — all without leaving your terminal session.
|
||||
</Card>
|
||||
|
||||
<Card title="Spawn sub-agents" icon="sitemap" href="/guides/multi-agent">
|
||||
Break complex tasks into parallel workstreams. Claude can spin up and coordinate multiple agents to work on different parts of a problem simultaneously.
|
||||
</Card>
|
||||
|
||||
<Card title="Connect MCP servers" icon="plug" href="/guides/mcp-servers">
|
||||
Extend Claude's capabilities with Model Context Protocol servers for databases, APIs, internal tools, and more.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Permission system
|
||||
|
||||
Every tool use in Claude Code goes through a permission check. You control how much autonomy Claude has.
|
||||
|
||||
| Mode | Behavior |
|
||||
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `default` | Claude asks before running shell commands and making edits. You approve or deny each action. |
|
||||
| `acceptEdits` | File edits are applied automatically. Shell commands still require approval. |
|
||||
| `plan` | Claude produces a plan and asks for your sign-off before taking any action. Good for reviewing large changes before they happen. |
|
||||
| `bypassPermissions` | All actions run without prompts. Intended for automated pipelines in sandboxed environments — not for interactive use. |
|
||||
|
||||
<Warning>
|
||||
`bypassPermissions` mode disables all confirmation prompts. Only use it in isolated environments (Docker containers, CI sandboxes) where Claude cannot affect systems outside the task.
|
||||
</Warning>
|
||||
|
||||
Set your permission mode with the `--permission-mode` flag when starting Claude, or change it with `/permissions` which also lets you manage allow/deny rules for specific tools:
|
||||
|
||||
```bash theme={null}
|
||||
claude --permission-mode acceptEdits
|
||||
```
|
||||
|
||||
## CLAUDE.md memory system
|
||||
|
||||
Claude Code reads `CLAUDE.md` files from your repository at the start of every session. These files let you encode project-specific knowledge — build commands, coding conventions, architecture notes, required environment variables — so Claude doesn't need to re-discover them from scratch every time.
|
||||
|
||||
There are three scopes:
|
||||
|
||||
* **Project** (`CLAUDE.md` at the repo root) — shared by everyone on the team, checked into source control.
|
||||
* **Personal** (`CLAUDE.local.md` at the repo root) — your private preferences for this project, gitignored.
|
||||
* **Subdirectory** (`CLAUDE.md` inside a subdirectory) — loaded automatically when Claude works in that directory. Useful for monorepos with distinct modules.
|
||||
|
||||
Run `/init` inside any Claude Code session to generate a `CLAUDE.md` for your project automatically. Claude analyzes your codebase and produces a file with the commands and context that matter most.
|
||||
|
||||
```bash theme={null}
|
||||
# Inside a Claude Code session
|
||||
/init
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Keep `CLAUDE.md` concise. Every line should pass this test: "Would removing this cause Claude to make mistakes?" If not, cut it.
|
||||
</Tip>
|
||||
|
||||
## Authentication
|
||||
|
||||
Claude Code authenticates in two ways:
|
||||
|
||||
1. **OAuth (recommended)** — Sign in with your Anthropic account at `claude.ai`. Run `claude` for the first time and follow the browser prompt.
|
||||
2. **API key** — Set the `ANTHROPIC_API_KEY` environment variable. Useful for CI pipelines and non-interactive sessions.
|
||||
|
||||
See [Authentication](/guides/authentication) for the full priority order and cloud provider options (AWS Bedrock, GCP Vertex AI).
|
||||
|
||||
## Ready to get started?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quickstart" icon="rocket" href="/quickstart">
|
||||
Get Claude Code running in under 5 minutes
|
||||
</Card>
|
||||
|
||||
<Card title="Installation" icon="download" href="/installation">
|
||||
Detailed installation instructions for all platforms
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
166
docs/claude-code-docs-main/en/quickstart.md
Normal file
166
docs/claude-code-docs-main/en/quickstart.md
Normal file
@@ -0,0 +1,166 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Quickstart
|
||||
|
||||
> Install Claude Code, authenticate, and complete your first coding task in under 5 minutes.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* Node.js 18 or higher
|
||||
* npm
|
||||
|
||||
To check your Node.js version:
|
||||
|
||||
```bash theme={null}
|
||||
node --version
|
||||
```
|
||||
|
||||
If you need to install or upgrade Node.js, download it from [nodejs.org](https://nodejs.org).
|
||||
|
||||
***
|
||||
|
||||
## Step 1: Install Claude Code
|
||||
|
||||
Install the package globally with npm:
|
||||
|
||||
```bash theme={null}
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
Verify the installation:
|
||||
|
||||
```bash theme={null}
|
||||
claude --version
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Step 2: Authenticate
|
||||
|
||||
Run `claude` from any directory to start the first-time setup:
|
||||
|
||||
```bash theme={null}
|
||||
claude
|
||||
```
|
||||
|
||||
On first run, Claude Code opens your browser and walks you through signing in with your Anthropic account. Once complete, your credentials are stored securely and reused for future sessions.
|
||||
|
||||
**Alternatively**, set an API key directly if you prefer not to use OAuth:
|
||||
|
||||
```bash theme={null}
|
||||
export ANTHROPIC_API_KEY=sk-ant-...
|
||||
```
|
||||
|
||||
<Note>
|
||||
API keys take priority when the `ANTHROPIC_API_KEY` environment variable is set. For interactive use, OAuth is recommended because it handles token refresh automatically.
|
||||
</Note>
|
||||
|
||||
***
|
||||
|
||||
## Step 3: Navigate to your project
|
||||
|
||||
Claude Code works within your current directory. Navigate to any project you want to work on:
|
||||
|
||||
```bash theme={null}
|
||||
cd my-project
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Step 4: Start an interactive session
|
||||
|
||||
Run `claude` to open an interactive session:
|
||||
|
||||
```bash theme={null}
|
||||
claude
|
||||
```
|
||||
|
||||
You'll see a prompt where you can type tasks in plain language. Claude reads your project files, runs commands, and makes changes based on what you describe.
|
||||
|
||||
**Example first tasks to try:**
|
||||
|
||||
```
|
||||
> explain the structure of this codebase
|
||||
> add input validation to the signup form
|
||||
> write tests for the UserService class
|
||||
> find all places where we catch and swallow errors
|
||||
```
|
||||
|
||||
Claude shows you what it plans to do before making changes that require permission. You can approve, deny, or ask for a different approach at each step.
|
||||
|
||||
***
|
||||
|
||||
## Step 5: Initialize a CLAUDE.md file
|
||||
|
||||
Run `/init` inside your session to generate a `CLAUDE.md` file for your project:
|
||||
|
||||
```
|
||||
/init
|
||||
```
|
||||
|
||||
Claude analyzes your repository — reading manifest files, existing documentation, and code structure — and produces a `CLAUDE.md` with the commands and context it needs to work effectively in your codebase. You should review and edit the generated file before committing it.
|
||||
|
||||
<Tip>
|
||||
`CLAUDE.md` is loaded at the start of every session. It's the best place to capture things like non-standard build commands, testing quirks, and coding conventions specific to your team.
|
||||
</Tip>
|
||||
|
||||
***
|
||||
|
||||
## Running a non-interactive command
|
||||
|
||||
Use the `-p` flag to run a single task and print the result, without entering an interactive session. This is useful for scripting or one-off queries:
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "explain this codebase"
|
||||
```
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "list all TODO comments and the files they appear in"
|
||||
```
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "check for unused exports in src/"
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Key slash commands
|
||||
|
||||
Once you're inside an interactive session, these slash commands are the most useful to know:
|
||||
|
||||
| Command | Description |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| `/help` | Show available commands and keyboard shortcuts |
|
||||
| `/init` | Generate or update a `CLAUDE.md` for the current project |
|
||||
| `/memory` | View and edit memory files (`CLAUDE.md`, `CLAUDE.local.md`) |
|
||||
| `/permissions` | View or change the current permission mode |
|
||||
| `/mcp` | Manage connected MCP servers |
|
||||
| `/clear` | Clear the current conversation context |
|
||||
| `/exit` | End the session |
|
||||
|
||||
***
|
||||
|
||||
## Next steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Core concepts" icon="lightbulb" href="/concepts/how-it-works">
|
||||
Understand how Claude Code thinks, plans, and acts on tasks
|
||||
</Card>
|
||||
|
||||
<Card title="Permission modes" icon="shield" href="/concepts/permissions">
|
||||
Learn how to configure how much autonomy Claude has
|
||||
</Card>
|
||||
|
||||
<Card title="CLAUDE.md reference" icon="file-text" href="/configuration/claudemd">
|
||||
Write effective memory files for your projects
|
||||
</Card>
|
||||
|
||||
<Card title="MCP servers" icon="plug" href="/guides/mcp-servers">
|
||||
Extend Claude with databases, APIs, and internal tools
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
517
docs/claude-code-docs-main/en/reference/commands/cli-flags.md
Normal file
517
docs/claude-code-docs-main/en/reference/commands/cli-flags.md
Normal file
@@ -0,0 +1,517 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# CLI flags
|
||||
|
||||
> All options you can pass when launching Claude Code from the terminal. Run claude --help to see the full list.
|
||||
|
||||
Pass CLI flags when you launch Claude Code:
|
||||
|
||||
```bash theme={null}
|
||||
claude [flags] [prompt]
|
||||
```
|
||||
|
||||
Run `claude --help` to see all available flags in your installed version.
|
||||
|
||||
<Tip>
|
||||
Flags that configure session behavior (like `--model` and `--permission-mode`) can also be changed mid-session with the corresponding slash commands: `/model` and `/permissions`.
|
||||
</Tip>
|
||||
|
||||
***
|
||||
|
||||
## Core flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="-p, --print">
|
||||
Run Claude non-interactively. Claude processes the prompt (from the argument or stdin), prints the response, and exits. No REPL is started.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "explain the main function in src/index.ts"
|
||||
echo "what does this do?" | claude -p
|
||||
```
|
||||
|
||||
<Warning>
|
||||
The workspace trust dialog is skipped in `--print` mode. Only use this flag in directories you trust.
|
||||
</Warning>
|
||||
|
||||
Works with: `--output-format`, `--model`, `--system-prompt`, `--permission-mode`, `--max-turns`, `--allowed-tools`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--output-format <format>">
|
||||
Set the output format. Only works with `--print`.
|
||||
|
||||
| Value | Description |
|
||||
| ------------- | --------------------------------------------------- |
|
||||
| `text` | Plain text output (default) |
|
||||
| `json` | Single JSON object with the complete result |
|
||||
| `stream-json` | Newline-delimited JSON stream with real-time events |
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "list the exported functions" --output-format json
|
||||
claude -p "refactor this file" --output-format stream-json
|
||||
```
|
||||
|
||||
Use `stream-json` when you want to process Claude's output incrementally as it arrives (useful for long-running tasks or piping into other tools).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--input-format <format>">
|
||||
Set the input format for stdin. Only works with `--print`.
|
||||
|
||||
| Value | Description |
|
||||
| ------------- | ----------------------------------- |
|
||||
| `text` | Plain text input (default) |
|
||||
| `stream-json` | Newline-delimited JSON stream input |
|
||||
|
||||
`stream-json` input requires `--output-format stream-json`.
|
||||
|
||||
```bash theme={null}
|
||||
cat messages.jsonl | claude -p --input-format stream-json --output-format stream-json
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--verbose">
|
||||
Enable verbose output. Overrides the `verbose` setting in your config file.
|
||||
|
||||
```bash theme={null}
|
||||
claude --verbose
|
||||
claude -p "debug this" --verbose
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="-v, --version">
|
||||
Print the version number and exit.
|
||||
|
||||
```bash theme={null}
|
||||
claude --version
|
||||
claude -v
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="-h, --help">
|
||||
Display help for the command and exit.
|
||||
|
||||
```bash theme={null}
|
||||
claude --help
|
||||
claude mcp --help
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Session continuation flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="-c, --continue">
|
||||
Resume the most recent conversation in the current directory without prompting for a session to resume.
|
||||
|
||||
```bash theme={null}
|
||||
claude --continue
|
||||
claude -c "now add tests for that"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="-r, --resume [session-id]">
|
||||
Resume a conversation by session ID. Without a value, opens an interactive picker where you can search through past sessions. Accepts an optional search term to filter the list.
|
||||
|
||||
```bash theme={null}
|
||||
# Open interactive picker
|
||||
claude --resume
|
||||
|
||||
# Resume by session ID
|
||||
claude --resume 550e8400-e29b-41d4-a716-446655440000
|
||||
|
||||
# Open picker filtered by search term
|
||||
claude --resume "auth refactor"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--fork-session">
|
||||
When used with `--continue` or `--resume`, creates a new session branched from the resumed conversation rather than continuing it in place.
|
||||
|
||||
```bash theme={null}
|
||||
claude --resume <session-id> --fork-session
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="-n, --name <name>">
|
||||
Set a display name for the session. The name appears in `/resume` and in the terminal title.
|
||||
|
||||
```bash theme={null}
|
||||
claude --name "auth-refactor"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--session-id <uuid>">
|
||||
Use a specific UUID as the session ID instead of a generated one. Must be a valid UUID. Cannot be used with `--continue` or `--resume` unless `--fork-session` is also specified.
|
||||
|
||||
```bash theme={null}
|
||||
claude --session-id 550e8400-e29b-41d4-a716-446655440000
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--no-session-persistence">
|
||||
Disable session persistence. The session will not be saved to disk and cannot be resumed. Only works with `--print`.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "one-off task" --no-session-persistence
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Model and capability flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="--model <model>">
|
||||
Set the model for the session. Accepts an alias (e.g. `sonnet`, `opus`, `haiku`) or a full model ID (e.g. `claude-sonnet-4-6`).
|
||||
|
||||
```bash theme={null}
|
||||
claude --model sonnet
|
||||
claude --model opus
|
||||
claude --model claude-sonnet-4-6
|
||||
```
|
||||
|
||||
You can also change the model mid-session with `/model`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--effort <level>">
|
||||
Set the effort level for the session. Controls how much computation Claude applies to each response.
|
||||
|
||||
| Value | Description |
|
||||
| -------- | ------------------------- |
|
||||
| `low` | Faster, lighter responses |
|
||||
| `medium` | Balanced (default) |
|
||||
| `high` | More thorough reasoning |
|
||||
| `max` | Maximum effort |
|
||||
|
||||
```bash theme={null}
|
||||
claude --effort high "review this architecture"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--fallback-model <model>">
|
||||
Enable automatic fallback to a different model when the primary model is overloaded. Only works with `--print`.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "analyze this" --model opus --fallback-model sonnet
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Permission and safety flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="--permission-mode <mode>">
|
||||
Set the permission mode for the session.
|
||||
|
||||
| Mode | Behavior |
|
||||
| ------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `default` | Claude prompts before running commands and making edits |
|
||||
| `acceptEdits` | File edits are applied automatically; shell commands still require approval |
|
||||
| `plan` | Claude proposes a plan and waits for your approval before acting |
|
||||
| `bypassPermissions` | All actions run without prompts — intended for sandboxed automated environments only |
|
||||
|
||||
```bash theme={null}
|
||||
claude --permission-mode acceptEdits
|
||||
claude --permission-mode plan "refactor the payment module"
|
||||
claude --permission-mode bypassPermissions # only in isolated sandboxes
|
||||
```
|
||||
|
||||
<Warning>
|
||||
`bypassPermissions` disables all confirmation prompts. Only use it inside Docker containers, CI sandboxes, or other isolated environments with no internet access.
|
||||
</Warning>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--dangerously-skip-permissions">
|
||||
Bypass all permission checks. Claude takes all actions (file edits, shell commands) without asking. Equivalent to `--permission-mode bypassPermissions`.
|
||||
|
||||
```bash theme={null}
|
||||
claude --dangerously-skip-permissions -p "run the full test suite and fix failures"
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Only use this in sandboxed environments with no internet access. Claude Code enforces this: the flag is rejected when running with root/sudo privileges, or outside a Docker or bubblewrap container.
|
||||
</Warning>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--allow-dangerously-skip-permissions">
|
||||
Make bypassing all permission checks available as an option during the session, without enabling it by default. Useful for automated pipelines that may need to escalate mid-session.
|
||||
|
||||
```bash theme={null}
|
||||
claude --allow-dangerously-skip-permissions -p "..."
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--allowed-tools <tools...>">
|
||||
**Aliases:** `--allowedTools`
|
||||
|
||||
Comma- or space-separated list of tools Claude is allowed to use. Tools not in this list are blocked.
|
||||
|
||||
```bash theme={null}
|
||||
claude --allowed-tools "Bash(git:*) Edit Read"
|
||||
claude --allowed-tools Bash,Edit,Read
|
||||
```
|
||||
|
||||
Tool patterns support glob-style matching: `Bash(git:*)` permits any git command; `Edit(src/**)` permits edits under `src/`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--disallowed-tools <tools...>">
|
||||
**Aliases:** `--disallowedTools`
|
||||
|
||||
Comma- or space-separated list of tools Claude is not allowed to use.
|
||||
|
||||
```bash theme={null}
|
||||
claude --disallowed-tools "Bash(rm:*)"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--tools <tools...>">
|
||||
Specify the exact set of built-in tools available for the session. Use `""` to disable all tools, `default` to enable all tools, or name specific tools.
|
||||
|
||||
```bash theme={null}
|
||||
# Disable all tools
|
||||
claude --tools ""
|
||||
|
||||
# Enable only Bash and Read
|
||||
claude --tools "Bash Read"
|
||||
|
||||
# Enable the default set
|
||||
claude --tools default
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Context and prompt flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="--add-dir <directories...>">
|
||||
Add one or more directories to the tool access context. Claude will be able to read and edit files in these directories in addition to the current working directory.
|
||||
|
||||
```bash theme={null}
|
||||
claude --add-dir /shared/libs --add-dir /shared/config
|
||||
```
|
||||
|
||||
Useful for monorepos or projects where related code lives outside the current directory.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--system-prompt <prompt>">
|
||||
Override the default system prompt with a custom prompt. Cannot be used with `--system-prompt-file`.
|
||||
|
||||
```bash theme={null}
|
||||
claude --system-prompt "You are a security auditor. Focus only on vulnerabilities."
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--append-system-prompt <text>">
|
||||
Append text to the default system prompt. Unlike `--system-prompt`, this preserves Claude's built-in instructions and adds to them.
|
||||
|
||||
```bash theme={null}
|
||||
claude --append-system-prompt "Always suggest test cases for every function you write."
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--mcp-config <configs...>">
|
||||
Load MCP servers from one or more JSON config files or inline JSON strings. Multiple values are space-separated.
|
||||
|
||||
```bash theme={null}
|
||||
# Load from a file
|
||||
claude --mcp-config ./mcp-servers.json
|
||||
|
||||
# Load from multiple files
|
||||
claude --mcp-config ./local-tools.json ./db-tools.json
|
||||
|
||||
# Pass inline JSON
|
||||
claude --mcp-config '{"mcpServers":{"filesystem":{"command":"npx","args":["@modelcontextprotocol/server-filesystem","/tmp"]}}}'
|
||||
```
|
||||
|
||||
See the [MCP servers guide](/guides/mcp-servers) for the config file format.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--strict-mcp-config">
|
||||
Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations (user config, project config, etc.).
|
||||
|
||||
```bash theme={null}
|
||||
claude --mcp-config ./ci-tools.json --strict-mcp-config
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--settings <file-or-json>">
|
||||
Load additional settings from a JSON file path or an inline JSON string.
|
||||
|
||||
```bash theme={null}
|
||||
# From a file
|
||||
claude --settings ./team-settings.json
|
||||
|
||||
# Inline JSON
|
||||
claude --settings '{"model":"claude-sonnet-4-6","verbose":true}'
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--setting-sources <sources>">
|
||||
Comma-separated list of settings sources to load. Controls which settings files are read at startup.
|
||||
|
||||
| Value | Description |
|
||||
| --------- | ----------------------------------------------------------- |
|
||||
| `user` | Load `~/.claude/settings.json` |
|
||||
| `project` | Load `.claude/settings.json` in the current directory |
|
||||
| `local` | Load `.claude/settings.local.json` in the current directory |
|
||||
|
||||
```bash theme={null}
|
||||
# Load only user-level settings (ignore project settings)
|
||||
claude --setting-sources user
|
||||
|
||||
# Load user and project settings
|
||||
claude --setting-sources user,project
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--agents <json>">
|
||||
Define custom agents inline as a JSON object. Each key is the agent name; the value is an object with `description` and `prompt`.
|
||||
|
||||
```bash theme={null}
|
||||
claude --agents '{"reviewer":{"description":"Reviews code for security issues","prompt":"You are a security-focused code reviewer."}}'
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Output control flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="--include-hook-events">
|
||||
Include all hook lifecycle events in the output stream. Only works with `--output-format stream-json`.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "run task" --output-format stream-json --include-hook-events
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--max-turns <n>">
|
||||
Limit the number of agentic turns in non-interactive mode. Claude stops after this many turns even if the task is incomplete. Only works with `--print`.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "refactor this module" --max-turns 10
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--max-budget-usd <amount>">
|
||||
Set a maximum dollar amount to spend on API calls. Claude stops when the budget is reached. Only works with `--print`.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "large analysis task" --max-budget-usd 2.50
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--json-schema <schema>">
|
||||
Provide a JSON Schema for structured output validation. Claude's response will be validated against this schema.
|
||||
|
||||
```bash theme={null}
|
||||
claude -p "extract the function names" \
|
||||
--output-format json \
|
||||
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Worktree flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="-w, --worktree [name]">
|
||||
Create a new git worktree for this session. Optionally specify a name for the worktree branch. Accepts a PR number or GitHub PR URL to create a worktree from that PR.
|
||||
|
||||
```bash theme={null}
|
||||
claude --worktree
|
||||
claude --worktree feature-auth
|
||||
claude --worktree "#142"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--tmux">
|
||||
Create a tmux session alongside the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` to force standard tmux behavior.
|
||||
|
||||
```bash theme={null}
|
||||
claude --worktree feature-auth --tmux
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Debug flags
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="-d, --debug [filter]">
|
||||
Enable debug mode. Optionally pass a filter to restrict which debug categories are shown.
|
||||
|
||||
```bash theme={null}
|
||||
# Show all debug output
|
||||
claude --debug
|
||||
|
||||
# Show only api and hooks categories
|
||||
claude --debug "api,hooks"
|
||||
|
||||
# Exclude specific categories
|
||||
claude --debug "!file,!1p"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--debug-file <path>">
|
||||
Write debug logs to a specific file path instead of displaying them inline. Implicitly enables debug mode.
|
||||
|
||||
```bash theme={null}
|
||||
claude --debug-file /tmp/claude-debug.log
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="--bare">
|
||||
Minimal mode. Skips hooks, LSP, plugin sync, attribution, auto-memory, background prefetches, keychain reads, and `CLAUDE.md` auto-discovery. Sets `CLAUDE_CODE_SIMPLE=1`.
|
||||
|
||||
Authentication is limited to `ANTHROPIC_API_KEY` or `apiKeyHelper` via `--settings` (OAuth and keychain are not used).
|
||||
|
||||
Use `--bare` in scripted pipelines where startup latency matters and the features it disables are not needed. You can still provide context explicitly:
|
||||
|
||||
```bash theme={null}
|
||||
claude --bare \
|
||||
--system-prompt "$(cat context.md)" \
|
||||
--add-dir /project/libs \
|
||||
--mcp-config ./tools.json \
|
||||
-p "perform the analysis"
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Flag combinations
|
||||
|
||||
Common flag patterns for scripting and automation:
|
||||
|
||||
```bash theme={null}
|
||||
# Non-interactive with JSON output
|
||||
claude -p "list all exported types" --output-format json
|
||||
|
||||
# Bypass permissions in CI (sandboxed environment only)
|
||||
claude -p "run full test suite and fix failures" --dangerously-skip-permissions
|
||||
|
||||
# Resume last session and continue non-interactively
|
||||
claude --continue -p "now write the tests for that"
|
||||
|
||||
# Use a custom MCP config with strict isolation
|
||||
claude --mcp-config ./ci-mcp.json --strict-mcp-config -p "analyze the schema"
|
||||
|
||||
# Append to system prompt without replacing it
|
||||
claude --append-system-prompt "Always output TypeScript, not JavaScript."
|
||||
```
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
106
docs/claude-code-docs-main/en/reference/commands/overview.md
Normal file
106
docs/claude-code-docs-main/en/reference/commands/overview.md
Normal file
@@ -0,0 +1,106 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Commands overview
|
||||
|
||||
> Claude Code accepts two categories of commands: CLI flags you pass at launch, and slash commands you type during a session.
|
||||
|
||||
Claude Code has two categories of commands:
|
||||
|
||||
* **CLI flags** — options you pass when starting Claude from your terminal (e.g. `claude --model sonnet`). They configure the session before it starts.
|
||||
* **Slash commands** — text commands you type inside an active session (e.g. `/help`). They control Claude's behavior while the session is running.
|
||||
|
||||
## Getting help
|
||||
|
||||
```bash theme={null}
|
||||
# Show all CLI flags
|
||||
claude --help
|
||||
|
||||
# Inside a session, list slash commands
|
||||
/help
|
||||
```
|
||||
|
||||
`/help` lists every slash command available in the current session, including commands added by plugins and skills.
|
||||
|
||||
## Two types of commands
|
||||
|
||||
| Type | When to use | Example |
|
||||
| -------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------ |
|
||||
| CLI flags | Configure a session at launch — set the model, output format, permission mode | `claude --permission-mode acceptEdits "fix the tests"` |
|
||||
| Slash commands | Interact with a running session — manage memory, switch models, commit code | `/commit` |
|
||||
|
||||
CLI flags are consumed once and cannot be changed mid-session (with the exception of `/model` and `/permissions`, which change the running configuration in place).
|
||||
|
||||
## CLI flags
|
||||
|
||||
Pass flags directly after `claude`:
|
||||
|
||||
```bash theme={null}
|
||||
claude [flags] [prompt]
|
||||
```
|
||||
|
||||
```bash theme={null}
|
||||
# Non-interactive: print response and exit
|
||||
claude -p "summarize this file" < README.md
|
||||
|
||||
# Set model for the session
|
||||
claude --model opus
|
||||
|
||||
# Accept all file edits automatically
|
||||
claude --permission-mode acceptEdits
|
||||
```
|
||||
|
||||
See [CLI flags](/reference/commands/cli-flags) for the full list.
|
||||
|
||||
## Slash commands
|
||||
|
||||
Type a slash command at the input prompt inside any session:
|
||||
|
||||
```
|
||||
/command [arguments]
|
||||
```
|
||||
|
||||
```
|
||||
/init
|
||||
/compact summarize only the last three tasks
|
||||
/model claude-opus-4-5
|
||||
```
|
||||
|
||||
See [Slash commands](/reference/commands/slash-commands) for the full list.
|
||||
|
||||
## Keyboard shortcuts
|
||||
|
||||
These shortcuts work inside any interactive Claude Code session:
|
||||
|
||||
| Key | Action |
|
||||
| ------------- | ---------------------------------------------------------------- |
|
||||
| `Ctrl+C` | Interrupt the current response (Claude stops mid-turn) |
|
||||
| `Ctrl+D` | Exit Claude Code |
|
||||
| `Ctrl+L` | Clear the terminal display (does not clear conversation history) |
|
||||
| `Up` / `Down` | Navigate input history |
|
||||
| `Tab` | Autocomplete slash command names |
|
||||
| `Escape` | Cancel an in-progress permission prompt |
|
||||
|
||||
<Note>
|
||||
`Ctrl+C` interrupts the current response but keeps the conversation alive. Use `Ctrl+D` or `/exit` to end the session entirely.
|
||||
</Note>
|
||||
|
||||
## Subcommands
|
||||
|
||||
In addition to the main `claude` command, a few subcommands are available in your terminal:
|
||||
|
||||
| Subcommand | Description |
|
||||
| ------------------ | ---------------------------------------------- |
|
||||
| `claude mcp` | Configure and manage MCP servers |
|
||||
| `claude mcp serve` | Start Claude Code as an MCP server |
|
||||
| `claude doctor` | Diagnose installation and configuration issues |
|
||||
| `claude update` | Update Claude Code to the latest version |
|
||||
|
||||
```bash theme={null}
|
||||
claude mcp --help
|
||||
claude doctor
|
||||
```
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
@@ -0,0 +1,381 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Slash commands
|
||||
|
||||
> Commands you type inside a running Claude Code session. Type / at the input prompt to activate them.
|
||||
|
||||
Slash commands are typed at the Claude Code input prompt during an active session. Every command starts with `/`.
|
||||
|
||||
```
|
||||
/command [arguments]
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Type `/help` at any time to see all commands available in the current session, including any added by plugins and skills.
|
||||
</Tip>
|
||||
|
||||
## Quick reference
|
||||
|
||||
| Command | Description |
|
||||
| ------------------------------ | -------------------------------------------------------------------- |
|
||||
| [`/init`](#init) | Generate `CLAUDE.md` files and optional skills/hooks for the project |
|
||||
| [`/memory`](#memory) | Edit Claude memory files (global, project, local) |
|
||||
| [`/config`](#config) | Open the settings panel |
|
||||
| [`/hooks`](#hooks) | View hook configurations for tool events |
|
||||
| [`/mcp`](#mcp) | Manage MCP servers — enable, disable, reconnect |
|
||||
| [`/permissions`](#permissions) | Manage allow and deny rules for tools |
|
||||
| [`/plan`](#plan) | Enable plan mode or open/describe the current session plan |
|
||||
| [`/model`](#model) | Set the AI model for the current session |
|
||||
| [`/commit`](#commit) | Create a git commit with an AI-generated message |
|
||||
| [`/review`](#review) | Review a pull request |
|
||||
| [`/skills`](#skills) | List available skills |
|
||||
| [`/compact`](#compact) | Summarize conversation history to reduce context usage |
|
||||
| [`/clear`](#clear) | Clear conversation history and free up context |
|
||||
| [`/help`](#help) | Show help and available commands |
|
||||
| [`/login`](#login) | Sign in or switch Anthropic accounts |
|
||||
| [`/logout`](#logout) | Sign out from your Anthropic account |
|
||||
|
||||
***
|
||||
|
||||
## Project and memory commands
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="/init">
|
||||
**Syntax:** `/init`
|
||||
|
||||
Analyzes your codebase and sets up `CLAUDE.md` file(s), and optionally skills and hooks. Claude surveys key project files — manifests, CI config, build scripts, README — then interviews you to fill in any gaps before writing the output files.
|
||||
|
||||
What it sets up, depending on your choices:
|
||||
|
||||
* **Project `CLAUDE.md`** — team-shared instructions checked into source control. Covers build/test/lint commands, coding conventions, architecture notes, and non-obvious gotchas.
|
||||
* **Personal `CLAUDE.local.md`** — your private preferences for this project (gitignored). Covers your role, sandbox URLs, communication preferences.
|
||||
* **Skills** (`.claude/skills/<name>/SKILL.md`) — on-demand workflows you or Claude invoke with `/<skill-name>`.
|
||||
* **Hooks** (`.claude/settings.json`) — deterministic shell commands that run automatically on tool events (e.g. format on every edit).
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/init
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Run `/init` again at any time. If `CLAUDE.md` already exists, Claude will propose specific changes rather than overwriting the file.
|
||||
</Tip>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/memory">
|
||||
**Syntax:** `/memory`
|
||||
|
||||
Opens an interactive editor for Claude's memory files. Memory files are loaded into every session and persist across conversations.
|
||||
|
||||
The three memory scopes are:
|
||||
|
||||
| Scope | File | Who it applies to |
|
||||
| ------- | --------------------------------- | --------------------------------------- |
|
||||
| Global | `~/.claude/CLAUDE.md` | You, across all projects |
|
||||
| Project | `CLAUDE.md` at project root | Everyone on the team |
|
||||
| Local | `CLAUDE.local.md` at project root | You, for this project only (gitignored) |
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/memory
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Configuration commands
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="/config">
|
||||
**Syntax:** `/config`
|
||||
|
||||
**Alias:** `/settings`
|
||||
|
||||
Opens the configuration panel where you can view and edit Claude Code settings, including model preferences, theme, verbose mode, and more.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/config
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/hooks">
|
||||
**Syntax:** `/hooks`
|
||||
|
||||
Displays the hook configurations currently active for this session. Hooks are shell commands that run automatically when tool events occur (e.g. after every file edit, before a Bash command).
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/hooks
|
||||
```
|
||||
|
||||
<Note>
|
||||
To create or edit hooks, use `/init` or edit `.claude/settings.json` directly. See the [hooks guide](/guides/hooks) for the full schema.
|
||||
</Note>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/mcp">
|
||||
**Syntax:** `/mcp [enable|disable [server-name]]`
|
||||
|
||||
Manages MCP (Model Context Protocol) servers for the current session. Without arguments, opens the MCP management panel. With arguments, enables or disables specific servers.
|
||||
|
||||
| Argument | Effect |
|
||||
| ------------------------- | --------------------------------- |
|
||||
| *(none)* | Open the MCP management panel |
|
||||
| `enable` | Enable all disabled MCP servers |
|
||||
| `enable <server-name>` | Enable a specific server by name |
|
||||
| `disable` | Disable all active MCP servers |
|
||||
| `disable <server-name>` | Disable a specific server by name |
|
||||
| `reconnect <server-name>` | Reconnect to a specific server |
|
||||
|
||||
**Examples:**
|
||||
|
||||
```
|
||||
/mcp
|
||||
/mcp enable
|
||||
/mcp enable my-database-server
|
||||
/mcp disable analytics-server
|
||||
/mcp reconnect filesystem
|
||||
```
|
||||
|
||||
<Note>
|
||||
To add or remove MCP servers permanently, use the `claude mcp` CLI subcommand or edit your MCP config file. Changes made with `/mcp enable`/`disable` apply for the current session only.
|
||||
</Note>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/permissions">
|
||||
**Syntax:** `/permissions`
|
||||
|
||||
**Alias:** `/allowed-tools`
|
||||
|
||||
Opens the permissions panel where you can view and manage allow and deny rules for tools. Rules control which tools Claude can use without prompting (allow rules) and which are blocked entirely (deny rules).
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/permissions
|
||||
```
|
||||
|
||||
Rules use glob-style patterns:
|
||||
|
||||
```
|
||||
Bash(git:*) # allow all git commands
|
||||
Bash(npm:*) # allow all npm commands
|
||||
Edit(src/**/*.ts) # allow edits to TypeScript files in src/
|
||||
```
|
||||
|
||||
See [permissions](/concepts/permissions) for the full rule syntax.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/model">
|
||||
**Syntax:** `/model [model]`
|
||||
|
||||
Sets the AI model used for the rest of the session. Without an argument, opens an interactive model picker. With a model name or alias, switches immediately.
|
||||
|
||||
| Argument | Effect |
|
||||
| ------------------- | ------------------------------------- |
|
||||
| *(none)* | Open the interactive model picker |
|
||||
| `sonnet` | Switch to the latest Claude Sonnet |
|
||||
| `opus` | Switch to the latest Claude Opus |
|
||||
| `haiku` | Switch to the latest Claude Haiku |
|
||||
| `claude-sonnet-4-6` | Switch to a specific model by full ID |
|
||||
|
||||
**Examples:**
|
||||
|
||||
```
|
||||
/model
|
||||
/model sonnet
|
||||
/model claude-opus-4-5
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Session management commands
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="/plan">
|
||||
**Syntax:** `/plan [open|<description>]`
|
||||
|
||||
Enables plan mode or manages the current session plan. In plan mode, Claude produces a written plan before taking any action and waits for your approval.
|
||||
|
||||
| Argument | Effect |
|
||||
| --------------- | -------------------------------------------- |
|
||||
| *(none)* | Toggle plan mode on/off |
|
||||
| `open` | Open and display the current plan |
|
||||
| `<description>` | Create a new plan with the given description |
|
||||
|
||||
**Examples:**
|
||||
|
||||
```
|
||||
/plan
|
||||
/plan open
|
||||
/plan refactor the auth module to use JWT
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Plan mode is equivalent to `--permission-mode plan` at launch. Use it when you want to review what Claude intends to do before any files are touched.
|
||||
</Tip>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/compact">
|
||||
**Syntax:** `/compact [instructions]`
|
||||
|
||||
Summarizes the conversation history and replaces it with a condensed version in context. Use this when the context window is filling up and you want to continue working without starting a new session.
|
||||
|
||||
An optional argument lets you give Claude specific instructions for how to summarize.
|
||||
|
||||
**Examples:**
|
||||
|
||||
```
|
||||
/compact
|
||||
/compact focus only on the database schema changes
|
||||
/compact summarize the last three completed tasks
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/clear">
|
||||
**Syntax:** `/clear`
|
||||
|
||||
**Aliases:** `/reset`, `/new`
|
||||
|
||||
Clears the entire conversation history and frees up context, starting a fresh session in the same working directory. Unlike `/compact`, this removes all history rather than summarizing it.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/clear
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/skills">
|
||||
**Syntax:** `/skills`
|
||||
|
||||
Lists all skills available in the current session. Skills are on-demand capabilities defined in `.claude/skills/` that you or Claude can invoke with `/<skill-name>`.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/skills
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Git commands
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="/commit">
|
||||
**Syntax:** `/commit`
|
||||
|
||||
Creates a git commit using AI-generated commit message. Claude reads the current git status and diff, analyzes staged and unstaged changes, and drafts a concise commit message that focuses on the "why" rather than the "what". It then stages the relevant files and creates the commit.
|
||||
|
||||
Claude follows the existing commit message style in the repository and applies these safety rules:
|
||||
|
||||
* Never amends existing commits (always creates a new commit)
|
||||
* Never skips hooks (`--no-verify`)
|
||||
* Never commits files that likely contain secrets (`.env`, credentials files)
|
||||
* Does not create empty commits when there are no changes
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/commit
|
||||
```
|
||||
|
||||
<Note>
|
||||
`/commit` only has access to `git add`, `git status`, and `git commit`. It cannot push, rebase, or run other git operations.
|
||||
</Note>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/review">
|
||||
**Syntax:** `/review [PR-number]`
|
||||
|
||||
Runs an AI code review on a pull request using the GitHub CLI (`gh`). Without a PR number, Claude runs `gh pr list` to show open PRs. With a PR number, it fetches the PR details and diff, then provides a structured review covering:
|
||||
|
||||
* Overview of what the PR does
|
||||
* Code quality and style analysis
|
||||
* Specific improvement suggestions
|
||||
* Potential issues or risks
|
||||
* Performance, test coverage, and security considerations
|
||||
|
||||
**Examples:**
|
||||
|
||||
```
|
||||
/review
|
||||
/review 142
|
||||
```
|
||||
|
||||
<Note>
|
||||
`/review` requires the [GitHub CLI](https://cli.github.com/) (`gh`) to be installed and authenticated.
|
||||
</Note>
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Account and help commands
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="/help">
|
||||
**Syntax:** `/help`
|
||||
|
||||
Shows help and lists all slash commands available in the current session, including built-in commands, skill commands, and any commands added by installed plugins.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/help
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/login">
|
||||
**Syntax:** `/login`
|
||||
|
||||
Signs in to your Anthropic account or switches between accounts. Opens a browser-based OAuth flow if not already authenticated, or presents the account switcher if you are.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/login
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="/logout">
|
||||
**Syntax:** `/logout`
|
||||
|
||||
Signs out from your Anthropic account. After logging out, Claude Code will prompt you to authenticate again on the next session.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
/logout
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Custom skill commands
|
||||
|
||||
When you or a plugin author creates a skill in `.claude/skills/<skill-name>/SKILL.md`, it becomes available as `/<skill-name>` in any session where that skill is loaded.
|
||||
|
||||
```
|
||||
/verify
|
||||
/deploy staging
|
||||
/fix-issue 123
|
||||
```
|
||||
|
||||
Run `/skills` to see all loaded skills and their descriptions. See the [skills guide](/guides/skills) for how to create your own.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
935
docs/claude-code-docs-main/en/reference/sdk/hooks-reference.md
Normal file
935
docs/claude-code-docs-main/en/reference/sdk/hooks-reference.md
Normal file
@@ -0,0 +1,935 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Hooks reference
|
||||
|
||||
> Full reference for every hook event, its input payload, output schema, and the effect each exit code has on Claude's behavior.
|
||||
|
||||
Hooks are shell commands, HTTP endpoints, LLM prompts, or in-process callbacks that fire at defined points in Claude's agentic loop. They let you inject logic before or after tool calls, intercept permission requests, react to session lifecycle events, and more.
|
||||
|
||||
## Configuration
|
||||
|
||||
Hooks are configured in any Claude Code settings file. The top-level `hooks` key maps event names to an array of matcher objects.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo 'About to run bash command' >&2"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "/usr/local/bin/lint-changed-file '$TOOL_INPUT'"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "notify-send 'Claude finished'"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Settings file locations
|
||||
|
||||
| Scope | Path | Priority |
|
||||
| ------- | ----------------------------- | -------- |
|
||||
| User | `~/.claude/settings.json` | Low |
|
||||
| Project | `.claude/settings.json` | Medium |
|
||||
| Local | `.claude/settings.local.json` | High |
|
||||
|
||||
Higher-priority settings files take precedence. All hooks across all files run; they are not overridden.
|
||||
|
||||
### Matcher configuration
|
||||
|
||||
<ResponseField name="matcher" type="string">
|
||||
A string pattern that filters when these hooks run. The field matched depends on the event:
|
||||
|
||||
* `PreToolUse` / `PostToolUse` / `PostToolUseFailure` / `PermissionRequest` / `PermissionDenied` — matched against `tool_name`
|
||||
* `Notification` — matched against `notification_type`
|
||||
* `SessionStart` — matched against `source` (`startup`, `resume`, `clear`, `compact`)
|
||||
* `Setup` — matched against `trigger` (`init`, `maintenance`)
|
||||
* `SubagentStart` / `SubagentStop` — matched against `agent_type`
|
||||
* `PreCompact` / `PostCompact` — matched against `trigger` (`manual`, `auto`)
|
||||
* `StopFailure` — matched against `error`
|
||||
* `ConfigChange` — matched against `source`
|
||||
* `InstructionsLoaded` — matched against `load_reason`
|
||||
* `Elicitation` / `ElicitationResult` — matched against `mcp_server_name`
|
||||
* `FileChanged` — matched against filenames (e.g., `".envrc|.env"`)
|
||||
|
||||
Omit `matcher` to run the hook for all instances of the event.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="hooks" type="HookCommand[]" required>
|
||||
One or more hook definitions to execute when the matcher fires.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## Hook types
|
||||
|
||||
### `command` — shell command
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq '.tool_name' && my-validator",
|
||||
"timeout": 30,
|
||||
"shell": "bash",
|
||||
"async": false,
|
||||
"once": false,
|
||||
"if": "Bash(git *)",
|
||||
"statusMessage": "Validating command..."
|
||||
}
|
||||
```
|
||||
|
||||
The hook input JSON is piped to the command's stdin. The `CLAUDE_ENV_FILE` environment variable is set for `CwdChanged` and `FileChanged` hooks — write `export KEY=value` lines there to inject environment variables into subsequent Bash tool calls.
|
||||
|
||||
<ResponseField name="command" type="string" required>
|
||||
Shell command to execute.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="timeout" type="number">
|
||||
Timeout in seconds. Defaults to the global hook timeout (60 s).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="shell" type="'bash' | 'powershell'">
|
||||
Shell interpreter. `bash` uses your `$SHELL` (bash/zsh/sh). Defaults to `bash`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="async" type="boolean">
|
||||
When `true`, the hook runs in the background without blocking Claude. Output is ignored.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="asyncRewake" type="boolean">
|
||||
When `true`, the hook runs in the background but wakes the model if it exits with code 2. Implies `async: true`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="once" type="boolean">
|
||||
When `true`, the hook runs once and is removed from the configuration after execution.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="if" type="string">
|
||||
Permission rule syntax (e.g., `"Bash(git *)"`) evaluated against the hook input. The hook is skipped if the condition does not match. Avoids spawning processes for non-matching tool calls.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="statusMessage" type="string">
|
||||
Custom message shown in the spinner while the hook runs.
|
||||
</ResponseField>
|
||||
|
||||
### `prompt` — LLM evaluation
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "prompt",
|
||||
"prompt": "Check whether this bash command is safe: $ARGUMENTS",
|
||||
"model": "claude-haiku-4-5",
|
||||
"timeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
The `$ARGUMENTS` placeholder is replaced with the hook input JSON. The model's response is treated as the hook output.
|
||||
|
||||
<ResponseField name="prompt" type="string" required>
|
||||
Prompt sent to the model. Use `$ARGUMENTS` to embed the hook input.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="model" type="string">
|
||||
Model to use. Defaults to the small fast model.
|
||||
</ResponseField>
|
||||
|
||||
### `agent` — agentic verifier
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "agent",
|
||||
"prompt": "Verify that unit tests ran and passed.",
|
||||
"model": "claude-haiku-4-5",
|
||||
"timeout": 120
|
||||
}
|
||||
```
|
||||
|
||||
Runs a short agentic loop that can call tools to verify the action. Use for `PostToolUse` hooks where you want the verifier to read files or run commands.
|
||||
|
||||
<ResponseField name="prompt" type="string" required>
|
||||
Verification prompt. Use `$ARGUMENTS` to embed the hook input.
|
||||
</ResponseField>
|
||||
|
||||
### `http` — HTTP endpoint
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "http",
|
||||
"url": "https://my-server.example.com/hook",
|
||||
"headers": {
|
||||
"Authorization": "Bearer $MY_TOKEN"
|
||||
},
|
||||
"allowedEnvVars": ["MY_TOKEN"],
|
||||
"timeout": 10
|
||||
}
|
||||
```
|
||||
|
||||
POSTs the hook input JSON to the given URL. Header values can reference environment variables using `$VAR_NAME` syntax, but only variables listed in `allowedEnvVars` are interpolated.
|
||||
|
||||
<ResponseField name="url" type="string" required>
|
||||
URL to POST the hook input JSON to.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="headers" type="Record<string, string>">
|
||||
Additional request headers.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="allowedEnvVars" type="string[]">
|
||||
Environment variable names that may be interpolated in header values.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## Base hook input
|
||||
|
||||
Every hook receives a JSON object on stdin with these fields present for all event types.
|
||||
|
||||
<ResponseField name="hook_event_name" type="string" required>
|
||||
The event that fired (e.g., `"PreToolUse"`).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="session_id" type="string" required>
|
||||
Current session identifier.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="transcript_path" type="string" required>
|
||||
Absolute path to the JSONL transcript file for this session.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="cwd" type="string" required>
|
||||
Current working directory at the time the hook fired.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="permission_mode" type="string">
|
||||
Active permission mode (`"default"`, `"acceptEdits"`, `"bypassPermissions"`, `"plan"`, `"dontAsk"`).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="agent_id" type="string">
|
||||
Subagent identifier. Present only when the hook fires from within a subagent. Use this field to distinguish subagent calls from main-thread calls.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="agent_type" type="string">
|
||||
Agent type name (e.g., `"general-purpose"`, `"code-reviewer"`). Present when the hook fires from a subagent, or on the main thread of a session started with `--agent`.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## Sync hook output (JSON on stdout)
|
||||
|
||||
For blocking hooks, write a JSON object to stdout before exiting. The schema is the same for all events, with event-specific fields nested under `hookSpecificOutput`.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"continue": true,
|
||||
"suppressOutput": false,
|
||||
"decision": "approve",
|
||||
"reason": "Command looks safe",
|
||||
"systemMessage": "The hook approved this action.",
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": "PreToolUse",
|
||||
"permissionDecision": "allow",
|
||||
"additionalContext": "Verified by security scanner."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="continue" type="boolean">
|
||||
When `false`, Claude stops the current turn immediately.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="suppressOutput" type="boolean">
|
||||
When `true`, the hook's stdout is not shown in transcript mode.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="decision" type="'approve' | 'block'">
|
||||
Explicit approve/block decision. Takes effect only when the CLI reads it.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="systemMessage" type="string">
|
||||
Message injected into Claude's context as a system turn.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="reason" type="string">
|
||||
Human-readable reason for the decision. Shown to the user when a hook blocks an action.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="hookSpecificOutput" type="object">
|
||||
Event-specific output. See each event section below for the allowed fields.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## Hook events
|
||||
|
||||
### `PreToolUse`
|
||||
|
||||
Fires immediately before a tool executes. You can inspect the tool input, approve or block the call, or modify the input before it reaches the tool.
|
||||
|
||||
**When it fires:** Before every tool invocation.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="tool_name" type="string">
|
||||
Name of the tool about to run (e.g., `"Bash"`, `"Write"`, `"mcp__myserver__my_tool"`).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="tool_input" type="unknown">
|
||||
The raw tool input object as Claude submitted it.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="tool_use_id" type="string">
|
||||
Unique ID for this tool invocation.
|
||||
</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ----------------------------------------------------------- |
|
||||
| `0` | Stdout/stderr not shown. Hook output JSON applied if valid. |
|
||||
| `2` | Stderr shown to Claude; tool call is **blocked**. |
|
||||
| Other | Stderr shown to user only; tool call continues. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="hookEventName" type="literal: 'PreToolUse'" required>
|
||||
Must be `"PreToolUse"`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="permissionDecision" type="'allow' | 'deny' | 'ask'">
|
||||
Override the permission decision for this tool call. `"allow"` approves the call; `"deny"` blocks it; `"ask"` forces the permission dialog.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="permissionDecisionReason" type="string">
|
||||
Reason string shown to the user when the decision is `"deny"` or `"ask"`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="updatedInput" type="Record<string, unknown>">
|
||||
Replacement tool input. When provided, the tool receives this object instead of Claude's original input.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="additionalContext" type="string">
|
||||
Text injected into Claude's context for this turn.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `PostToolUse`
|
||||
|
||||
Fires after a tool completes successfully. You can observe the tool output or inject context for Claude to act on.
|
||||
|
||||
**When it fires:** After every successful tool execution.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="tool_name" type="string">Tool that ran.</ResponseField>
|
||||
<ResponseField name="tool_input" type="unknown">Input that was passed to the tool.</ResponseField>
|
||||
<ResponseField name="tool_response" type="unknown">The tool's output.</ResponseField>
|
||||
<ResponseField name="tool_use_id" type="string">Unique ID for this invocation.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ------------------------------------------------------- |
|
||||
| `0` | Stdout shown in transcript mode (Ctrl+O). |
|
||||
| `2` | Stderr shown to Claude immediately as a system message. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="additionalContext" type="string">
|
||||
Context injected into Claude's conversation after the tool result.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="updatedMCPToolOutput" type="unknown">
|
||||
Replacement for the MCP tool's output. Only effective for MCP tool calls.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `PostToolUseFailure`
|
||||
|
||||
Fires when a tool call ends in an error or is interrupted.
|
||||
|
||||
**When it fires:** When a tool throws or is aborted.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="tool_name" type="string">Tool that failed.</ResponseField>
|
||||
<ResponseField name="tool_input" type="unknown">Input that was passed to the tool.</ResponseField>
|
||||
<ResponseField name="tool_use_id" type="string">Unique ID for this invocation.</ResponseField>
|
||||
<ResponseField name="error" type="string">Error message from the tool.</ResponseField>
|
||||
<ResponseField name="is_interrupt" type="boolean">Whether the failure was caused by an interrupt signal.</ResponseField>
|
||||
|
||||
**Exit codes:** Same as `PostToolUse`. Hook output and exit codes are logged but do not affect the failed tool result.
|
||||
|
||||
***
|
||||
|
||||
### `PermissionRequest`
|
||||
|
||||
Fires when a permission dialog would be shown to the user. Hooks can programmatically approve or deny without showing any UI.
|
||||
|
||||
**When it fires:** When Claude requests permission for a tool call and the default behavior is to prompt.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="tool_name" type="string">Tool requesting permission.</ResponseField>
|
||||
<ResponseField name="tool_input" type="unknown">Input the tool would receive if approved.</ResponseField>
|
||||
<ResponseField name="permission_suggestions" type="PermissionUpdate[]">Suggested permission rules (allow/deny) that the UI would offer.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `0` | Hook decision applied if `hookSpecificOutput.decision` is set; otherwise falls through to normal dialog. |
|
||||
| Other | Stderr shown to user; falls through to normal dialog. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="hookEventName" type="literal: 'PermissionRequest'" required>
|
||||
Must be `"PermissionRequest"`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="decision" type="object">
|
||||
The approval or denial decision.
|
||||
|
||||
<Expandable title="Allow decision">
|
||||
```json theme={null}
|
||||
{
|
||||
"behavior": "allow",
|
||||
"updatedInput": { ... },
|
||||
"updatedPermissions": [...]
|
||||
}
|
||||
```
|
||||
</Expandable>
|
||||
|
||||
<Expandable title="Deny decision">
|
||||
```json theme={null}
|
||||
{
|
||||
"behavior": "deny",
|
||||
"message": "Blocked by security policy.",
|
||||
"interrupt": false
|
||||
}
|
||||
```
|
||||
|
||||
When `interrupt` is `true`, the current turn is aborted after denial.
|
||||
</Expandable>
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `PermissionDenied`
|
||||
|
||||
Fires when a tool call is denied (by rules, mode, or classifier). You can instruct Claude to retry the action.
|
||||
|
||||
**When it fires:** After every permission denial.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="tool_name" type="string">Denied tool.</ResponseField>
|
||||
<ResponseField name="tool_input" type="unknown">Input that was denied.</ResponseField>
|
||||
<ResponseField name="tool_use_id" type="string">Unique ID for this invocation.</ResponseField>
|
||||
<ResponseField name="reason" type="string">Human-readable denial reason.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | -------------------------------- |
|
||||
| `0` | Stdout shown in transcript mode. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="retry" type="boolean">
|
||||
When `true`, Claude is told it may retry the denied action.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `Stop`
|
||||
|
||||
Fires just before Claude concludes its response for the current turn.
|
||||
|
||||
**When it fires:** When the model is about to stop and return control to the user.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="stop_hook_active" type="boolean">
|
||||
Whether a Stop hook is currently running (prevents infinite loops if your Stop hook itself would trigger a Stop).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="last_assistant_message" type="string">
|
||||
Text content of the last assistant message before stopping. Saves you from parsing the transcript file.
|
||||
</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | --------------------------------------------------------------------------- |
|
||||
| `0` | Stdout/stderr not shown. |
|
||||
| `2` | Stderr injected as a system message; Claude **continues** the conversation. |
|
||||
| Other | Stderr shown to user only; Claude stops. |
|
||||
|
||||
<Tip>
|
||||
Use exit code 2 from a Stop hook to check Claude's output and keep the conversation going if a condition is unmet — for example, if tests are still failing.
|
||||
</Tip>
|
||||
|
||||
***
|
||||
|
||||
### `StopFailure`
|
||||
|
||||
Fires instead of `Stop` when the turn ends due to an API error.
|
||||
|
||||
**When it fires:** When a rate limit, authentication failure, or other API error ends the turn.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="error" type="'authentication_failed' | 'billing_error' | 'rate_limit' | 'invalid_request' | 'server_error' | 'unknown' | 'max_output_tokens'">
|
||||
The error category.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="error_details" type="string">
|
||||
Detailed error message.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="last_assistant_message" type="string">
|
||||
Last assistant message text, if any was produced before the error.
|
||||
</ResponseField>
|
||||
|
||||
**Behavior:** Fire-and-forget. Hook output and exit codes are ignored.
|
||||
|
||||
***
|
||||
|
||||
### `SubagentStart`
|
||||
|
||||
Fires when Claude spawns a subagent via the `Agent` tool.
|
||||
|
||||
**When it fires:** When an Agent tool call begins.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="agent_id" type="string">Unique ID for this subagent instance.</ResponseField>
|
||||
<ResponseField name="agent_type" type="string">Agent type name (e.g., `"general-purpose"`).</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ---------------------------------------- |
|
||||
| `0` | Stdout shown to the subagent as context. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="additionalContext" type="string">
|
||||
Context injected into the subagent's conversation at the start.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `SubagentStop`
|
||||
|
||||
Fires just before a subagent concludes its response. Mirrors `Stop` but for subagents.
|
||||
|
||||
**When it fires:** When a subagent is about to return its result to the parent.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="agent_id" type="string">Subagent instance ID.</ResponseField>
|
||||
<ResponseField name="agent_type" type="string">Agent type name.</ResponseField>
|
||||
<ResponseField name="agent_transcript_path" type="string">Path to the subagent's JSONL transcript.</ResponseField>
|
||||
<ResponseField name="stop_hook_active" type="boolean">Whether a SubagentStop hook is already running.</ResponseField>
|
||||
<ResponseField name="last_assistant_message" type="string">Last message from the subagent.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | --------------------------------------------------------- |
|
||||
| `0` | Stdout/stderr not shown. |
|
||||
| `2` | Stderr shown to subagent; subagent **continues** running. |
|
||||
| Other | Stderr shown to user only; subagent stops. |
|
||||
|
||||
***
|
||||
|
||||
### `SessionStart`
|
||||
|
||||
Fires when a session begins. Use this to inject initial context or set up the environment.
|
||||
|
||||
**When it fires:** On session startup, resume, clear (`/clear`), or after compaction.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="source" type="'startup' | 'resume' | 'clear' | 'compact'">
|
||||
What triggered the session start.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="model" type="string">Active model for the session.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ------------------------------------------ |
|
||||
| `0` | Stdout shown to Claude as initial context. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="additionalContext" type="string">
|
||||
Context injected into Claude's system prompt for this session.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="initialUserMessage" type="string">
|
||||
Auto-submitted as the first user message of the session.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="watchPaths" type="string[]">
|
||||
Absolute file paths to register with the `FileChanged` watcher.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `SessionEnd`
|
||||
|
||||
Fires when a session is about to end.
|
||||
|
||||
**When it fires:** On clear, logout, prompt-input exit, or other termination reasons.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="reason" type="'clear' | 'resume' | 'logout' | 'prompt_input_exit' | 'other' | 'bypass_permissions_disabled'">
|
||||
The reason the session is ending.
|
||||
</ResponseField>
|
||||
|
||||
**Exit codes:** Exit code 0 completes successfully. Other exit codes show stderr to the user.
|
||||
|
||||
***
|
||||
|
||||
### `Setup`
|
||||
|
||||
Fires during repository initialization and maintenance checks.
|
||||
|
||||
**When it fires:** On `init` (first time Claude Code runs in a directory) or `maintenance` (periodic checks).
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="trigger" type="'init' | 'maintenance'">
|
||||
What triggered the setup hook.
|
||||
</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ------------------------------------------------------- |
|
||||
| `0` | Stdout shown to Claude. |
|
||||
| Other | Stderr shown to user only. Blocking errors are ignored. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="additionalContext" type="string">
|
||||
Context provided to Claude for the setup phase.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `PreCompact`
|
||||
|
||||
Fires before context compaction begins.
|
||||
|
||||
**When it fires:** Before the compaction summary is generated, whether triggered manually (`/compact`) or automatically.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="trigger" type="'manual' | 'auto'">Whether compaction was requested by the user or triggered automatically.</ResponseField>
|
||||
<ResponseField name="custom_instructions" type="string | null">Any custom compaction instructions already configured.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | -------------------------------------------------- |
|
||||
| `0` | Stdout appended as custom compaction instructions. |
|
||||
| `2` | Compaction is **blocked**. |
|
||||
| Other | Stderr shown to user; compaction continues. |
|
||||
|
||||
***
|
||||
|
||||
### `PostCompact`
|
||||
|
||||
Fires after compaction completes.
|
||||
|
||||
**When it fires:** After the compaction summary has been generated and applied.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="trigger" type="'manual' | 'auto'">How compaction was triggered.</ResponseField>
|
||||
<ResponseField name="compact_summary" type="string">The summary produced by compaction.</ResponseField>
|
||||
|
||||
**Exit codes:** Exit code 0 shows stdout to the user. Other exit codes show stderr to the user.
|
||||
|
||||
***
|
||||
|
||||
### `UserPromptSubmit`
|
||||
|
||||
Fires when the user submits a prompt, before Claude processes it.
|
||||
|
||||
**When it fires:** Each time you press Enter with a message in the terminal.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="prompt" type="string">The raw prompt text the user submitted.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | --------------------------------------------------------------------- |
|
||||
| `0` | Stdout shown to Claude as additional context. |
|
||||
| `2` | Processing **blocked**; original prompt erased; stderr shown to user. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="additionalContext" type="string">
|
||||
Context appended to Claude's view of the user message.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `Notification`
|
||||
|
||||
Fires when Claude Code sends a notification (e.g., permission prompts, idle alerts).
|
||||
|
||||
**When it fires:** When a notification event is raised internally.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="message" type="string">Notification message text.</ResponseField>
|
||||
<ResponseField name="title" type="string">Notification title.</ResponseField>
|
||||
|
||||
<ResponseField name="notification_type" type="'permission_prompt' | 'idle_prompt' | 'auth_success' | 'elicitation_dialog' | 'elicitation_complete' | 'elicitation_response'">
|
||||
The type of notification.
|
||||
</ResponseField>
|
||||
|
||||
**Exit codes:** Exit code 0 produces no output. Other exit codes show stderr to the user.
|
||||
|
||||
***
|
||||
|
||||
### `Elicitation`
|
||||
|
||||
Fires when an MCP server requests user input. Hooks can auto-respond without showing the dialog.
|
||||
|
||||
**When it fires:** When an MCP server sends an elicitation request (a structured input form or URL).
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="mcp_server_name" type="string">Name of the MCP server requesting input.</ResponseField>
|
||||
<ResponseField name="message" type="string">The prompt message from the server.</ResponseField>
|
||||
<ResponseField name="mode" type="'form' | 'url'">Input mode.</ResponseField>
|
||||
<ResponseField name="elicitation_id" type="string">Request identifier.</ResponseField>
|
||||
<ResponseField name="requested_schema" type="Record<string, unknown>">JSON schema describing the expected input structure.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ----------------------------------------------------------------------------- |
|
||||
| `0` | Use hook response if `hookSpecificOutput` is provided; otherwise show dialog. |
|
||||
| `2` | Deny the elicitation. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="action" type="'accept' | 'decline' | 'cancel'">
|
||||
The programmatic response to the elicitation.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="content" type="Record<string, unknown>">
|
||||
Form data to submit when `action` is `"accept"`.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `ElicitationResult`
|
||||
|
||||
Fires after a user responds to an MCP elicitation. Hooks can observe or override the response.
|
||||
|
||||
**When it fires:** After the user (or an Elicitation hook) responds to the elicitation.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="mcp_server_name" type="string">Name of the MCP server.</ResponseField>
|
||||
<ResponseField name="elicitation_id" type="string">Request identifier.</ResponseField>
|
||||
<ResponseField name="action" type="'accept' | 'decline' | 'cancel'">How the user responded.</ResponseField>
|
||||
<ResponseField name="content" type="Record<string, unknown>">Submitted form data, if accepted.</ResponseField>
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="action" type="'accept' | 'decline' | 'cancel'">
|
||||
Override the user's action before it is sent to the server.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="content" type="Record<string, unknown>">
|
||||
Override the submitted content.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
### `ConfigChange`
|
||||
|
||||
Fires when a settings file changes during a session.
|
||||
|
||||
**When it fires:** When `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills` files are modified on disk.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="source" type="'user_settings' | 'project_settings' | 'local_settings' | 'policy_settings' | 'skills'">
|
||||
Which settings source changed.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="file_path" type="string">Absolute path to the changed file.</ResponseField>
|
||||
|
||||
**Exit codes:**
|
||||
|
||||
| Exit code | Effect |
|
||||
| --------- | ------------------------------------------------------- |
|
||||
| `0` | Allow the change to be applied. |
|
||||
| `2` | **Block** the change from being applied to the session. |
|
||||
| Other | Stderr shown to user only. |
|
||||
|
||||
***
|
||||
|
||||
### `InstructionsLoaded`
|
||||
|
||||
Fires when a CLAUDE.md or instruction rule file is loaded. This event is observability-only.
|
||||
|
||||
**When it fires:** When any instruction file is loaded into context.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="file_path" type="string">Path to the loaded file.</ResponseField>
|
||||
<ResponseField name="memory_type" type="'User' | 'Project' | 'Local' | 'Managed'">The memory scope of the file.</ResponseField>
|
||||
<ResponseField name="load_reason" type="'session_start' | 'nested_traversal' | 'path_glob_match' | 'include' | 'compact'">Why the file was loaded.</ResponseField>
|
||||
<ResponseField name="globs" type="string[]">The `paths:` frontmatter patterns that matched (if `load_reason` is `path_glob_match`).</ResponseField>
|
||||
<ResponseField name="trigger_file_path" type="string">The file Claude accessed that caused this load (for `path_glob_match`).</ResponseField>
|
||||
<ResponseField name="parent_file_path" type="string">The file that `@include`d this one (for `include`).</ResponseField>
|
||||
|
||||
**Behavior:** Blocking not supported. Exit code 0 completes normally. Other exit codes show stderr to the user.
|
||||
|
||||
***
|
||||
|
||||
### `WorktreeCreate`
|
||||
|
||||
Fires when Claude Code needs to create an isolated worktree. The hook is responsible for actually creating the worktree and reporting its path.
|
||||
|
||||
**When it fires:** When worktree isolation is requested for a task.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="name" type="string">Suggested slug for the worktree directory.</ResponseField>
|
||||
|
||||
**Behavior:** Write the absolute path of the created worktree directory to stdout and exit with code 0. Any other exit code signals a failure.
|
||||
|
||||
***
|
||||
|
||||
### `WorktreeRemove`
|
||||
|
||||
Fires when Claude Code needs to remove a previously created worktree.
|
||||
|
||||
**When it fires:** When a worktree task completes and the worktree should be cleaned up.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="worktree_path" type="string">Absolute path of the worktree to remove.</ResponseField>
|
||||
|
||||
**Behavior:** Exit code 0 means success. Other exit codes show stderr to the user.
|
||||
|
||||
***
|
||||
|
||||
### `CwdChanged`
|
||||
|
||||
Fires after the working directory changes.
|
||||
|
||||
**When it fires:** When Claude changes directories during a session.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="old_cwd" type="string">Previous working directory.</ResponseField>
|
||||
<ResponseField name="new_cwd" type="string">New working directory.</ResponseField>
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="watchPaths" type="string[]">
|
||||
Absolute paths to add to the `FileChanged` watcher. Return this to start watching files in the new directory.
|
||||
</ResponseField>
|
||||
|
||||
The `CLAUDE_ENV_FILE` environment variable is set — write `export KEY=value` lines to apply environment variables to subsequent Bash tool commands.
|
||||
|
||||
***
|
||||
|
||||
### `FileChanged`
|
||||
|
||||
Fires when a watched file is modified, added, or removed.
|
||||
|
||||
**When it fires:** When a file registered via `SessionStart.watchPaths` or `CwdChanged.watchPaths` changes on disk.
|
||||
|
||||
**Input fields:**
|
||||
|
||||
<ResponseField name="file_path" type="string">Absolute path of the changed file.</ResponseField>
|
||||
<ResponseField name="event" type="'change' | 'add' | 'unlink'">The type of filesystem event.</ResponseField>
|
||||
|
||||
**`hookSpecificOutput` fields:**
|
||||
|
||||
<ResponseField name="watchPaths" type="string[]">
|
||||
Update the watch list with these absolute paths.
|
||||
</ResponseField>
|
||||
|
||||
The `CLAUDE_ENV_FILE` environment variable is set for this hook as well.
|
||||
|
||||
***
|
||||
|
||||
## Async hooks
|
||||
|
||||
For hooks that need to run in the background without delaying Claude, output an async acknowledgment on stdout instead of the normal sync output:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"async": true,
|
||||
"asyncTimeout": 30
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="async" type="literal: true" required>
|
||||
Signals that this hook is running asynchronously.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="asyncTimeout" type="number">
|
||||
How long (in seconds) the async hook is allowed to run before it is cancelled.
|
||||
</ResponseField>
|
||||
|
||||
<Warning>
|
||||
Async hooks cannot block tool execution or inject context. Use them for side effects like notifications, logging, or metrics that must not slow down the agentic loop.
|
||||
</Warning>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
517
docs/claude-code-docs-main/en/reference/sdk/overview.md
Normal file
517
docs/claude-code-docs-main/en/reference/sdk/overview.md
Normal file
@@ -0,0 +1,517 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# SDK overview
|
||||
|
||||
> Embed Claude Code in your own tools using the stdin/stdout control protocol. Reference for the SDK session API, message types, and output formats.
|
||||
|
||||
The Claude Code SDK is a control protocol for embedding Claude Code in other applications — IDEs, automation scripts, CI/CD pipelines, or any host that can spawn a subprocess and communicate over stdin/stdout.
|
||||
|
||||
Rather than exposing a library API directly, the SDK communicates with a running `claude` process over a structured JSON message stream. The host process sends user messages and control requests; the CLI process streams back assistant messages, tool progress events, and result payloads.
|
||||
|
||||
<Note>
|
||||
The TypeScript types described on this page are exported from `@anthropic-ai/claude-code` under the `agentSdkTypes` entry point. Control protocol types (prefixed `SDKControl`) are `@alpha` and subject to change.
|
||||
</Note>
|
||||
|
||||
## How it works
|
||||
|
||||
<Steps>
|
||||
<Step title="Spawn a Claude Code process">
|
||||
Start `claude` with `--output-format stream-json` and `--print` (non-interactive mode). Pipe its stdin and stdout into your host process.
|
||||
|
||||
```bash theme={null}
|
||||
claude --output-format stream-json --print --verbose
|
||||
```
|
||||
|
||||
For a persistent session that accepts multiple prompts over time, omit `--print` and instead send `SDKUserMessage` objects to stdin after the session initializes.
|
||||
</Step>
|
||||
|
||||
<Step title="Send an initialize request">
|
||||
Write a `control_request` with `subtype: "initialize"` to stdin. The CLI responds with an `SDKControlInitializeResponse` containing available commands, models, agents, and account information.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "init-1",
|
||||
"request": {
|
||||
"subtype": "initialize",
|
||||
"systemPrompt": "You are a code reviewer.",
|
||||
"appendSystemPrompt": "Always suggest tests."
|
||||
}
|
||||
}
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Stream messages from stdout">
|
||||
Read newline-delimited JSON from stdout. Each line is one of the `SDKMessage` union types — assistant turns, tool progress, system events, and result summaries.
|
||||
</Step>
|
||||
|
||||
<Step title="Send user messages">
|
||||
Write `SDKUserMessage` objects to stdin to continue the conversation. Each message contains an Anthropic API-compatible `message` payload.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Output formats
|
||||
|
||||
Pass `--output-format` to control what Claude Code writes to stdout.
|
||||
|
||||
| Format | Description |
|
||||
| ------------- | --------------------------------------------------------------------------------------------------- |
|
||||
| `text` | Plain text responses only. Default for interactive mode. |
|
||||
| `json` | Single JSON object written at completion. Suitable for one-shot scripts. |
|
||||
| `stream-json` | Newline-delimited JSON stream. One message per line, emitted as events occur. Required for SDK use. |
|
||||
|
||||
<Tip>
|
||||
Use `stream-json` when you need to render progress incrementally or handle tool events. Use `json` when you only care about the final result.
|
||||
</Tip>
|
||||
|
||||
## Control protocol messages
|
||||
|
||||
The control protocol uses two top-level envelope types that flow bidirectionally over stdin/stdout.
|
||||
|
||||
### `SDKControlRequest`
|
||||
|
||||
Sent **to** the CLI process to configure the session or issue commands.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "<unique-string>",
|
||||
"request": { "subtype": "...", ...payload }
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="type" type="literal: 'control_request'" required>
|
||||
Always `"control_request"`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="request_id" type="string" required>
|
||||
Unique identifier for this request. The CLI echoes it back in the corresponding `control_response`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="request" type="SDKControlRequestInner" required>
|
||||
The request payload. `subtype` identifies which operation to perform.
|
||||
</ResponseField>
|
||||
|
||||
### `SDKControlResponse`
|
||||
|
||||
Emitted **from** the CLI process in response to a `control_request`.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_response",
|
||||
"response": {
|
||||
"subtype": "success",
|
||||
"request_id": "<echoed-id>",
|
||||
"response": { ...payload }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
On error, `subtype` is `"error"` and the `error` field contains a human-readable message.
|
||||
|
||||
***
|
||||
|
||||
## Initialize request and response
|
||||
|
||||
The `initialize` request is the first control message you must send. It configures the session and returns available capabilities.
|
||||
|
||||
### `SDKControlInitializeRequest`
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "init-1",
|
||||
"request": {
|
||||
"subtype": "initialize",
|
||||
"systemPrompt": "You are a CI automation agent.",
|
||||
"appendSystemPrompt": "Always add test coverage.",
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hookCallbackIds": ["my-hook-id"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"agents": {
|
||||
"CodeReviewer": {
|
||||
"description": "Reviews code for quality and security.",
|
||||
"prompt": "You are an expert code reviewer...",
|
||||
"model": "opus"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="subtype" type="literal: 'initialize'" required>
|
||||
Identifies this as an initialize request.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="systemPrompt" type="string">
|
||||
Replaces the default system prompt for this session.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="appendSystemPrompt" type="string">
|
||||
Appended to the system prompt without replacing it. Use this to add context while keeping the default behavior.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="hooks" type="Record<HookEvent, SDKHookCallbackMatcher[]>">
|
||||
Registers SDK-side hook callbacks. The CLI calls back into the SDK process when hook events fire. See [Hooks reference](/reference/sdk/hooks-reference).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="sdkMcpServers" type="string[]">
|
||||
Names of in-process SDK MCP servers (created with `createSdkMcpServer`) to connect to this session.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="agents" type="Record<string, AgentDefinition>">
|
||||
Custom subagent definitions available to the `Agent` tool during this session.
|
||||
|
||||
<Expandable title="AgentDefinition fields">
|
||||
<ResponseField name="description" type="string" required>
|
||||
Natural language description of when Claude should invoke this agent.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="prompt" type="string" required>
|
||||
System prompt for this agent.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="model" type="string">
|
||||
Model alias (`"sonnet"`, `"opus"`, `"haiku"`) or full model ID. Defaults to inheriting the parent model.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="tools" type="string[]">
|
||||
Allow-list of tool names. When omitted, the agent inherits all tools.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="disallowedTools" type="string[]">
|
||||
Tools explicitly blocked for this agent.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="maxTurns" type="number">
|
||||
Maximum agentic turns before the agent stops.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="permissionMode" type="PermissionMode">
|
||||
Override permission mode for this agent. See [Permissions API](/reference/sdk/permissions-api).
|
||||
</ResponseField>
|
||||
</Expandable>
|
||||
</ResponseField>
|
||||
|
||||
### `SDKControlInitializeResponse`
|
||||
|
||||
The CLI responds with the session's current capabilities.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_response",
|
||||
"response": {
|
||||
"subtype": "success",
|
||||
"request_id": "init-1",
|
||||
"response": {
|
||||
"commands": [...],
|
||||
"agents": [...],
|
||||
"output_style": "stream-json",
|
||||
"available_output_styles": ["text", "json", "stream-json"],
|
||||
"models": [...],
|
||||
"account": {
|
||||
"email": "user@example.com",
|
||||
"organization": "Acme Corp",
|
||||
"apiProvider": "firstParty"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="commands" type="SlashCommand[]">
|
||||
Available slash commands (e.g., `/compact`, `/cost`). Each entry has `name`, `description`, and `argumentHint`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="agents" type="AgentInfo[]">
|
||||
Available subagent types. Each has `name`, `description`, and an optional `model`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="output_style" type="string">
|
||||
The active output format (`"stream-json"`, `"json"`, `"text"`).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="models" type="ModelInfo[]">
|
||||
Available models for this account.
|
||||
|
||||
<Expandable title="ModelInfo fields">
|
||||
<ResponseField name="value" type="string">
|
||||
Model identifier for API calls (e.g., `"claude-sonnet-4-6"`).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="displayName" type="string">
|
||||
Human-readable name (e.g., `"Claude Sonnet 4.6"`).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="supportsEffort" type="boolean">
|
||||
Whether this model supports effort levels.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="supportsAdaptiveThinking" type="boolean">
|
||||
Whether this model supports adaptive thinking (Claude decides when and how much to think).
|
||||
</ResponseField>
|
||||
</Expandable>
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="account" type="AccountInfo">
|
||||
Logged-in account details.
|
||||
|
||||
<Expandable title="AccountInfo fields">
|
||||
<ResponseField name="email" type="string">
|
||||
Account email address.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="organization" type="string">
|
||||
Organization name.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="subscriptionType" type="string">
|
||||
Subscription tier.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="apiProvider" type="'firstParty' | 'bedrock' | 'vertex' | 'foundry'">
|
||||
Active API backend. Anthropic OAuth only applies when `"firstParty"`.
|
||||
</ResponseField>
|
||||
</Expandable>
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## User messages
|
||||
|
||||
Send user messages to stdin to drive the conversation forward.
|
||||
|
||||
### `SDKUserMessage`
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "user",
|
||||
"message": {
|
||||
"role": "user",
|
||||
"content": "Refactor this function to use async/await."
|
||||
},
|
||||
"parent_tool_use_id": null
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="type" type="literal: 'user'" required>
|
||||
Always `"user"`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="message" type="APIUserMessage" required>
|
||||
An Anthropic API-compatible user message. `content` can be a string or a content block array (for images and other media).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="parent_tool_use_id" type="string | null" required>
|
||||
Tool use ID this message is responding to, or `null` for top-level user messages.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="uuid" type="string">
|
||||
Optional UUID to track this message. Echoed back in related events.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="priority" type="'now' | 'next' | 'later'">
|
||||
Scheduling hint for async message queuing.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## SDK message stream types
|
||||
|
||||
Claude Code emits a stream of JSON messages to stdout. The `type` field identifies each message.
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="system — session initialization">
|
||||
Emitted once at session start with `subtype: "init"`. Contains the active model, tool list, MCP server statuses, permission mode, and session ID.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "system",
|
||||
"subtype": "init",
|
||||
"model": "claude-sonnet-4-6",
|
||||
"tools": ["Bash", "Read", "Write", "Edit", "Glob", "Grep"],
|
||||
"mcp_servers": [],
|
||||
"permissionMode": "default",
|
||||
"session_id": "abc123",
|
||||
"uuid": "..."
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="assistant — model response">
|
||||
Emitted when the model produces a turn. Contains the full Anthropic API response object, including any `tool_use` blocks.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "assistant",
|
||||
"message": { "role": "assistant", "content": [...] },
|
||||
"parent_tool_use_id": null,
|
||||
"uuid": "...",
|
||||
"session_id": "abc123"
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="stream_event — partial streaming tokens">
|
||||
Emitted during streaming with `RawMessageStreamEvent` payloads. Use these to render incremental output.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="tool_progress — long-running tool status">
|
||||
Emitted periodically for tools that take more than a few seconds (e.g., Bash commands). Contains `tool_name`, `tool_use_id`, and elapsed time.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="result — final turn summary">
|
||||
Emitted at the end of each turn. `subtype` is `"success"` or one of the error subtypes.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "result",
|
||||
"subtype": "success",
|
||||
"result": "The function has been refactored.",
|
||||
"duration_ms": 4200,
|
||||
"total_cost_usd": 0.0042,
|
||||
"num_turns": 3,
|
||||
"is_error": false,
|
||||
"stop_reason": "end_turn",
|
||||
"session_id": "abc123",
|
||||
"uuid": "..."
|
||||
}
|
||||
```
|
||||
|
||||
Error subtypes: `"error_during_execution"`, `"error_max_turns"`, `"error_max_budget_usd"`, `"error_max_structured_output_retries"`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="system — status updates">
|
||||
Emitted with `subtype: "status"` when the permission mode or session status changes (e.g., `"compacting"`).
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Other control requests
|
||||
|
||||
Beyond `initialize`, the control protocol exposes these operations.
|
||||
|
||||
| `subtype` | Direction | Description |
|
||||
| --------------------- | ---------- | --------------------------------------------------------------------- |
|
||||
| `interrupt` | host → CLI | Interrupt the current turn. |
|
||||
| `set_permission_mode` | host → CLI | Change the active permission mode. |
|
||||
| `set_model` | host → CLI | Switch to a different model mid-session. |
|
||||
| `can_use_tool` | CLI → host | Permission request for a tool call (requires SDK permission handler). |
|
||||
| `mcp_status` | host → CLI | Get MCP server connection statuses. |
|
||||
| `mcp_set_servers` | host → CLI | Replace dynamically managed MCP servers. |
|
||||
| `get_context_usage` | host → CLI | Get context window usage breakdown. |
|
||||
| `get_settings` | host → CLI | Read the effective merged settings. |
|
||||
| `apply_flag_settings` | host → CLI | Merge settings into the flag settings layer. |
|
||||
| `rewind_files` | host → CLI | Revert file changes made since a given message. |
|
||||
| `hook_callback` | CLI → host | Deliver a hook event for an SDK-registered hook callback. |
|
||||
| `reload_plugins` | host → CLI | Reload plugins from disk. |
|
||||
|
||||
***
|
||||
|
||||
## Session management API
|
||||
|
||||
For scripting scenarios, the SDK exports functions that operate on saved session transcripts stored in `~/.claude/`.
|
||||
|
||||
```typescript theme={null}
|
||||
import {
|
||||
query,
|
||||
listSessions,
|
||||
getSessionInfo,
|
||||
getSessionMessages,
|
||||
forkSession,
|
||||
renameSession,
|
||||
tagSession,
|
||||
} from '@anthropic-ai/claude-code'
|
||||
```
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="query — run a prompt">
|
||||
The primary SDK entry point. Accepts a `prompt` string or `AsyncIterable<SDKUserMessage>` and returns an async iterable of `SDKMessage`.
|
||||
|
||||
```typescript theme={null}
|
||||
for await (const message of query({
|
||||
prompt: 'What files are in this directory?',
|
||||
options: { cwd: '/my/project' }
|
||||
})) {
|
||||
if (message.type === 'result') {
|
||||
console.log(message.result)
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="listSessions — list saved sessions">
|
||||
Returns session metadata for a project directory. Pass `dir` to scope to a specific project, or omit to list all sessions.
|
||||
|
||||
```typescript theme={null}
|
||||
const sessions = await listSessions({ dir: '/my/project', limit: 50 })
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="getSessionMessages — read a transcript">
|
||||
Parses the JSONL transcript file for a session and returns messages in chronological order.
|
||||
|
||||
```typescript theme={null}
|
||||
const messages = await getSessionMessages(sessionId, {
|
||||
dir: '/my/project',
|
||||
includeSystemMessages: false,
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="forkSession — branch a conversation">
|
||||
Copies a session's transcript into a new session with remapped UUIDs. Supports `upToMessageId` to fork from a specific point.
|
||||
|
||||
```typescript theme={null}
|
||||
const { sessionId: newId } = await forkSession(originalSessionId, {
|
||||
upToMessageId: 'msg-uuid',
|
||||
title: 'Experimental branch',
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="renameSession and tagSession">
|
||||
```typescript theme={null}
|
||||
await renameSession(sessionId, 'My refactor session')
|
||||
await tagSession(sessionId, 'needs-review')
|
||||
await tagSession(sessionId, null) // clear tag
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
***
|
||||
|
||||
## Use cases
|
||||
|
||||
<Tabs>
|
||||
<Tab title="IDE integration">
|
||||
IDEs can spawn a persistent Claude Code process and route messages through the control protocol. Send the `initialize` request with a custom `systemPrompt` that describes the IDE context, then forward user messages from the editor's chat panel. Use `PreToolUse` hook callbacks to intercept file edits and display diffs in the IDE's native UI before they are applied.
|
||||
</Tab>
|
||||
|
||||
<Tab title="CI/CD automation">
|
||||
In CI pipelines, use `--output-format json` and `--print` for one-shot tasks:
|
||||
|
||||
```bash theme={null}
|
||||
result=$(echo "Review the diff and output pass/fail" | \
|
||||
claude --output-format json --print \
|
||||
--permission-mode bypassPermissions)
|
||||
```
|
||||
|
||||
Parse the `result` field from the JSON output to extract the agent's response programmatically.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Headless agents">
|
||||
For long-running background agents, use `query()` from the TypeScript SDK with a streaming output format. Combine with `watchScheduledTasks` (internal) to fire tasks on cron schedules while keeping a persistent daemon process that maintains the WebSocket connection to claude.ai.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
473
docs/claude-code-docs-main/en/reference/sdk/permissions-api.md
Normal file
473
docs/claude-code-docs-main/en/reference/sdk/permissions-api.md
Normal file
@@ -0,0 +1,473 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Permissions API
|
||||
|
||||
> Reference for permission modes, allow/deny rule syntax, and configuration methods for controlling which tools Claude Code can use without prompting.
|
||||
|
||||
The permissions system controls whether Claude Code runs a tool immediately, prompts you for confirmation, or blocks the call entirely. You configure it through permission modes and rule lists that can be set globally, per project, or per session.
|
||||
|
||||
## Permission modes
|
||||
|
||||
A permission mode sets the baseline behavior for all tool calls. Individual allow/deny rules can override this baseline for specific tools or commands.
|
||||
|
||||
| Mode | Description |
|
||||
| ------------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `default` | Prompt for approval on potentially dangerous operations. Safe read-only tools run without prompting. |
|
||||
| `acceptEdits` | Auto-approve all file edit operations (`Write`, `Edit`, `MultiEdit`). Bash commands still prompt. |
|
||||
| `bypassPermissions` | Skip all permission checks. All tools run without prompting. Requires `allowDangerouslySkipPermissions: true` in settings. |
|
||||
| `plan` | Read-only planning mode. No tool execution; Claude can only read files and explain what it would do. |
|
||||
| `dontAsk` | Do not prompt the user. Deny any tool call that is not pre-approved by an explicit allow rule. |
|
||||
|
||||
<Warning>
|
||||
`bypassPermissions` mode disables all safeguards. Only use it in sandboxed environments or CI pipelines where you fully control the input. The mode requires `allowDangerouslySkipPermissions: true` in your settings file.
|
||||
</Warning>
|
||||
|
||||
### Setting the permission mode
|
||||
|
||||
<Tabs>
|
||||
<Tab title="CLI flag">
|
||||
Pass `--permission-mode` to set the mode for a single invocation:
|
||||
|
||||
```bash theme={null}
|
||||
claude --permission-mode acceptEdits
|
||||
claude --permission-mode bypassPermissions --dangerously-skip-permissions
|
||||
claude --permission-mode plan
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Settings file">
|
||||
Set `defaultPermissionMode` in any Claude Code settings file to make it the default for all sessions in that scope:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"defaultPermissionMode": "acceptEdits"
|
||||
}
|
||||
```
|
||||
|
||||
Settings files load in this priority order (highest wins):
|
||||
|
||||
* `.claude/settings.local.json` — local overrides, not committed
|
||||
* `.claude/settings.json` — project-level defaults
|
||||
* `~/.claude/settings.json` — user-level defaults
|
||||
</Tab>
|
||||
|
||||
<Tab title="/permissions command">
|
||||
Run `/permissions` inside a session to open the interactive permissions panel where you can view and edit allow/deny rules. Session-level changes are not persisted to disk.
|
||||
|
||||
```
|
||||
/permissions
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="SDK control request">
|
||||
Change the permission mode programmatically via the control protocol:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "pm-1",
|
||||
"request": {
|
||||
"subtype": "set_permission_mode",
|
||||
"mode": "acceptEdits"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
***
|
||||
|
||||
## Permission rules
|
||||
|
||||
Rules let you pre-approve or block specific tools and commands without changing the global permission mode. Rules are additive across settings scopes — allow rules from all files merge together.
|
||||
|
||||
### Configuration format
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git *)",
|
||||
"Bash(npm run *)",
|
||||
"Read",
|
||||
"Write(src/**)",
|
||||
"mcp__myserver"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(rm -rf *)",
|
||||
"Bash(curl * | bash)",
|
||||
"Write(/etc/**)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="allow" type="string[]">
|
||||
Rules that auto-approve matching tool calls without prompting.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="deny" type="string[]">
|
||||
Rules that unconditionally block matching tool calls.
|
||||
</ResponseField>
|
||||
|
||||
<Note>
|
||||
Deny rules always take precedence over allow rules. If both an allow rule and a deny rule match a tool call, the call is blocked.
|
||||
</Note>
|
||||
|
||||
### Rule syntax
|
||||
|
||||
A rule is a string that matches a tool name, optionally with a parenthesized content pattern.
|
||||
|
||||
**Tool name only** — matches every call to that tool:
|
||||
|
||||
```
|
||||
Read
|
||||
Write
|
||||
Edit
|
||||
Bash
|
||||
```
|
||||
|
||||
**Tool name with content pattern** — matches calls where the tool's primary input matches the glob:
|
||||
|
||||
```
|
||||
Bash(git *)
|
||||
Bash(npm run *)
|
||||
Write(src/*)
|
||||
Edit(*.ts)
|
||||
```
|
||||
|
||||
For `Bash`, the pattern is matched against the full command string. For file tools (`Write`, `Edit`, `Read`, `Glob`), the pattern is matched against the file path argument.
|
||||
|
||||
**MCP server** — matches all tools from a specific MCP server:
|
||||
|
||||
```
|
||||
mcp__myserver
|
||||
```
|
||||
|
||||
**MCP server wildcard** — same as above, explicit wildcard form:
|
||||
|
||||
```
|
||||
mcp__myserver__*
|
||||
```
|
||||
|
||||
**Specific MCP tool** — matches one tool from a server:
|
||||
|
||||
```
|
||||
mcp__myserver__query_database
|
||||
```
|
||||
|
||||
**Agent type** — blocks or allows a specific subagent:
|
||||
|
||||
```
|
||||
Agent(Explore)
|
||||
Agent(CodeReviewer)
|
||||
```
|
||||
|
||||
### Pattern matching for `Bash`
|
||||
|
||||
Bash rule patterns use shell-style glob matching on the full command string.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git status)",
|
||||
"Bash(git log *)",
|
||||
"Bash(git diff *)",
|
||||
"Bash(npm run test*)",
|
||||
"Bash(make *)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(rm *)",
|
||||
"Bash(sudo *)",
|
||||
"Bash(* | bash)",
|
||||
"Bash(* | sh)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Bash patterns match prefix-first. A rule like `Bash(git *)` matches `git status`, `git log --oneline`, and `git push --force`. Be specific when writing deny rules.
|
||||
</Warning>
|
||||
|
||||
### Pattern matching for file tools
|
||||
|
||||
File path patterns are matched against the absolute path of the file being read, written, or edited.
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Write(src/**)",
|
||||
"Write(tests/**)",
|
||||
"Edit(*.md)",
|
||||
"Read"
|
||||
],
|
||||
"deny": [
|
||||
"Write(/etc/**)",
|
||||
"Write(~/.ssh/**)",
|
||||
"Edit(.env*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Permission rule sources and priority
|
||||
|
||||
Rules are collected from multiple sources and evaluated in a defined order. When the same tool call matches rules from different sources, deny takes precedence over allow, and the most restrictive result wins.
|
||||
|
||||
| Source | Where configured | Editable |
|
||||
| ----------------- | -------------------------------------------- | -------------- |
|
||||
| `policySettings` | Managed policy layer | No |
|
||||
| `flagSettings` | CLI flags and SDK control requests | Per-session |
|
||||
| `userSettings` | `~/.claude/settings.json` | Yes |
|
||||
| `projectSettings` | `.claude/settings.json` | Yes |
|
||||
| `localSettings` | `.claude/settings.local.json` | Yes |
|
||||
| `cliArg` | `--allowedTools` / `--disallowedTools` flags | Per-invocation |
|
||||
| `session` | `/permissions` command, SDK updates | Per-session |
|
||||
|
||||
### `--allowedTools` and `--disallowedTools` CLI flags
|
||||
|
||||
Pass comma-separated rule strings directly on the command line:
|
||||
|
||||
```bash theme={null}
|
||||
claude --allowedTools "Bash(git *),Read,Write" --print "Run the tests"
|
||||
claude --disallowedTools "Bash,Write" --print "Summarize this project"
|
||||
```
|
||||
|
||||
These map to the `cliArg` source and apply for the duration of the invocation.
|
||||
|
||||
***
|
||||
|
||||
## Permission decisions
|
||||
|
||||
The permission engine evaluates each tool call through a pipeline and returns one of three outcomes.
|
||||
|
||||
| Decision | Meaning |
|
||||
| -------- | ------------------------------------------------------ |
|
||||
| `allow` | Tool runs immediately. |
|
||||
| `ask` | User is prompted for confirmation. |
|
||||
| `deny` | Tool call is blocked; Claude receives an error result. |
|
||||
|
||||
### Decision pipeline
|
||||
|
||||
Claude Code evaluates tool calls in this order:
|
||||
|
||||
1. **Deny rules** — if any deny rule matches, the call is blocked immediately.
|
||||
2. **Ask rules** — if any ask rule matches, the permission dialog is shown.
|
||||
3. **Tool's own permission check** — the tool's `checkPermissions` method runs (e.g., Bash checks individual subcommands).
|
||||
4. **Safety checks** — paths inside `.git/`, `.claude/`, `.vscode/`, and shell config files always prompt, even in `bypassPermissions` mode.
|
||||
5. **Mode check** — `bypassPermissions` and plan mode apply here.
|
||||
6. **Allow rules** — if an allow rule matches, the call is approved.
|
||||
7. **Default behavior** — if no rule matched, prompt the user.
|
||||
|
||||
<Note>
|
||||
Safety checks (step 4) are bypass-immune. Even with `bypassPermissions` mode, Claude Code will prompt before modifying files in `.git/` or shell configuration files like `~/.bashrc`.
|
||||
</Note>
|
||||
|
||||
***
|
||||
|
||||
## Working directories
|
||||
|
||||
By default, Claude Code restricts file operations to the current working directory and its subdirectories. You can grant access to additional directories.
|
||||
|
||||
### Via CLI flag
|
||||
|
||||
```bash theme={null}
|
||||
claude --add-dir /path/to/extra/dir
|
||||
```
|
||||
|
||||
### Via settings
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"permissions": {
|
||||
"additionalDirectories": [
|
||||
"/shared/data",
|
||||
"/home/user/configs"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Via SDK control request
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_request",
|
||||
"request_id": "dirs-1",
|
||||
"request": {
|
||||
"subtype": "apply_flag_settings",
|
||||
"settings": {
|
||||
"permissions": {
|
||||
"additionalDirectories": ["/shared/data"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## Permission updates via the SDK
|
||||
|
||||
SDK hosts (IDEs, desktop apps) can respond to `can_use_tool` control requests and include permission updates to persist rule changes alongside their decisions.
|
||||
|
||||
### `PermissionUpdate` object
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "addRules",
|
||||
"rules": [
|
||||
{ "toolName": "Bash", "ruleContent": "git *" }
|
||||
],
|
||||
"behavior": "allow",
|
||||
"destination": "userSettings"
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="type" type="'addRules' | 'replaceRules' | 'removeRules' | 'setMode' | 'addDirectories' | 'removeDirectories'" required>
|
||||
The update operation.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="rules" type="PermissionRuleValue[]">
|
||||
Rules to add, replace, or remove. Each rule has `toolName` and an optional `ruleContent` (the parenthesized pattern).
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="behavior" type="'allow' | 'deny' | 'ask'" required>
|
||||
Which rule list to modify.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="destination" type="'userSettings' | 'projectSettings' | 'localSettings' | 'session' | 'cliArg'" required>
|
||||
Where to persist the update. `session` applies only to the current session; `userSettings`, `projectSettings`, and `localSettings` write to the corresponding settings files on disk.
|
||||
</ResponseField>
|
||||
|
||||
### Permission decision response
|
||||
|
||||
When responding to a `can_use_tool` request, include `updatedPermissions` to persist rule changes:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"type": "control_response",
|
||||
"response": {
|
||||
"subtype": "success",
|
||||
"request_id": "<request_id>",
|
||||
"response": {
|
||||
"behavior": "allow",
|
||||
"updatedPermissions": [
|
||||
{
|
||||
"type": "addRules",
|
||||
"rules": [{ "toolName": "Bash", "ruleContent": "git *" }],
|
||||
"behavior": "allow",
|
||||
"destination": "userSettings"
|
||||
}
|
||||
],
|
||||
"decisionClassification": "user_permanent"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<ResponseField name="behavior" type="'allow' | 'deny'" required>
|
||||
The permission decision.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="updatedInput" type="Record<string, unknown>">
|
||||
Modified tool input to use instead of the original. Only valid when `behavior` is `"allow"`.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="updatedPermissions" type="PermissionUpdate[]">
|
||||
Permission rule updates to apply and persist alongside this decision.
|
||||
</ResponseField>
|
||||
|
||||
<ResponseField name="decisionClassification" type="'user_temporary' | 'user_permanent' | 'user_reject'">
|
||||
How the user responded, for telemetry. `user_temporary` for allow-once; `user_permanent` for always-allow; `user_reject` for deny.
|
||||
</ResponseField>
|
||||
|
||||
***
|
||||
|
||||
## Hooks and permissions
|
||||
|
||||
`PreToolUse` and `PermissionRequest` hooks can inject permission decisions programmatically. See [Hooks reference](/reference/sdk/hooks-reference) for details on `permissionDecision` output and `hookSpecificOutput.decision`.
|
||||
|
||||
The hook-based permission flow is especially useful for headless agents that cannot show interactive prompts. When `shouldAvoidPermissionPrompts` is true (background agent mode), Claude Code runs `PermissionRequest` hooks before falling back to auto-deny.
|
||||
|
||||
***
|
||||
|
||||
## Safety recommendations
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="CI/CD pipelines">
|
||||
Use `bypassPermissions` only in isolated, short-lived environments where you control all inputs. Set explicit deny rules for destructive operations as a defense-in-depth measure:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"defaultPermissionMode": "bypassPermissions",
|
||||
"allowDangerouslySkipPermissions": true,
|
||||
"permissions": {
|
||||
"deny": [
|
||||
"Bash(rm -rf *)",
|
||||
"Bash(sudo *)",
|
||||
"Bash(curl * | bash)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="IDE and interactive use">
|
||||
Use `default` mode with allow rules for common safe operations. This minimizes interruptions while keeping you in control of destructive actions:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"defaultPermissionMode": "default",
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Read",
|
||||
"Glob",
|
||||
"Grep",
|
||||
"Bash(git status)",
|
||||
"Bash(git log *)",
|
||||
"Bash(git diff *)",
|
||||
"Bash(npm run *)",
|
||||
"Bash(make *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Code review and read-only analysis">
|
||||
Use `plan` mode when you want Claude to reason about code without making any changes. Claude can read files and explain what it would do, but cannot write, edit, or run commands:
|
||||
|
||||
```bash theme={null}
|
||||
claude --permission-mode plan "Explain the architecture of this codebase"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Automated agents with human approval">
|
||||
Use `dontAsk` mode combined with an SDK `PermissionRequest` hook to replace the interactive dialog with your own approval UI. The hook receives every tool call that would have prompted and can allow, deny, or forward it to a human reviewer:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"defaultPermissionMode": "dontAsk",
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Read",
|
||||
"Bash(git *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Any tool call not matching an allow rule is sent to your `PermissionRequest` hook handler instead of being auto-denied.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
225
docs/claude-code-docs-main/en/reference/tools/agent.md
Normal file
225
docs/claude-code-docs-main/en/reference/tools/agent.md
Normal file
@@ -0,0 +1,225 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Agent & Task Tools
|
||||
|
||||
> Spawn sub-agents for complex tasks and track work with a structured todo list.
|
||||
|
||||
Claude Code has two meta-tools for managing complex, multi-step work: `Task` (also called the Agent tool) for launching autonomous sub-agents, and `TodoWrite` for maintaining a structured task list within a session.
|
||||
|
||||
***
|
||||
|
||||
## Task (Agent tool)
|
||||
|
||||
Launches a specialized sub-agent to handle a complex task autonomously. The sub-agent runs independently, uses its own set of tools, and returns a single result message when it finishes.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="prompt" type="string" required>
|
||||
The full task description for the agent. Since sub-agents start with no knowledge of the parent conversation, the prompt must be self-contained — include relevant file paths, line numbers, context, and any constraints. Terse command-style prompts produce shallow results.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="description" type="string" required>
|
||||
A short (3–5 word) label describing what the agent will do. Shown in the UI.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="subagent_type" type="string">
|
||||
The type of specialized agent to use (e.g., `"code-reviewer"`, `"test-runner"`). When omitted, the general-purpose agent is used. Available agent types are listed in the system prompt.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="model" type="string">
|
||||
Optional model override: `"sonnet"`, `"opus"`, or `"haiku"`. Takes precedence over the agent definition's configured model. Omit to inherit from the agent definition or parent.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="run_in_background" type="boolean">
|
||||
When `true`, the agent runs in the background. Claude is notified when it completes and should not poll or sleep while waiting. Use background mode when you have genuinely independent work to continue in the meantime.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="isolation" type="string">
|
||||
Isolation mode for the agent's filesystem context:
|
||||
|
||||
* `"worktree"` — agent runs in a temporary git worktree (isolated copy of the repo). The worktree is cleaned up automatically if the agent makes no changes; otherwise the path and branch are returned.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="cwd" type="string">
|
||||
Absolute path to use as the working directory for all filesystem and shell operations inside the agent. Mutually exclusive with `isolation: "worktree"`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="name" type="string">
|
||||
A name for the spawned agent. Makes it addressable via `SendMessage({ to: name })` while it is running.
|
||||
</ParamField>
|
||||
|
||||
### How sub-agents work
|
||||
|
||||
Each agent invocation starts with zero conversation context. The agent:
|
||||
|
||||
1. Receives its own system prompt and the `prompt` you provide
|
||||
2. Has access to a tool set defined by its `subagent_type` (or all tools for the general-purpose agent)
|
||||
3. Runs autonomously until the task is complete
|
||||
4. Returns a single result message back to the parent
|
||||
|
||||
The result is **not** shown directly to the user — Claude summarizes it in a follow-up message.
|
||||
|
||||
<Warning>
|
||||
Never write "based on your findings, fix the bug" or similar delegation phrases. Prompts that push synthesis back onto the agent produce generic work. Include concrete file paths, line numbers, and specific instructions in the prompt.
|
||||
</Warning>
|
||||
|
||||
### When to use the Task tool
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Good use cases">
|
||||
* Open-ended research that requires multiple rounds of searching and reading
|
||||
* Running a test suite and analyzing failures after code changes
|
||||
* Independent code review by a fresh agent with no prior context bias
|
||||
* Long-running operations that can proceed while Claude handles other requests
|
||||
* Tasks that would generate noisy intermediate output you don't need in the main context
|
||||
</Tab>
|
||||
|
||||
<Tab title="When NOT to use it">
|
||||
* Reading a specific file — use the `Read` tool directly
|
||||
* Searching for a class definition — use `Grep` directly
|
||||
* Searching within 2–3 known files — use `Read` directly
|
||||
* Simple tasks unrelated to the available agent types
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Parallel agents
|
||||
|
||||
When tasks are independent, Claude launches multiple agents in a single message:
|
||||
|
||||
```
|
||||
Task({ description: "Run tests", prompt: "Run the full test suite..." })
|
||||
Task({ description: "Check types", prompt: "Run tsc --noEmit and report errors..." })
|
||||
```
|
||||
|
||||
Both agents run concurrently. When both complete, Claude synthesizes the results.
|
||||
|
||||
### Resuming agents
|
||||
|
||||
To send a follow-up message to a running or completed agent, use `SendMessage` with the agent's `name` as the `to` field. The agent resumes with its full context preserved.
|
||||
|
||||
### Writing effective prompts
|
||||
|
||||
<Accordion title="Brief like a colleague joining mid-task">
|
||||
The agent knows nothing about your session. Treat the prompt like a complete briefing for a smart colleague who just arrived:
|
||||
|
||||
* What you're trying to accomplish and why
|
||||
* What you've already tried or ruled out
|
||||
* The specific files, functions, or systems involved
|
||||
* What form the result should take ("report in under 200 words", "make the fix directly", etc.)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Lookups vs. investigations">
|
||||
* **Lookups**: hand over the exact command or query. The agent should not need to figure out what to run.
|
||||
* **Investigations**: hand over the question, not prescribed steps. Over-specifying steps for open-ended problems causes the agent to waste effort on a wrong path.
|
||||
</Accordion>
|
||||
|
||||
***
|
||||
|
||||
## TodoWrite
|
||||
|
||||
Maintains a structured task list for the current session. Claude uses this tool proactively to track progress, organize multi-step work, and provide visibility into what it is doing.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="todos" type="TodoItem[]" required>
|
||||
The complete, updated todo list. Each call **replaces** the entire list — there is no incremental add or remove.
|
||||
</ParamField>
|
||||
|
||||
### TodoItem schema
|
||||
|
||||
Each item in the `todos` array has the following fields:
|
||||
|
||||
<ParamField body="content" type="string" required>
|
||||
The task description in imperative form — what needs to be done. Example: `"Run tests"`, `"Fix authentication bug"`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="activeForm" type="string" required>
|
||||
The present-continuous form of the task description, shown while the task is in progress. Example: `"Running tests"`, `"Fixing authentication bug"`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="status" type="string" required>
|
||||
The current state of the task. One of:
|
||||
|
||||
| Value | Meaning |
|
||||
| ------------- | ------------------------- |
|
||||
| `pending` | Not yet started |
|
||||
| `in_progress` | Currently being worked on |
|
||||
| `completed` | Finished successfully |
|
||||
|
||||
Exactly one task should be `in_progress` at any time.
|
||||
</ParamField>
|
||||
|
||||
### How Claude uses TodoWrite
|
||||
|
||||
Claude calls `TodoWrite` proactively when:
|
||||
|
||||
* A task requires **3 or more distinct steps**
|
||||
* Work is non-trivial and benefits from structured tracking
|
||||
* The user provides a list of multiple things to do
|
||||
* New sub-tasks are discovered mid-implementation
|
||||
|
||||
Claude does **not** use `TodoWrite` for:
|
||||
|
||||
* Single-step tasks
|
||||
* Trivial operations (e.g., adding a comment, running one command)
|
||||
* Purely informational or conversational responses
|
||||
|
||||
### Task lifecycle
|
||||
|
||||
<Accordion title="Starting work">
|
||||
Claude marks a task `in_progress` **before** beginning, not after. This ensures the UI reflects what is actively happening.
|
||||
|
||||
```json theme={null}
|
||||
{ "content": "Add dark mode toggle", "activeForm": "Adding dark mode toggle", "status": "in_progress" }
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Completing work">
|
||||
Claude marks a task `completed` immediately when it finishes — it does not batch completions. A task is only marked complete when:
|
||||
|
||||
* Implementation is fully done
|
||||
* No tests are failing
|
||||
* No unresolved errors remain
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Handling blockers">
|
||||
If a task cannot be completed (missing file, failing test, unresolved error), Claude keeps it `in_progress` and creates a new `pending` task describing what needs to be resolved first.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Clearing the list">
|
||||
When all tasks are marked `completed`, Claude clears the list automatically. An empty list signals that all requested work is done.
|
||||
</Accordion>
|
||||
|
||||
### Example list
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"todos": [
|
||||
{
|
||||
"content": "Add dark mode CSS variables",
|
||||
"activeForm": "Adding dark mode CSS variables",
|
||||
"status": "completed"
|
||||
},
|
||||
{
|
||||
"content": "Implement theme context provider",
|
||||
"activeForm": "Implementing theme context provider",
|
||||
"status": "in_progress"
|
||||
},
|
||||
{
|
||||
"content": "Update existing components to use theme",
|
||||
"activeForm": "Updating existing components to use theme",
|
||||
"status": "pending"
|
||||
},
|
||||
{
|
||||
"content": "Run tests and build",
|
||||
"activeForm": "Running tests and build",
|
||||
"status": "pending"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
170
docs/claude-code-docs-main/en/reference/tools/bash.md
Normal file
170
docs/claude-code-docs-main/en/reference/tools/bash.md
Normal file
@@ -0,0 +1,170 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Bash
|
||||
|
||||
> Execute shell commands in a persistent bash session.
|
||||
|
||||
The `Bash` tool runs shell commands and returns their output. Commands execute in a persistent bash session — the working directory is preserved between calls, though the shell state (variables, aliases, functions) is re-initialized from the user's profile on each invocation.
|
||||
|
||||
<Note>
|
||||
Claude prefers dedicated tools (`Read`, `Edit`, `Glob`, `Grep`) over Bash equivalents for file operations. Bash is reserved for tasks where no purpose-built tool applies.
|
||||
</Note>
|
||||
|
||||
## Parameters
|
||||
|
||||
<ParamField body="command" type="string" required>
|
||||
The shell command to execute. Supports all standard bash syntax including pipes, redirections, and compound operators (`&&`, `||`, `;`).
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="timeout" type="number">
|
||||
Maximum execution time in milliseconds. Defaults to **120,000 ms (2 minutes)**. Maximum allowed value is **600,000 ms (10 minutes)**.
|
||||
|
||||
Both values can be overridden at runtime via `BASH_DEFAULT_TIMEOUT_MS` and `BASH_MAX_TIMEOUT_MS` environment variables.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="description" type="string">
|
||||
A short human-readable description of what the command does. Shown in the UI when Claude explains its actions.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="run_in_background" type="boolean">
|
||||
When `true`, the command runs in the background. Claude is notified when it completes and does not need to poll for results. Do not append `&` to the command when using this parameter — background execution is handled internally.
|
||||
</ParamField>
|
||||
|
||||
## Session behavior
|
||||
|
||||
The bash session persists working directory across calls but does **not** persist:
|
||||
|
||||
* Shell variables set in previous commands
|
||||
* Aliases or functions
|
||||
* `cd` changes (Claude uses absolute paths instead)
|
||||
|
||||
Claude initializes each session from the user's shell profile (`bash` or `zsh`).
|
||||
|
||||
## Timeouts
|
||||
|
||||
| Setting | Default | Max |
|
||||
| --------------- | ------------------- | --- |
|
||||
| Default timeout | 120,000 ms (2 min) | — |
|
||||
| Maximum timeout | 600,000 ms (10 min) | — |
|
||||
|
||||
Pass a `timeout` value (in milliseconds) to override the default for a specific command.
|
||||
|
||||
## Permission model
|
||||
|
||||
Every Bash command passes through a permission check before execution. The outcome is one of:
|
||||
|
||||
* **Allow** — command matches an existing allow rule or is classified as read-only
|
||||
* **Ask** — command requires user approval before running
|
||||
* **Deny** — command matches an explicit deny rule and is blocked
|
||||
|
||||
### Allow rules
|
||||
|
||||
Rules are matched by exact command, prefix (`git commit:*`), or wildcard pattern. Safe wrapper commands (`timeout`, `time`, `nice`, `nohup`) and safe environment variable assignments (`NODE_ENV=prod`, `GOARCH=arm64`) are stripped before matching so prefix rules work correctly.
|
||||
|
||||
### Read-only auto-allow
|
||||
|
||||
Commands that only read state (e.g., `ls`, `cat`, `git log`, `grep`) are automatically allowed without a prompt.
|
||||
|
||||
### Security restrictions
|
||||
|
||||
Claude's security layer checks each command for patterns that commonly indicate injection or obfuscation attempts. Commands containing the following require explicit user approval:
|
||||
|
||||
* Command substitution: `` `...` ``, `$()`, `${}`
|
||||
* Process substitution: `<()`, `>()`
|
||||
* Input/output redirections (`<`, `>`) in suspicious contexts
|
||||
* Zsh-specific constructs: `zmodload`, `emulate -c`, `ztcp`, `zsocket`
|
||||
* ANSI-C quoting (`$'...'`) or locale quoting (`$"..."`)
|
||||
* IFS variable manipulation (`$IFS`)
|
||||
* Access to `/proc/*/environ`
|
||||
* Newlines or carriage returns in non-quoted positions
|
||||
|
||||
<Warning>
|
||||
Commands are split into subcommands before permission checking. A rule like `Bash(ls:*)` will **not** match `ls /tmp && rm -rf /` — the `rm -rf /` subcommand is checked separately.
|
||||
</Warning>
|
||||
|
||||
## Background execution
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Foreground (default)">
|
||||
```json theme={null}
|
||||
{
|
||||
"command": "npm run build",
|
||||
"description": "Build the project"
|
||||
}
|
||||
```
|
||||
|
||||
Claude waits for the command to finish and receives its output immediately.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Background">
|
||||
```json theme={null}
|
||||
{
|
||||
"command": "npm run dev",
|
||||
"description": "Start dev server",
|
||||
"run_in_background": true
|
||||
}
|
||||
```
|
||||
|
||||
The command starts and Claude continues without blocking. A notification arrives when the process finishes.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Examples
|
||||
|
||||
<Accordion title="Running tests">
|
||||
```bash theme={null}
|
||||
pytest tests/ -x --tb=short
|
||||
```
|
||||
|
||||
Run a test suite and stop on the first failure.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Git operations">
|
||||
```bash theme={null}
|
||||
git status && git diff --staged
|
||||
```
|
||||
|
||||
Check working tree status and staged changes in a single compound command.
|
||||
|
||||
<Note>
|
||||
Claude follows a strict protocol for `git commit` and `git push` — it never amends pushed commits, never skips hooks with `--no-verify`, and never force-pushes to `main`/`master` without explicit user instruction.
|
||||
</Note>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Installing dependencies">
|
||||
```bash theme={null}
|
||||
npm install
|
||||
```
|
||||
|
||||
Standard package installation. Claude stages related commands in parallel when they are independent.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Long-running server with timeout override">
|
||||
```json theme={null}
|
||||
{
|
||||
"command": "cargo build --release",
|
||||
"timeout": 300000,
|
||||
"description": "Release build (up to 5 min)"
|
||||
}
|
||||
```
|
||||
|
||||
Override the 2-minute default for commands known to take longer.
|
||||
</Accordion>
|
||||
|
||||
## Tool preference
|
||||
|
||||
Claude uses Bash only when no purpose-built tool is available:
|
||||
|
||||
| Task | Preferred tool |
|
||||
| ----------------------------- | -------------- |
|
||||
| Find files by name | `Glob` |
|
||||
| Search file contents | `Grep` |
|
||||
| Read a file | `Read` |
|
||||
| Edit a file | `Edit` |
|
||||
| Write a new file | `Write` |
|
||||
| Shell commands, builds, tests | **Bash** |
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
157
docs/claude-code-docs-main/en/reference/tools/file-operations.md
Normal file
157
docs/claude-code-docs-main/en/reference/tools/file-operations.md
Normal file
@@ -0,0 +1,157 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# File Operations
|
||||
|
||||
> Read, edit, and write files on the local filesystem.
|
||||
|
||||
Claude Code has three dedicated tools for working with files: `Read` for reading content, `Edit` for precise in-place edits, and `Write` for creating or fully rewriting files.
|
||||
|
||||
<Tip>
|
||||
Prefer `Edit` over `Write` when modifying existing files — `Edit` sends only the changed fragment, saving context and reducing the chance of unintended overwrites.
|
||||
</Tip>
|
||||
|
||||
***
|
||||
|
||||
## Read
|
||||
|
||||
Reads a file from the local filesystem and returns its contents with line numbers.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="file_path" type="string" required>
|
||||
Absolute path to the file. Relative paths are not accepted.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="offset" type="number">
|
||||
Line number to start reading from (1-indexed). Use this with `limit` to read a specific section of a large file.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="limit" type="number">
|
||||
Maximum number of lines to return. Defaults to **2,000** lines. For files longer than this, call `Read` again with a higher `offset` to page through the content.
|
||||
</ParamField>
|
||||
|
||||
### Output format
|
||||
|
||||
Results use `cat -n` style formatting: each line is prefixed with its 1-indexed line number.
|
||||
|
||||
```
|
||||
1 import { z } from 'zod'
|
||||
2
|
||||
3 export const schema = z.object({
|
||||
4 name: z.string(),
|
||||
5 })
|
||||
```
|
||||
|
||||
Claude preserves exact indentation from this output when constructing `Edit` calls.
|
||||
|
||||
### Supported file types
|
||||
|
||||
| Type | Behavior |
|
||||
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Text files | Returns raw text with line numbers |
|
||||
| Images (PNG, JPG, etc.) | Displayed visually — Claude is multimodal |
|
||||
| PDF files | Returned as document content. For PDFs over 10 pages, use the `pages` parameter (e.g., `"1-5"`). Maximum 20 pages per request. |
|
||||
| Jupyter notebooks (`.ipynb`) | All cells and outputs are returned, combining code, text, and visualizations |
|
||||
|
||||
<Note>
|
||||
`Read` cannot list directories. To inspect a directory's contents, use `ls` via the `Bash` tool.
|
||||
</Note>
|
||||
|
||||
### Caching
|
||||
|
||||
If a file has not changed since the last `Read` call in the same conversation, Claude receives a cached stub instead of re-reading the file. This avoids redundant reads on unchanged files.
|
||||
|
||||
***
|
||||
|
||||
## Edit
|
||||
|
||||
Performs exact string replacement within a file.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="file_path" type="string" required>
|
||||
Absolute path to the file to modify.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="old_string" type="string" required>
|
||||
The exact string to find and replace. Must match the file content character-for-character, including whitespace and indentation.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="new_string" type="string" required>
|
||||
The replacement string. Use an empty string to delete `old_string`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="replace_all" type="boolean">
|
||||
When `true`, replaces every occurrence of `old_string` in the file instead of only the first. Useful for renaming variables or symbols that appear multiple times.
|
||||
</ParamField>
|
||||
|
||||
### How Edit works
|
||||
|
||||
`Edit` finds the literal text in `old_string` inside the file and substitutes it with `new_string`. No regex interpretation occurs — the match is a plain string comparison.
|
||||
|
||||
<Warning>
|
||||
The tool **fails** if `old_string` appears more than once in the file and `replace_all` is not set. Provide enough surrounding context in `old_string` to make it unique, or set `replace_all: true` to update all occurrences.
|
||||
</Warning>
|
||||
|
||||
### Pre-read requirement
|
||||
|
||||
Claude must call `Read` on a file at least once in the conversation before calling `Edit` on it. The tool enforces this to prevent edits based on stale or assumed content.
|
||||
|
||||
### Indentation matching
|
||||
|
||||
When Claude derives `old_string` from `Read` output, it uses the content that appears **after** the line-number prefix. For example, given:
|
||||
|
||||
```
|
||||
12 const x = 1
|
||||
```
|
||||
|
||||
The `old_string` is ` const x = 1` (six leading spaces), not ` 12 const x = 1`.
|
||||
|
||||
***
|
||||
|
||||
## Write
|
||||
|
||||
Creates a new file or fully overwrites an existing one.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="file_path" type="string" required>
|
||||
Absolute path to the file to create or overwrite.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="content" type="string" required>
|
||||
The complete content to write to the file. If the file already exists, it is replaced entirely.
|
||||
</ParamField>
|
||||
|
||||
### When to use Write vs Edit
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Use Edit">
|
||||
* Modifying one or more sections of an existing file
|
||||
* Renaming a variable or symbol across the file
|
||||
* Adding or removing a block of code
|
||||
|
||||
Edit is preferred because it transmits only the changed fragment.
|
||||
</Tab>
|
||||
|
||||
<Tab title="Use Write">
|
||||
* Creating a new file from scratch
|
||||
* Completely rewriting a file (e.g., regenerating a config from new requirements)
|
||||
* When the new content is entirely different from the original
|
||||
|
||||
Write replaces the entire file in one call.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Pre-read requirement
|
||||
|
||||
When overwriting an existing file, Claude must call `Read` first. Write enforces this to prevent unintentional data loss.
|
||||
|
||||
<Warning>
|
||||
Claude does not proactively create documentation files (`*.md`, `README.*`) unless explicitly instructed. Write follows the same principle.
|
||||
</Warning>
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
187
docs/claude-code-docs-main/en/reference/tools/search.md
Normal file
187
docs/claude-code-docs-main/en/reference/tools/search.md
Normal file
@@ -0,0 +1,187 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Search
|
||||
|
||||
> Find files by name pattern and search file contents with regular expressions.
|
||||
|
||||
Claude Code has two dedicated search tools: `Glob` for finding files by name and `Grep` for searching file contents. Both are preferred over running `find` or `grep` as Bash commands — they have correct permission integration, return results sorted by modification time, and produce structured output Claude can act on directly.
|
||||
|
||||
***
|
||||
|
||||
## Glob
|
||||
|
||||
Finds files whose paths match a glob pattern. Results are sorted by modification time (most recently modified first).
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="pattern" type="string" required>
|
||||
A glob pattern to match file paths against. Supports `*` (any characters within a path segment), `**` (any number of path segments), and `?` (single character).
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="path" type="string">
|
||||
The directory to search in. Defaults to the current working directory. Must be an existing directory path — omit the parameter entirely to use the default; do not pass `null` or `"undefined"`.
|
||||
</ParamField>
|
||||
|
||||
### Output
|
||||
|
||||
Returns a list of matching file paths, relative to the working directory, sorted by modification time. Results are capped at **100 files**. If the result is truncated, consider narrowing the pattern or specifying a more specific `path`.
|
||||
|
||||
### Pattern examples
|
||||
|
||||
| Pattern | Matches |
|
||||
| ---------------------------- | ----------------------------------------------- |
|
||||
| `**/*.ts` | All TypeScript files anywhere in the tree |
|
||||
| `src/**/*.tsx` | All TSX files under `src/` |
|
||||
| `*.json` | JSON files in the current directory only |
|
||||
| `**/{package,tsconfig}.json` | `package.json` and `tsconfig.json` at any depth |
|
||||
| `tools/*/prompt.ts` | `prompt.ts` one level inside `tools/` |
|
||||
|
||||
<Tip>
|
||||
Use `Glob` when you know the filename or extension you're looking for. For open-ended exploration that requires multiple rounds of searching, use the `Task` (Agent) tool instead.
|
||||
</Tip>
|
||||
|
||||
***
|
||||
|
||||
## Grep
|
||||
|
||||
Searches file contents using regular expressions, powered by ripgrep. Returns matching file paths, line numbers, and (optionally) matching lines.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="pattern" type="string" required>
|
||||
A regular expression to search for in file contents. Supports full regex syntax: character classes, quantifiers, lookaheads, alternation, etc.
|
||||
|
||||
Ripgrep syntax differs from POSIX `grep` in one notable way: literal braces must be escaped. Use `interface\{\}` to find `interface{}` in Go code.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="path" type="string">
|
||||
File or directory to search in. Defaults to the current working directory. Can be a single file path to restrict the search.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="glob" type="string">
|
||||
Glob pattern to filter which files are searched (e.g., `"*.js"`, `"*.{ts,tsx}"`). Maps to `rg --glob`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="type" type="string">
|
||||
Ripgrep file type to restrict the search (e.g., `"js"`, `"py"`, `"rust"`, `"go"`, `"java"`). More efficient than `glob` for standard file type filtering. Maps to `rg --type`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="output_mode" type="string">
|
||||
Controls what is returned. Options:
|
||||
|
||||
* `"files_with_matches"` *(default)* — returns file paths only
|
||||
* `"content"` — returns matching lines with context support
|
||||
* `"count"` — returns match counts per file
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="-i" type="boolean">
|
||||
Case-insensitive search. Maps to `rg -i`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="-n" type="boolean">
|
||||
Show line numbers in output. Applies to `output_mode: "content"` only. Defaults to `true`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="-A" type="number">
|
||||
Lines of context to show after each match. Applies to `output_mode: "content"` only. Maps to `rg -A`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="-B" type="number">
|
||||
Lines of context to show before each match. Applies to `output_mode: "content"` only. Maps to `rg -B`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="context" type="number">
|
||||
Lines of context to show before and after each match (equivalent to `rg -C`). Takes precedence over `-A` and `-B`. Applies to `output_mode: "content"` only.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="multiline" type="boolean">
|
||||
Enable multiline mode where `.` matches newlines and patterns can span multiple lines (`rg -U --multiline-dotall`). Default: `false`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="head_limit" type="number">
|
||||
Limit output to the first N lines or entries (equivalent to `| head -N`). Applies across all output modes. Defaults to **250**. Pass `0` for unlimited results.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="offset" type="number">
|
||||
Skip the first N entries before applying `head_limit` (equivalent to `| tail -n +N`). Useful for paginating large result sets. Defaults to `0`.
|
||||
</ParamField>
|
||||
|
||||
### Output modes
|
||||
|
||||
<Tabs>
|
||||
<Tab title="files_with_matches (default)">
|
||||
Returns a list of file paths that contain at least one match, sorted by modification time.
|
||||
|
||||
```
|
||||
Found 3 files
|
||||
src/utils/permissions/bashClassifier.ts
|
||||
src/tools/BashTool/BashTool.tsx
|
||||
src/tools/BashTool/bashPermissions.ts
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="content">
|
||||
Returns the matching lines themselves, with optional surrounding context.
|
||||
|
||||
```
|
||||
src/utils/permissions/bashClassifier.ts:42:export function classifyBashCommand(
|
||||
src/utils/permissions/bashClassifier.ts:43: command: string,
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="count">
|
||||
Returns match counts per file.
|
||||
|
||||
```
|
||||
src/utils/permissions/bashClassifier.ts:7
|
||||
src/tools/BashTool/bashPermissions.ts:3
|
||||
|
||||
Found 10 total occurrences across 2 files.
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Pattern syntax notes
|
||||
|
||||
<Accordion title="Escaping braces for Go / TypeScript">
|
||||
Ripgrep treats `{` and `}` as literal characters by default, unlike some regex engines that use them for quantifiers. To search for literal braces, escape them:
|
||||
|
||||
```
|
||||
interface\{\} → finds interface{}
|
||||
map\[string\] → finds map[string]
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Multiline patterns">
|
||||
By default, `.` does not match newlines. To search across line boundaries:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"pattern": "struct \\{[\\s\\S]*?field",
|
||||
"multiline": true
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Combining glob and type filters">
|
||||
`glob` and `type` can be used independently or together:
|
||||
|
||||
```json theme={null}
|
||||
{ "pattern": "TODO", "type": "ts" }
|
||||
```
|
||||
|
||||
```json theme={null}
|
||||
{ "pattern": "TODO", "glob": "src/**/*.ts" }
|
||||
```
|
||||
|
||||
Use `type` for standard language types; use `glob` when the file set doesn't align with a named type.
|
||||
</Accordion>
|
||||
|
||||
### Excluded directories
|
||||
|
||||
Grep automatically excludes version-control metadata directories: `.git`, `.svn`, `.hg`, `.bzr`, `.jj`, `.sl`.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
154
docs/claude-code-docs-main/en/reference/tools/web.md
Normal file
154
docs/claude-code-docs-main/en/reference/tools/web.md
Normal file
@@ -0,0 +1,154 @@
|
||||
> ## Documentation Index
|
||||
> Fetch the complete documentation index at: https://vineetagarwal-code-claude-code.mintlify.app/llms.txt
|
||||
> Use this file to discover all available pages before exploring further.
|
||||
|
||||
# Web
|
||||
|
||||
> Fetch web pages and search the internet for current information.
|
||||
|
||||
Claude Code has two web tools: `WebFetch` for retrieving and analyzing specific URLs, and `WebSearch` for querying the web when information may be beyond Claude's training cutoff.
|
||||
|
||||
***
|
||||
|
||||
## WebFetch
|
||||
|
||||
Fetches a URL, converts the HTML to markdown, and then processes the content using a small fast model with a prompt you provide. Returns the model's response — not the raw page content.
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="url" type="string" required>
|
||||
A fully-formed, valid URL. HTTP URLs are automatically upgraded to HTTPS.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="prompt" type="string" required>
|
||||
A natural-language prompt describing what to extract or analyze from the page content. The fetched content is passed to a secondary model along with this prompt, and the model's response is returned.
|
||||
</ParamField>
|
||||
|
||||
### Behavior
|
||||
|
||||
1. Claude fetches the URL and converts HTML to markdown.
|
||||
2. The markdown and the `prompt` are sent to a small, fast model.
|
||||
3. That model's response is returned as the tool result.
|
||||
|
||||
Because a secondary model processes the content, the result is always a synthesized answer — not a raw dump of the page. If the content is very large, it may be summarized automatically.
|
||||
|
||||
<Info>
|
||||
WebFetch includes a 15-minute in-memory cache. Repeated calls to the same URL within that window return cached content without a network request.
|
||||
</Info>
|
||||
|
||||
### Redirects
|
||||
|
||||
When a URL redirects to a different host, the tool returns a special message indicating the redirect destination rather than following it automatically. Claude then makes a new `WebFetch` call with the redirect URL.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Read-only — does not submit forms or interact with pages
|
||||
* Not suitable for pages requiring authentication (login walls, paywalls)
|
||||
* For GitHub resources, prefer the `gh` CLI via `Bash` (e.g., `gh pr view`, `gh issue view`, `gh api`)
|
||||
|
||||
<Tip>
|
||||
If an MCP-provided web fetch tool is available in your environment, it may have fewer restrictions and should be preferred over this built-in tool.
|
||||
</Tip>
|
||||
|
||||
### Example usage
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Extract API details">
|
||||
```json theme={null}
|
||||
{
|
||||
"url": "https://docs.example.com/api/authentication",
|
||||
"prompt": "What authentication methods are supported and what headers are required?"
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Check library version">
|
||||
```json theme={null}
|
||||
{
|
||||
"url": "https://github.com/some-org/some-lib/blob/main/CHANGELOG.md",
|
||||
"prompt": "What changed in the latest version?"
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Read documentation">
|
||||
```json theme={null}
|
||||
{
|
||||
"url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API",
|
||||
"prompt": "Summarize the Fetch API and show a basic usage example."
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
***
|
||||
|
||||
## WebSearch
|
||||
|
||||
Searches the web and returns results including titles, URLs, and a model-synthesized summary. Useful when information may be newer than Claude's training data.
|
||||
|
||||
<Info>
|
||||
Web search is only available in the United States. It requires a compatible API provider (Anthropic first-party, Vertex AI with Claude 4.0+ models, or Foundry).
|
||||
</Info>
|
||||
|
||||
### Parameters
|
||||
|
||||
<ParamField body="query" type="string" required>
|
||||
The search query to execute. Minimum length: 2 characters.
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="allowed_domains" type="string[]">
|
||||
When set, only return results from these domains. Cannot be combined with `blocked_domains` in the same request.
|
||||
|
||||
Example: `["docs.python.org", "peps.python.org"]`
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="blocked_domains" type="string[]">
|
||||
Exclude results from these domains. Cannot be combined with `allowed_domains` in the same request.
|
||||
|
||||
Example: `["w3schools.com"]`
|
||||
</ParamField>
|
||||
|
||||
### Output
|
||||
|
||||
The tool returns search results as structured blocks containing:
|
||||
|
||||
* Result titles and URLs
|
||||
* A synthesized summary produced by a model that has access to the search results
|
||||
|
||||
Claude is required to cite sources from web searches by appending a `Sources:` section with markdown hyperlinks to its response.
|
||||
|
||||
### Domain filtering
|
||||
|
||||
<Accordion title="Restricting to specific domains (allowed_domains)">
|
||||
Use `allowed_domains` when you want results exclusively from trusted or authoritative sources:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"query": "Python asyncio best practices 2024",
|
||||
"allowed_domains": ["docs.python.org", "realpython.com"]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Excluding domains (blocked_domains)">
|
||||
Use `blocked_domains` to suppress low-quality or paywalled sources:
|
||||
|
||||
```json theme={null}
|
||||
{
|
||||
"query": "React server components tutorial",
|
||||
"blocked_domains": ["medium.com"]
|
||||
}
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
### Search limits
|
||||
|
||||
Each `WebSearch` invocation performs up to **8 individual web searches** internally. Claude automatically refines queries as needed within that budget.
|
||||
|
||||
### Current date awareness
|
||||
|
||||
When searching for recent information, Claude includes the current year in search queries to avoid returning outdated results — for example, appending the year when searching for library documentation or current events.
|
||||
|
||||
|
||||
Built with [Mintlify](https://mintlify.com).
|
||||
Reference in New Issue
Block a user