[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-zebbern--claude-code-guide":3,"tool-zebbern--claude-code-guide":62},[4,18,26,36,46,54],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",158594,2,"2026-04-16T23:34:05",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":42,"last_commit_at":43,"category_tags":44,"status":17},8272,"opencode","anomalyco\u002Fopencode","OpenCode 是一款开源的 AI 编程助手（Coding Agent），旨在像一位智能搭档一样融入您的开发流程。它不仅仅是一个代码补全插件，而是一个能够理解项目上下文、自主规划任务并执行复杂编码操作的智能体。无论是生成全新功能、重构现有代码，还是排查难以定位的 Bug，OpenCode 都能通过自然语言交互高效完成，显著减少开发者在重复性劳动和上下文切换上的时间消耗。\n\n这款工具专为软件开发者、工程师及技术研究人员设计，特别适合希望利用大模型能力来提升编码效率、加速原型开发或处理遗留代码维护的专业人群。其核心亮点在于完全开源的架构，这意味着用户可以审查代码逻辑、自定义行为策略，甚至私有化部署以保障数据安全，彻底打破了传统闭源 AI 助手的“黑盒”限制。\n\n在技术体验上，OpenCode 提供了灵活的终端界面（Terminal UI）和正在测试中的桌面应用程序，支持 macOS、Windows 及 Linux 全平台。它兼容多种包管理工具，安装便捷，并能无缝集成到现有的开发环境中。无论您是追求极致控制权的资深极客，还是渴望提升产出的独立开发者，OpenCode 都提供了一个透明、可信",144296,1,"2026-04-16T14:50:03",[13,45],"插件",{"id":47,"name":48,"github_repo":49,"description_zh":50,"stars":51,"difficulty_score":32,"last_commit_at":52,"category_tags":53,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":55,"name":56,"github_repo":57,"description_zh":58,"stars":59,"difficulty_score":32,"last_commit_at":60,"category_tags":61,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[45,13,15,14],{"id":63,"github_repo":64,"name":65,"description_en":66,"description_zh":67,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":77,"owner_location":74,"owner_email":74,"owner_twitter":74,"owner_website":78,"owner_url":79,"languages":74,"stars":80,"forks":81,"last_commit_at":82,"license":83,"difficulty_score":32,"env_os":84,"env_gpu":85,"env_ram":86,"env_deps":87,"category_tags":94,"github_topics":95,"view_count":32,"oss_zip_url":74,"oss_zip_packed_at":74,"status":17,"created_at":115,"updated_at":116,"faqs":117,"releases":118},8280,"zebbern\u002Fclaude-code-guide","claude-code-guide","Claude Code Guide - Setup, Commands, workflows, agents, skills & tips-n-tricks go from beginner to power user!","claude-code-guide 是一份专为 Anthropic 官方命令行工具 Claude Code 打造的社区驱动型实战指南。它旨在帮助用户跨越从入门新手到高级专家的学习曲线，系统性地解决在配置环境、掌握复杂指令、构建自动化工作流以及管理多智能体协作时遇到的各类难题。\n\n这份指南特别适合开发者、DevOps 工程师以及希望将 AI 深度集成到编码流程中的技术研究人员使用。无论是需要快速上手的初学者，还是追求极致效率的资深用户，都能从中找到对应的解决方案。其核心亮点在于不仅涵盖了基础的安装与快捷键操作，更深入探讨了思维模式（Thinking Mode）、沙箱隔离、子智能体（Sub Agents）协作、MCP 协议集成以及钩子系统（Hooks）等高级特性。此外，指南还提供了丰富的安全最佳实践、故障排查技巧以及大量可复用的技能模板（Skills），让用户能够安全、高效地利用 AI 进行代码审查、问题分类及自动化脚本编写，真正释放命令行环境下 AI 编程的全部潜力。","\u003Cdiv align=\"center\">\n\n\u003Ch2 id=\"claude-code-community-guide\">Claude Code Guide\u003C\u002Fh2>\n\n_For updates and contributions, visit the [official Claude Code documentation](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview)_\n\n![Claude Code](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002F@anthropic-ai\u002Fclaude-code?label=Claude%20Code&logo=anthropic)\n[![Status](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FStatus-Active-brightgreen)](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code)\n[![License](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-Anthropic-orange)](https:\u002F\u002Fclaude.ai\u002Fcode)\n\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n\u003Ckbd>\n\n| Section                                           | Status | Other Resources |\n| ------------------------------------------------- | ------ |------ |\n| Getting Started                       |✅|\u003Ckbd> **Claude-Code** [**Changelogs**](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fclaude-code-guide\u002Fblob\u002Fmain\u002FCHANGELOG.md)\u003C\u002Fkbd> |\n| Configuration & Environment Variables |✅|\u003Ckbd>**Claude-Code via** [**Discord**](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fclaude-code-discord)\u003C\u002Fkbd> |\n| Commands & Usage                      |✅|\u003Ckbd>Security Agents [SKILL.md](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fclaude-code-guide\u002Ftree\u002Fmain\u002Fskills)\u003C\u002Fkbd> |\n| Interface & Input                     |✅|\u003Ckbd>Let Agent Create [SKILL.md](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fagent-skills-authoring)\u003C\u002Fkbd> |\n| Advanced Features                     |✅|\u003Ckbd>954+ Agent [Skills](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fantigravity-awesome-skills)\u003C\u002Fkbd> |\n| Automation & Integration              |✅|\u003Ckbd>No cost ai [resources](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fno-cost-ai)\u003C\u002Fkbd>  |\n| Help & Troubleshooting                |✅|\u003Ckbd>250+ Mermaid [templates](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fmermaid-templates)\u003C\u002Fkbd>  |\n| Third-Party Integrations              |✅|\u003Ckbd>Discord Communication [MCP](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fdiscord-mcp-agent)\u003C\u002Fkbd> |\n\n\n\u003C\u002Fkbd>\n\n\u003C\u002Fdiv>\n\n---\n\n\u003Ch3 id=\"content\">Content\u003C\u002Fh3>\n\n_Quick links:_ [Install](#quick-start) · [Commands](#claude-commands) · [Shortcuts](#keyboard-shortcuts) · [MCP](#mcp-integration) · [Troubleshoot](#help--troubleshooting)\n\n- **[Getting Started](#getting-started)**\n  - [Quick Start](#quick-start)\n  - [Initial Setup](#initial-setup)\n\n- **[Configuration & Environment](#configuration--environment)**\n  - [Environment Variables](#environment-variables)\n  - [Configuration Files](#configuration-files)\n\n- **[Commands & Usage](#commands--usage)**\n  - [Slash Command Reference](#claude-commands)\n  - [CLI Quick Reference](#cheat-sheet)\n\n- **[Interface & Input](#interface--input)**\n  - [Keyboard Shortcuts](#keyboard-shortcuts)\n  - [Vim Mode](#vim-mode)\n\n- **[Advanced Features](#advanced-features)**\n  - [Thinking Mode](#thinking-keywords)\n  - [Plan Mode](#plan-mode)\n  - [Fast Mode](#fast-mode)\n  - [Background Tasks](#background-tasks)\n  - [Claude in Chrome](#claude-in-chrome)\n  - [Sandbox Mode](#sandbox-mode)\n  - [LSP Tool](#lsp-tool)\n  - [Remote Sessions](#remote-sessions)\n  - [Sub Agents](#sub-agents)\n  - [Agent Teams](#agent-teams)\n  - [Skills](#skills)\n  - [Plugin System](#plugin-system)\n  - [Worktree Isolation](#worktree-isolation)\n  - [MCP Integration](#mcp-integration)\n  - [Hooks System](#hooks-system)\n  - [Native Installer](#native-installer)\n  - [Authentication CLI](#claude-auth)\n  - [Agent Management CLI](#claude-agents-cli)\n  - [Remote Control](#remote-control)\n  - [Managed Settings](#managed-settings)\n  - [Model Updates](#model-updates)\n  - [Insights](#insights)\n\n- **[Security & Permissions](#security--permissions)**\n  - [Dangerous Mode](#dangerous-mode)\n  - [Security Best Practices](#security-best-practices-main)\n\n- **[Automation & Integration](#automation--integration)**\n  - [Automation & Scripting](#automation--scripting-with-claude-code)\n  - [Auto PR Review](#auto-pr-review-inline-comments)\n  - [Issue Triage](#issue-triage-suggest-labels--severity)\n\n- **[Help & Troubleshooting](#help--troubleshooting)**\n  - [Installation Issues](#installation--nodejs-issues)\n  - [MCP Issues](#mcp-model-context-protocol-issues)\n  - [Best Practices](#best-practices)\n\n- **[Third-Party Integrations](#third-party-integrations)**\n  - [DeepSeek Integration](#deepseek-integration)\n\n---\n\n\u003Ch1 id=\"getting-started\">Getting Started\u003C\u002Fh1>\n\n**Enable sound alerts when claude completes the task:**\n\n> \u003Ckbd>claude config set --global preferredNotifChannel terminal_bell\u003C\u002Fkbd>\n\n\u003Ch2 id=\"quick-start\">Quick Start\u003C\u002Fh2>\n\n> [!TIP]\n> **Send \u003Cmark>claude\u003C\u002Fmark> or \u003Cmark>npx claude\u003C\u002Fmark> in terminal to start the interface**\n>\n> **Go to [Help & Troubleshooting](#help--troubleshooting) to fix issues...**\n\n```C\n# Native Installer (preferred — no Node.js required) ⭐️\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Windows\n\u002F* Via CMD (native)      *\u002F curl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.cmd -o install.cmd && install.cmd && del install.cmd\n\u002F* Via Powershell        *\u002F irm https:\u002F\u002Fclaude.ai\u002Finstall.ps1 | iex\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# macOS \u002F Linux \u002F WSL\n\u002F* Via Terminal          *\u002F curl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Arch\n\u002F* Via Terminal          *\u002F yay -S claude-code*\u002F\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n# Alternative (npm) — deprecated in favor of native installer\n# Requires Node.js 18+\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Windows\n\u002F* Via CMD (npm)         *\u002F npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# macOS\n\u002F* Via Terminal          *\u002F brew install node && npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Linux\n\u002F* Via Terminal          *\u002F sudo apt update && sudo apt install -y nodejs npm\n\u002F* Via Terminal          *\u002F npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# WSL\u002FGIT\n\u002F* Via Terminal          *\u002F npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Docker\n\u002F* Windows (CMD)         *\u002F docker run -it --rm -v \"%cd%:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim bash -lc \"npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude\"\n\u002F* macOS\u002FLinux (bash\u002Fzsh)*\u002F docker run -it --rm -v \"$PWD:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim bash -lc 'npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude'\n\u002F* No bash Fallback      *\u002F docker run -it --rm -v \"$PWD:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim sh -lc 'npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude'\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Check if claude is installed correctly\n\u002F* Linux                 *\u002F which claude\n\u002F* Windows               *\u002F where claude\n\u002F* Universal             *\u002F claude --version\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Common Management\n\u002F*claude config          *\u002F Configure settings\n\u002F*claude mcp list        *\u002F Setup MCP servers, you can also replace \"list\" with add\u002Fremove\n\u002F*claude \u002Fagents         *\u002F Configure\u002FSetup Subagents for different tasks\n\u002F*claude update          *\u002F Update to latest\n```\n\n---\n\n> [!Tip]\n> \u003Cins>**Open Project Via Terminal Into VS Code \u002F Cursor**\u003C\u002Fins>\n>\n> ### $ - \u003Ckbd>cd \u002Fpath\u002Fto\u002Fproject\u003C\u002Fkbd>\n>\n> ### $ - \u003Ckbd>code .\u003C\u002Fkbd>\n>\n> **Make sure you have the \u003Cmark>(Claude Code extension)\u003C\u002Fmark> installed in your VS Code \u002F Cursor**\n\n---\n\n\u003Ch2 id=\"system-requirements\">System Requirements\u003C\u002Fh2>\n\n> - OS: macOS 10.15+, Ubuntu 20.04+\u002FDebian 10+, or Windows 10\u002F11 or WSL\n\n> - Hardware: 4GB RAM minimum 8GB+ recommended\n\n> - Software: Node.js 18+ or git 2.23+ (optional) & GitHub or GitLab CLI for PR workflows (optional)\n> - _Node.js is only required for npm-based installation. The native installer bundles its own runtime._\n\n> - Internet: Connection for API calls\n\n> - Node.js 18+ _(only required for npm-based installation; the native installer bundles its own runtime)_\n\n---\n\n\u003Ch2 id=\"initial-setup\">Initial Setup\u003C\u002Fh2>\n\n> [!Tip]\n> **Find API key from [Anthropic Console](https:\u002F\u002Fconsole.anthropic.com)**\n>\n> **Do NOT commit real keys use git-ignored files, OS key stores, or secret managers**\n\n```C\n# Universal\n\u002F* start login process                    *\u002F claude \u002Flogin\n\u002F* Setup long-lived authentication token  *\u002F claude setup-token\n\u002F* Authenticate via Anthropic account     *\u002F claude auth login\n----------------------------------------------------------------------------------------------------------------------------------\n# Windows\n\u002F* Set-api-key        *\u002F set ANTHROPIC_API_KEY=sk-your-key-here-here\n\u002F* cmd-masked-check   *\u002F echo OK: %ANTHROPIC_API_KEY:~0,8%***\n\u002F* Set-persistent-key *\u002F setx ANTHROPIC_API_KEY \"sk-your-key-here-here\"\n\u002F* cmd-unset-key      *\u002F set ANTHROPIC_API_KEY=\n----------------------------------------------------------------------------------------------------------------------------------\n# Linux\n\u002F* Set-api-key        *\u002F export ANTHROPIC_API_KEY=\"sk-your-key-here-here\"\n\u002F* masked-check       *\u002F echo \"OK: ${ANTHROPIC_API_KEY:0:8}***\"\n\u002F* remove-session     *\u002F unset ANTHROPIC_API_KEY\n----------------------------------------------------------------------------------------------------------------------------------\n# Powershell\n\u002F* ps-session         *\u002F $env:ANTHROPIC_API_KEY = \"sk-your-key-here-here\"\n\u002F* ps-masked-check    *\u002F \"OK: $($env:ANTHROPIC_API_KEY.Substring(0,8))***\"\n\u002F* ps-persist         *\u002F [Environment]::SetEnvironmentVariable(\"ANTHROPIC_API_KEY\",\"sk-your-key-here-here\",\"User\")\n\u002F* ps-rotate          *\u002F $env:ANTHROPIC_API_KEY = \"sk-new-key\"\n\u002F* ps-remove          *\u002F Remove-Item Env:\\ANTHROPIC_API_KEY\n----------------------------------------------------------------------------------------------------------------------------------\n# Other...\n# persist-bash\u002F*      *\u002F echo 'export ANTHROPIC_API_KEY=\"sk-your-key-here-here\"' >> ~\u002F.bashrc && source ~\u002F.bashrc\n# persist-zsh \u002F*      *\u002F echo 'export ANTHROPIC_API_KEY=\"sk-your-key-here-here\"' >> ~\u002F.zshrc  && source ~\u002F.zshrc\n# persist-fish\u002F*      *\u002F fish -lc 'set -Ux ANTHROPIC_API_KEY sk-your-key-here-here'\n----------------------------------------------------------------------------------------------------------------------------------\n```\n\n---\n\n\u003Ch1 id=\"configuration--environment\">Configuration & Environment\u003C\u002Fh1>\n\n\u003Ch2 id=\"environment-variables\">Environment Variables\u003C\u002Fh2>\n\n> **You can also set any of these in settings.json under the \"env\" key for automatic application.**\n\n> [!Important]\n> **Windows Users replace \u003Ckbd>export\u003C\u002Fkbd> with \u003Ckbd>set\u003C\u002Fkbd> or \u003Ckbd>setx\u003C\u002Fkbd> for perm**\n\n```bash\n# Environment toggles (put in ~\u002F.bashrc or ~\u002F.zshrc)\nexport ANTHROPIC_API_KEY=\"sk-your-key-here-here\"      # API key sent as X-Api-Key header (interactive usage: \u002Flogin)\nexport ANTHROPIC_AUTH_TOKEN=\"my-auth-token\"           # Custom Authorization header; Claude adds \"Bearer \" prefix automatically\nexport ANTHROPIC_CUSTOM_HEADERS=\"X-Trace-Id: 12345\"   # Extra request headers (format: \"Name: Value\")\n\nexport ANTHROPIC_MODEL=\"claude-sonnet-4-6-20260217\"                # Custom model name to use\nexport ANTHROPIC_DEFAULT_SONNET_MODEL=\"claude-sonnet-4-6-20260217\" # Default Sonnet model alias\nexport ANTHROPIC_DEFAULT_OPUS_MODEL=\"claude-opus-4-6-20260130\"   # Default Opus model alias (Opus 4.6 now available)\nexport ANTHROPIC_SMALL_FAST_MODEL=\"haiku-model\"                  # Haiku-class model for background tasks (placeholder)\nexport ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=\"REGION\"            # Override AWS region for the small\u002Ffast model on Bedrock (placeholder)\n\nexport AWS_BEARER_TOKEN_BEDROCK=\"bedrock_...\"         # Amazon Bedrock API key\u002Ftoken for authentication\n\nexport BASH_DEFAULT_TIMEOUT_MS=60000                  # Default timeout (ms) for long-running bash commands\nexport BASH_MAX_TIMEOUT_MS=300000                     # Maximum timeout (ms) allowed for long-running bash commands\nexport BASH_MAX_OUTPUT_LENGTH=20000                   # Max characters in bash outputs before middle-truncation\n\nexport CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1     # (0 or 1) return to original project dir after each Bash command\nexport CLAUDE_BASH_NO_LOGIN=1                         # When set, BashTool does not use a login shell. Default behavior changed in v2.1.51 (login shell used only as fallback).\nexport CLAUDE_CODE_API_KEY_HELPER_TTL_MS=600000       # Interval (ms) to refresh creds when using apiKeyHelper\nexport CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL=1            # (0 or 1) skip auto-installation of IDE extensions\nexport CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096             # Max number of output tokens for most requests\n\nexport CLAUDE_CODE_USE_BEDROCK=1                      # (0 or 1) use Amazon Bedrock\nexport CLAUDE_CODE_USE_VERTEX=0                       # (0 or 1) use Google Vertex AI\nexport CLAUDE_CODE_SKIP_BEDROCK_AUTH=0                # (0 or 1) skip AWS auth for Bedrock (e.g., via LLM gateway)\nexport CLAUDE_CODE_SKIP_VERTEX_AUTH=0                 # (0 or 1) skip Google auth for Vertex (e.g., via LLM gateway)\n\nexport CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=0     # (0 or 1) disable nonessential traffic (equivalent to DISABLE_* below)\nexport CLAUDE_CODE_DISABLE_TERMINAL_TITLE=0           # (0 or 1) disable automatic terminal title updates\n\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1         # (0 or 1) enable agent teams research preview\nexport CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 # (0 or 1) load CLAUDE.md from --add-dir paths\nexport CLAUDE_CODE_ENABLE_TASKS=false                 # Set to \"false\" to disable new task system\n\nexport DISABLE_AUTOUPDATER=0                          # (0 or 1) disable automatic updates (overrides autoUpdates setting)\nexport DISABLE_BUG_COMMAND=0                          # (0 or 1) disable the \u002Fbug command\nexport DISABLE_COST_WARNINGS=0                        # (0 or 1) disable cost warning messages\nexport DISABLE_ERROR_REPORTING=0                      # (0 or 1) opt out of Sentry error reporting\nexport DISABLE_NON_ESSENTIAL_MODEL_CALLS=0            # (0 or 1) disable model calls for non-critical paths\nexport DISABLE_TELEMETRY=0                            # (0 or 1) opt out of Statsig telemetry\n\nexport HTTP_PROXY=\"http:\u002F\u002Fproxy:8080\"                 # HTTP proxy server URL\nexport HTTPS_PROXY=\"https:\u002F\u002Fproxy:8443\"               # HTTPS proxy server URL\n\nexport MAX_THINKING_TOKENS=0                          # (0 or 1 to turn off\u002Fon) force a thinking budget for the model\nexport MCP_TIMEOUT=120000                             # MCP server startup timeout (ms)\nexport MCP_TOOL_TIMEOUT=60000                         # MCP tool execution timeout (ms)\nexport MAX_MCP_OUTPUT_TOKENS=25000                    # Max tokens allowed in MCP tool responses (default 25000)\n\nexport USE_BUILTIN_RIPGREP=0                          # (0 or 1) set 0 to use system-installed rg instead of bundled one\n\nexport VERTEX_REGION_CLAUDE_3_5_HAIKU=\"REGION\"        # Region override for Claude 3.5 Haiku on Vertex AI (legacy model family name)\nexport VERTEX_REGION_CLAUDE_3_5_SONNET=\"REGION\"       # Region override for Claude 3.5 Sonnet on Vertex AI (legacy model family name)\nexport VERTEX_REGION_CLAUDE_3_7_SONNET=\"REGION\"       # Region override for Claude 3.7 Sonnet on Vertex AI (legacy model family name)\n# Note: CLAUDE_3_5_* and CLAUDE_3_7_* use legacy model family names and may be updated in future versions.\nexport VERTEX_REGION_CLAUDE_4_0_OPUS=\"REGION\"         # Region override for Claude 4.0 Opus on Vertex AI\nexport VERTEX_REGION_CLAUDE_4_0_SONNET=\"REGION\"       # Region override for Claude 4.0 Sonnet on Vertex AI\nexport VERTEX_REGION_CLAUDE_4_1_OPUS=\"REGION\"         # Region override for Claude 4.1 Opus on Vertex AI\nexport VERTEX_REGION_CLAUDE_4_6_OPUS=\"REGION\"         # Region override for Claude 4.6 Opus on Vertex AI\nexport VERTEX_REGION_CLAUDE_4_6_SONNET=\"REGION\"       # Region override for Claude 4.6 Sonnet on Vertex AI\n\n# ── New in v2.1.32–2.1.63 ──────────────────────────────────────────────────────\nexport CLAUDE_CODE_SIMPLE=1                            # Minimal mode: disables MCP tools, attachments, hooks, CLAUDE.md, and skills\nexport CLAUDE_CODE_DISABLE_1M_CONTEXT=1                # Disable 1 M-token context window (use default shorter context)\nexport CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1          # Disable background tasks entirely\nexport CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1        # Opt out of experimental beta features\nexport CLAUDE_CODE_AUTO_CONNECT_IDE=false              # Disable automatic IDE connection on startup\nexport CLAUDE_CODE_TMPDIR=\"\u002Fcustom\u002Ftmp\"                # Override the temp directory Claude Code uses\nexport CLAUDE_CODE_SHELL=\"\u002Fbin\u002Fzsh\"                    # Override shell detection (force a specific shell)\nexport CLAUDE_CODE_SHELL_PREFIX=\"command-wrapper\"      # Prefix\u002Fwrap every shell command Claude runs\nexport CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS=50000   # Override max output tokens for the Read tool\nexport CLAUDE_CODE_PROXY_RESOLVES_HOSTS=true           # Let the HTTP\u002FHTTPS proxy handle DNS resolution\nexport CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=30000         # Auto-exit SDK mode after idle for N ms\nexport CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS=30000         # Timeout (ms) for plugin git operations\nexport CLAUDE_CODE_ACCOUNT_UUID=\"uuid\"                 # Override account UUID (SDK \u002F automation flows)\nexport CLAUDE_CODE_USER_EMAIL=\"user@example.com\"       # Override user email (SDK \u002F automation flows)\nexport CLAUDE_CODE_ORGANIZATION_UUID=\"uuid\"            # Override organization UUID (SDK \u002F automation flows)\nexport ENABLE_CLAUDEAI_MCP_SERVERS=false               # Opt out from claude.ai-synced MCP servers\nexport FORCE_AUTOUPDATE_PLUGINS=1                      # Allow plugin auto-update even when main updater is disabled\nexport IS_DEMO=1                                       # Demo mode — hides email\u002Forg from the UI\nexport NO_PROXY=\"localhost,127.0.0.1\"                  # Bypass proxy for specified hosts (comma-separated)\n```\n\n\u003Ch2 id=\"global-config-options\">Global Config Options\u003C\u002Fh2>\n\n```bash\nclaude config set -g theme dark                               # Theme: dark | light | light-daltonized | dark-daltonized\nclaude config set -g preferredNotifChannel iterm2_with_bell   # Notification channel: iterm2 | iterm2_with_bell | terminal_bell | notifications_disabled\nclaude config set -g autoUpdates true                         # Auto-download & install updates (applied on restart)\nclaude config set -g verbose true                             # Show full bash\u002Fcommand outputs\n\nclaude config set -g attribution false                        # Omit \"co-authored-by Claude\" in git commits\u002FPRs\nclaude config set -g forceLoginMethod claudeai                 # Restrict login flow: claudeai | console\nclaude config set -g model \"claude-sonnet-4-6-20260217\"       # Default model override\nclaude config set -g statusLine '{\"type\":\"command\",\"command\":\"~\u002F.claude\u002Fstatusline.sh\"}'  # Custom status line\n\nclaude config set -g enableAllProjectMcpServers true              # Auto-approve all MCP servers from .mcp.json\nclaude config set -g enabledMcpjsonServers '[\"memory\",\"github\"]'  # Approve specific MCP servers\nclaude config set -g disabledMcpjsonServers '[\"filesystem\"]'      # Reject specific MCP servers\n```\n\n\u003Ch2 id=\"configuration-files\">Configuration Files\u003C\u002Fh2>\n\n**(Memory type) Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose:**\n\n| Memory Type                | Location                                                                                                                                                | Purpose                                             | Use Case Examples                                                    | Shared With                     |\n| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |\n| **Enterprise policy**      | macOS: `\u002FLibrary\u002FApplication Support\u002FClaudeCode\u002FCLAUDE.md`\u003Cbr \u002F>Linux: `\u002Fetc\u002Fclaude-code\u002FCLAUDE.md`\u003Cbr \u002F>Windows: `C:\\ProgramData\\ClaudeCode\\CLAUDE.md` | Organization-wide instructions managed by IT\u002FDevOps | Company coding standards, security policies, compliance requirements | All users in organization       |\n| **Project memory**         | `.\u002FCLAUDE.md`                                                                                                                                           | Team-shared instructions for the project            | Project architecture, coding standards, common workflows             | Team members via source control |\n| **User memory**            | `~\u002F.claude\u002FCLAUDE.md`                                                                                                                                   | Personal preferences for all projects               | Code styling preferences, personal tooling shortcuts                 | Just you (all projects)         |\n| **Project memory (local)** | `.\u002FCLAUDE.local.md`                                                                                                                                     | Personal project-specific preferences (git-ignored) | Your sandbox URLs, preferred test data, personal overrides           | Just you (current project)      |\n| **Project rules**          | `.claude\u002Frules\u002F*.md`                                                                                                                                    | Modular project rules (loaded alongside CLAUDE.md)  | Linting rules, API conventions, per-directory standards              | Team members via source control |\n\n> All memory files are automatically loaded into Claude Code's context when launched. Files higher in the hierarchy take precedence and are loaded first, providing a foundation that more specific memories build upon.\n\n#### `.claude\u002Frules\u002F` Directory (v2.0.64+)\n\nThe `.claude\u002Frules\u002F` directory lets you break project instructions into separate Markdown files instead of one large `CLAUDE.md`. Every `*.md` file inside is automatically loaded into context alongside `CLAUDE.md`. This is useful for:\n\n- **Modular organization**: Separate concerns (e.g., `api-conventions.md`, `testing-rules.md`)\n- **Per-directory overrides**: Nested `rules\u002F` directories can apply scoped rules\n- **Team collaboration**: Different team members can own different rule files via PR review\n\n#### Auto-Memory (v2.1.32+)\n\nClaude now automatically saves useful context to memory during your sessions. Managed memories include things like project conventions, tooling preferences, and architectural decisions that Claude observed while working with you. Use `\u002Fmemory` to view and manage auto-saved memories.\n\n---\n\n\u003Ch1 id=\"commands--usage\">Commands & Usage\u003C\u002Fh1>\n\n\u003Ch2 id=\"claude-commands\">Slash Command Reference\u003C\u002Fh2>\n\n| Command                   | Purpose                                                                                                  |\n| :------------------------ | :------------------------------------------------------------------------------------------------------- |\n| `\u002Fadd-dir`                | Add additional working directories                                                                       |\n| `\u002Fagents`                 | Manage custom AI subagents for specialized tasks                                                         |\n| `\u002Fbug`                    | Report bugs (sends conversation to Anthropic)                                                            |\n| `\u002Fclear`                  | Clear conversation history                                                                               |\n| `\u002Fcompact [instructions]` | Compact conversation with optional focus instructions                                                    |\n| `\u002Fconfig`                 | Open the Settings interface (Config tab)                                                                 |\n| `\u002Fcontext`                | Visualize current context usage as a colored grid                                                        |\n| `\u002Fcopy`                   | Copy conversation content to clipboard                                                                   |\n| `\u002Fcost`                   | Show token usage statistics and billing information                                                      |\n| `\u002Fdebug`                  | Troubleshoot current session and diagnose issues                                                         |\n| `\u002Fdoctor`                 | Checks the health of your Claude Code installation                                                       |\n| `\u002Fexit`                   | Exit the REPL                                                                                            |\n| `\u002Fexport [filename]`      | Export the current conversation to a file or clipboard                                                   |\n| `\u002Fextra-usage`            | Enable extra usage mode (required before `\u002Ffast`)                                                        |\n| `\u002Ffast`                   | Toggle fast mode for accelerated Opus 4.6 responses                                                      |\n| `\u002Ffork`                   | Fork the current conversation into a new session                                                         |\n| `\u002Fhelp`                   | Get usage help                                                                                           |\n| `\u002Finit`                   | Initialize project with CLAUDE.md guide                                                                  |\n| `\u002Finsights`               | Generate an interactive HTML report analyzing your coding habits                                         |\n| `\u002Fkeybindings`            | Configure custom keyboard shortcuts                                                                      |\n| `\u002Flogin`                  | Switch Anthropic accounts                                                                                |\n| `\u002Flogout`                 | Sign out from your Anthropic account                                                                     |\n| `\u002Fmcp`                    | Manage MCP server connections and OAuth authentication                                                   |\n| `\u002Fmemory`                 | Edit CLAUDE.md memory files                                                                              |\n| `\u002Fmodel`                  | Select or change the AI model                                                                            |\n| `\u002Fpermissions`            | View or update tool permissions                                                                          |\n| `\u002Fplan`                   | Enter plan mode directly from the prompt                                                                 |\n| `\u002Fplugins`                | Manage plugins (install, enable, disable, marketplace)                                                   |\n| `\u002Fpr_comments`            | View pull request comments                                                                               |\n| `\u002Frename \u003Cname>`          | Rename the current session for easier identification                                                     |\n| `\u002Fresume [session]`       | Resume a conversation by ID or name, or open session picker                                              |\n| `\u002Freview`                 | Request code review                                                                                      |\n| `\u002Frules`                  | View and manage `.claude\u002Frules\u002F` directory (modular project rules)                                       |\n| `\u002Frewind`                 | Rewind the conversation and\u002For code to a previous point                                                  |\n| `\u002Fsandbox`                | View sandbox dependency status with installation instructions                                            |\n| `\u002Fstats`                  | Visualize daily usage, session history, streaks, and model preferences                                   |\n| `\u002Fsettings`               | Open Settings interface (alias for `\u002Fconfig`)                                                            |\n| `\u002Fsimplify`               | Simplify selected code or conversation (bundled skill)                                                   |\n| `\u002Fstatus`                 | Open Settings interface (Status tab) showing version, model, account                                     |\n| `\u002Fstatusline`             | Set up Claude Code's status line UI                                                                      |\n| `\u002Ftasks`                  | List and manage background tasks                                                                         |\n| `\u002Fteleport`               | Resume a remote session from claude.ai (subscribers only)                                                |\n| `\u002Fterminal-setup`         | Install Shift+Enter key binding for newlines (iTerm2, VS Code, Kitty, Alacritty, Zed, Warp, and WezTerm) |\n| `\u002Fremote-env`             | Configure remote environment settings                                                                    |\n| `\u002Ftheme`                  | Change the color theme                                                                                   |\n| `\u002Ftodos`                  | List current TODO items                                                                                  |\n| `\u002Fusage`                  | Show plan usage limits and rate limit status (subscription plans)                                        |\n| `\u002Fvim`                    | Enter vim mode for alternating insert and command modes                                                  |\n| `\u002Fbatch`                  | Run batch operations on multiple files (bundled skill)                                                   |\n\n\u003Ch2 id=\"command-line-flags\">Command Line Flags\u003C\u002Fh2>\n\n| Flag \u002F Command                                       | Description                                                                                                                                                  | Example                                                                                |\n| :--------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------- |\n| `-d, --debug`                                        | Enable debug mode (shows detailed debug output).                                                                                                             | `claude -d -p \"query\"`                                                                 |\n| `--include-partial-messages`                         | partial message streaming support via CLI flag                                                                                                               |\n| `--mcp-debug`                                        | [DEPRECATED] MCP debug mode (shows MCP server errors). Use `--debug` instead.                                                                                | `claude --mcp-debug`                                                                   |\n| `--verbose`                                          | Override verbose mode setting from config (shows expanded logging \u002F turn-by-turn output).                                                                    | `claude --verbose`                                                                     |\n| `-p, --print`                                        | Print response and exit (useful for piping output).                                                                                                          | `claude -p \"query\"`                                                                    |\n| `--output-format \u003Cformat>`                           | Output format (only works with `--print`): `text` (default), `json` (single result), or `stream-json` (realtime streaming).                                  | `claude -p \"query\" --output-format json`                                               |\n| `--input-format \u003Cformat>`                            | Input format (only works with `--print`): `text` (default) or `stream-json` (realtime streaming input).                                                      | `claude -p --output-format stream-json --input-format stream-json`                     |\n| `--replay-user-messages`                             | Re-emit user messages from stdin back to stdout for acknowledgment — **only works with** `--input-format=stream-json` **and** `--output-format=stream-json`. | `claude --input-format stream-json --output-format stream-json --replay-user-messages` |\n| `--allowedTools`, `--allowed-tools \u003Ctools...>`       | Comma\u002Fspace-separated list of tool names to allow (e.g. `\"Bash(git:*) Edit\"`).                                                                               | `--allowed-tools \"Bash(git:*)\" Edit\"`                                                  |\n| `--disallowedTools`, `--disallowed-tools \u003Ctools...>` | Comma\u002Fspace-separated list of tool names to deny (e.g. `\"Bash(git:*) Edit\"`).                                                                                | `--disallowed-tools \"Edit\"`                                                            |\n| `--mcp-config \u003Cconfigs...>`                          | Load MCP servers from JSON files or strings (space-separated).                                                                                               | `claude --mcp-config .\u002Fmcp-servers.json`                                               |\n| `--strict-mcp-config`                                | Only use MCP servers from `--mcp-config`, ignoring other MCP configurations.                                                                                 | `claude --mcp-config .\u002Fa.json --strict-mcp-config`                                     |\n| `--append-system-prompt \u003Cprompt>`                    | Append a system prompt to the default system prompt (useful in print mode).                                                                                  | `claude -p --append-system-prompt \"Do X then Y\"`                                       |\n| `--permission-mode \u003Cmode>`                           | Permission mode for the session (choices include `acceptEdits`, `bypassPermissions`, `default`, `plan`).                                                     | `claude --permission-mode plan`                                                        |\n| `--permission-prompt-tool \u003Ctool>`                    | Specify an MCP tool to handle permission prompts in non-interactive mode.                                                                                    | `claude -p --permission-prompt-tool mcp_auth_tool \"query\"`                             |\n| `--fallback-model \u003Cmodel>`                           | Enable automatic fallback to a specified model when the default is overloaded (note: only works with `--print` per help).                                    | `claude -p --fallback-model claude-haiku-20240307 \"query\"`                             |\n| `--model \u003Cmodel>`                                    | Model for the current session. Accepts aliases like `sonnet`\u002F`opus` or a full model name (e.g. `claude-sonnet-4-6-20260217`).                                | `claude --model sonnet`                                                                |\n| `--settings \u003Cfile-or-json>`                          | Load additional settings from a JSON file or a JSON string.                                                                                                  | `claude --settings .\u002Fsettings.json`                                                    |\n| `--add-dir \u003Cdirectories...>`                         | Additional directories to allow tool access to.                                                                                                              | `claude --add-dir ..\u002Fapps ..\u002Flib`                                                      |\n| `--ide`                                              | Automatically connect to an IDE on startup if exactly one valid IDE is available.                                                                            | `claude --ide`                                                                         |\n| `-c, --continue`                                     | Continue the most recent conversation in the current directory.                                                                                              | `claude --continue`                                                                    |\n| `-r, --resume [sessionId]`                           | Resume a conversation; provide a session ID or interactively select one.                                                                                     | `claude -r \"abc123\"`                                                                   |\n| `--session-id \u003Cuuid>`                                | Use a specific session ID for the conversation (must be a valid UUID).                                                                                       | `claude --session-id 123e4567-e89b-12d3-a456-426614174000`                             |\n| `--agents \u003Cjson>`                                    | Define custom subagents dynamically via JSON (see subagent docs for format).                                                                                 | `claude --agents '{\"reviewer\":{\"description\":\"Reviews code\",\"prompt\":\"...\"}}'`         |\n| `--agent \u003Cname>`                                     | Specify a specific agent for the current session.                                                                                                            | `claude --agent my-custom-agent`                                                       |\n| `--chrome`                                           | Enable Chrome browser integration for web automation and testing.                                                                                            | `claude --chrome`                                                                      |\n| `--no-chrome`                                        | Disable Chrome browser integration for this session.                                                                                                         | `claude --no-chrome`                                                                   |\n| `--remote`                                           | Create a new web session on claude.ai with the provided task description.                                                                                    | `claude --remote \"Fix the login bug\"`                                                  |\n| `--teleport`                                         | Resume a web session in your local terminal.                                                                                                                 | `claude --teleport`                                                                    |\n| `--fork-session`                                     | When resuming, create a new session ID instead of reusing the original.                                                                                      | `claude --resume abc123 --fork-session`                                                |\n| `--json-schema \u003Cschema>`                             | Get validated JSON output matching a JSON Schema after agent completes (print mode only).                                                                    | `claude -p --json-schema '{\"type\":\"object\",...}' \"query\"`                              |\n| `--max-budget-usd \u003Camount>`                          | Maximum dollar amount to spend on API calls before stopping (print mode only).                                                                               | `claude -p --max-budget-usd 5.00 \"query\"`                                              |\n| `--max-turns \u003Cn>`                                    | Limit the number of agentic turns (print mode only). Exits with error when limit reached.                                                                    | `claude -p --max-turns 3 \"query\"`                                                      |\n| `--betas \u003Cheaders>`                                  | Beta headers to include in API requests (API key users only).                                                                                                | `claude --betas interleaved-thinking`                                                  |\n| `--tools \u003Ctools>`                                    | Restrict which built-in tools Claude can use. Use \"\" to disable all, \"default\" for all, or specific tool names.                                              | `claude --tools \"Bash,Edit,Read\"`                                                      |\n| `--system-prompt \u003Cprompt>`                           | Replace the entire system prompt with custom text (works in interactive and print modes).                                                                    | `claude --system-prompt \"You are a Python expert\"`                                     |\n| `--system-prompt-file \u003Cfile>`                        | Load system prompt from a file, replacing the default prompt (print mode only).                                                                              | `claude -p --system-prompt-file .\u002Fcustom-prompt.txt \"query\"`                           |\n| `--append-system-prompt-file \u003Cfile>`                 | Load additional system prompt text from a file and append to default (print mode only).                                                                      | `claude -p --append-system-prompt-file .\u002Fextra-rules.txt \"query\"`                      |\n| `--plugin-dir \u003Cdir>`                                 | Load plugins from directories for this session only (repeatable).                                                                                            | `claude --plugin-dir .\u002Fmy-plugins`                                                     |\n| `--setting-sources \u003Csources>`                        | Comma-separated list of setting sources to load (user, project, local).                                                                                      | `claude --setting-sources user,project`                                                |\n| `--no-session-persistence`                           | Disable session persistence so sessions are not saved to disk (print mode only).                                                                             | `claude -p --no-session-persistence \"query\"`                                           |\n| `--disable-slash-commands`                           | Disable all skills and slash commands for this session.                                                                                                      | `claude --disable-slash-commands`                                                      |\n| `--dangerously-skip-permissions`                     | Bypass all permission checks (only for trusted sandboxes).                                                                                                   | `claude --dangerously-skip-permissions`                                                |\n| `--worktree`, `-w`                                   | Start in an isolated git worktree (v2.1.49).                                                                                                                 | `claude -w \"implement feature\"`                                                        |\n| `--from-pr \u003Curl>`                                    | Start session from a pull request URL (v2.1.27).                                                                                                             | `claude --from-pr https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\u002Fpull\u002F123`                                |\n| `--init`                                             | Trigger Setup hook event (v2.1.10).                                                                                                                          | `claude --init`                                                                        |\n| `--init-only`                                        | Run Setup hook and exit (v2.1.10).                                                                                                                           | `claude --init-only`                                                                   |\n| `--maintenance`                                      | Run Setup hook in maintenance mode (v2.1.10).                                                                                                                | `claude --maintenance`                                                                 |\n| `-v, --version`                                      | Show the installed `claude` CLI version.                                                                                                                     | `claude --version`                                                                     |\n| `-h, --help`                                         | Display help \u002F usage.                                                                                                                                        | `claude --help`                                                                        |\n\n> The `--output-format json` flag is particularly useful for scripting and automation, allowing you to parse Claude's responses programmatically.\n\n\u003Ch2 id=\"cheat-sheet\">CLI Quick Reference & Configuration Examples\u003C\u002Fh2>\n\n```md\n## Claude Cheat Sheet\n\n# Basics \u002F interactive\n\nclaude # Start interactive REPL\nclaude \"explain this project\" # Start REPL seeded with a prompt\nclaude -p \"summarize README.md\" # Non-interactive print mode (SDK-backed)\ncat logs.txt | claude -p \"explain\" # Pipe input to Claude and exit\nclaude -c # Continue most recent conversation (alias for --continue)\nclaude -r \"\u003Csession-id>\" \"finish this\" # Resume specific session by ID (alias for --resume)\nclaude --model claude-sonnet-4-6-20260217 # Pick model for this run\nclaude --max-turns 3 -p \"lint this\" # Cap agentic turns in print mode\nclaude --replay-user-messages # Replay user messages to stdout for debugging \u002F SDK workflows\n\n# Update & install\n\nclaude update # Manually update Claude Code\nclaude doctor # Diagnose install\u002Fversion & setup\nclaude install # Start native binary installer (beta)\nclaude migrate-installer # Migrate from global npm to local installer\n\n# Authentication (v2.1.41+)\n\nclaude auth login # Log in to your Anthropic account\nclaude auth status # Check authentication status\nclaude auth logout # Log out\n\n# Agent management (v2.1.50+)\n\nclaude agents # List all configured agents (project, user, plugin)\nclaude remote-control # Start remote-control mode for external tooling\n\n# Config: interactive wizard + direct ops\n\nclaude config # Interactive config wizard\nclaude config get \u003Ckey> # Get value (e.g., claude config get theme)\nclaude config set \u003Ckey> \u003Cval> # Set value (e.g., claude config set theme dark)\nclaude config add \u003Ckey> \u003Cvals…> # Append to array-type keys (e.g., claude config add env DEV=1)\nclaude config remove \u003Ckey> \u003Cvals…> # Remove items from list-type keys\nclaude config list # Show all current settings for project (project scope is default)\n\n# Example project-scoped settings\n\nclaude config set model \"claude-sonnet-4-6-20260217\" # Override default model for this project\nclaude config set attribution false # Disable \"co-authored-by Claude\" byline in git\u002FPRs\nclaude config set forceLoginMethod claudeai # Restrict login flow: claudeai | console\nclaude config set enableAllProjectMcpServers true # Auto-approve all MCP servers from .mcp.json\nclaude config set defaultMode \"acceptEdits\" # Set default permission mode\nclaude config set disableBypassPermissionsMode disable # Prevent bypassPermissions mode (example key)\n\n# Manage list settings (project scope)\n\nclaude config add enabledMcpjsonServers github # Approve a specific MCP server from .mcp.json\nclaude config add enabledMcpjsonServers memory # Add another\nclaude config remove enabledMcpjsonServers memory # Remove one entry\nclaude config add disabledMcpjsonServers filesystem # Explicitly reject a specific MCP server\n\n# Global scope (use -g or --global)\n\nclaude config set -g autoUpdates false # Turn off automatic updates globally\nclaude config set --global preferredNotifChannel iterm2_with_bell\nclaude config set -g theme dark # Theme: dark | light | light-daltonized | dark-daltonized\nclaude config set -g verbose true # Show full bash\u002Fcommand outputs everywhere\nclaude config get -g theme # Confirm a global value\n\n# MCP (Model Context Protocol) management\n\nclaude mcp # Launch MCP wizard \u002F configure MCP servers\nclaude mcp list # List configured MCP servers\nclaude mcp get \u003Cname> # Show details for a server\nclaude mcp remove \u003Cname> # Remove a server\nclaude mcp add \u003Cname> \u003Ccommand> [args...] # Add local stdio server\nclaude mcp add --transport sse \u003Cname> \u003Curl> # Add remote SSE server\nclaude mcp add --transport http \u003Cname> \u003Curl> # Add remote HTTP server\nclaude mcp add \u003Cname> --env KEY=VALUE -- \u003Ccmd> [args...] # Pass env to server command\nclaude mcp add --transport sse private-api https:\u002F\u002Fapi.example\u002Fmcp \\\n --header \"Authorization: Bearer TOKEN\" # Add with auth header\nclaude mcp add-json \u003Cname> '\u003Cjson>' # Add server via JSON blob\nclaude mcp add-from-claude-desktop # Import servers from Claude Desktop\nclaude mcp reset-project-choices # Reset approvals for project .mcp.json servers\nclaude mcp serve # Run Claude Code itself as an MCP stdio server\n\n# Other useful flags (print \u002F SDK mode)\n\nclaude --add-dir ..\u002Fapps ..\u002Flib # Add additional working directories\nclaude --allowedTools \"Bash(git log:\\*)\" \"Read\" # Allow listed tools without permission prompts\nclaude --disallowedTools \"Edit\" # Disallow listed tools without permission prompts\nclaude --append-system-prompt \"Custom instruction\" # Append to system prompt (only with -p)\nclaude -p \"query\" --output-format json --input-format stream-json # Control IO formats for scripting\nclaude --verbose # Verbose logging (turn-by-turn)\nclaude --dangerously-skip-permissions # Skip permission prompts (use with caution)\nclaude --permission-mode plan # Start in plan mode (read-only analysis)\nclaude --max-turns 3 -p \"query\" # Limit agentic turns (print mode only)\nclaude --max-budget-usd 5.00 -p \"query\" # Cap spending per session (print mode only)\nclaude --json-schema '{\"type\":\"object\"}' -p \"query\" # Get validated JSON output\nclaude --chrome # Enable Chrome browser integration\nclaude --remote \"Fix the bug\" # Create web session on claude.ai\nclaude --teleport # Resume web session locally\nclaude --agents '{\"name\":{...}}' # Define subagents via JSON\n\n# Session management\n\nclaude -c # Continue most recent conversation\nclaude -r \"session-name\" # Resume by name or ID\nclaude --fork-session -r abc123 # Fork instead of reusing original\nclaude -w \"implement feature\" # Start in an isolated git worktree\n\u002Frename auth-refactor # Name current session\n\u002Fresume # Open session picker\n\u002Fexport output.md # Export conversation to file\n\u002Ffork # Fork the current conversation\n\n# Quick verification \u002F notes\n\n# - Project scope is default for 'claude config'; use -g\u002F--global to affect all projects.\n\n# - Settings precedence: Enterprise > CLI args > local project > shared project > user (~\u002F.claude).\n\n# - Use 'add' \u002F 'remove' only with list-type keys (e.g., enabledMcpjsonServers).\n\n# - The CLI reference and release notes are the authoritative sources for flags and recent additions.\n```\n\n---\n\n\u003Ch1 id=\"interface--input\">Interface & Input\u003C\u002Fh1>\n\n\u003Ch2 id=\"keyboard-shortcuts\">Keyboard Shortcuts\u003C\u002Fh2>\n\n| Shortcut                     | Description                        | Context                                  |\n| :--------------------------- | :--------------------------------- | :--------------------------------------- |\n| `Ctrl+C`                     | Cancel current input or generation | Standard interrupt                       |\n| `Ctrl+D`                     | Exit Claude Code session           | EOF signal                               |\n| `Ctrl+G`                     | Open in default text editor        | Edit your prompt or custom response      |\n| `Ctrl+L`                     | Clear terminal screen              | Keeps conversation history               |\n| `Ctrl+O`                     | Toggle verbose output              | Shows detailed tool usage and execution  |\n| `Ctrl+R`                     | Reverse search command history     | Search through previous commands         |\n| `Ctrl+V` or `Cmd+V` (iTerm2) | Paste image from clipboard         | Pastes an image or path to an image file |\n| `Ctrl+B`                     | Background running tasks           | Backgrounds bash commands and agents     |\n| `Ctrl+F` (press twice)       | Kill all background agents         | Two-press confirmation to stop agents    |\n| `Up\u002FDown arrows`             | Navigate command history           | Recall previous inputs                   |\n| `Left\u002FRight arrows`          | Cycle through dialog tabs          | Navigate between tabs in dialogs         |\n| `Esc` + `Esc`                | Rewind the code\u002Fconversation       | Restore to a previous point              |\n| `Shift+Tab` or `Alt+M`       | Toggle permission modes            | Switch between Auto-Accept, Plan, Normal |\n| `Option+P` (macOS) \u002F `Alt+P` | Switch model                       | Switch models without clearing prompt    |\n| `Option+T` (macOS) \u002F `Alt+T` | Toggle extended thinking           | Enable\u002Fdisable extended thinking mode    |\n\n\u003Ch3 id=\"text-editing\">Text Editing\u003C\u002Fh3>\n\n| Shortcut               | Description                  | Context                               |\n| :--------------------- | :--------------------------- | :------------------------------------ |\n| `Ctrl+K`               | Delete to end of line        | Stores deleted text for pasting       |\n| `Ctrl+U`               | Delete entire line           | Stores deleted text for pasting       |\n| `Ctrl+Y`               | Paste deleted text           | Paste text deleted with Ctrl+K\u002FU      |\n| `Alt+Y` (after Ctrl+Y) | Cycle paste history          | Cycle through previously deleted text |\n| `Alt+B`                | Move cursor back one word    | Requires Option as Meta on macOS      |\n| `Alt+F`                | Move cursor forward one word | Requires Option as Meta on macOS      |\n\n\u003Ch3 id=\"multiline-input\">Multiline Input\u003C\u002Fh3>\n\n| Method           | Shortcut       | Context                           |\n| :--------------- | :------------- | :-------------------------------- |\n| Quick escape     | `\\` + `Enter`  | Works in all terminals            |\n| macOS default    | `Option+Enter` | Default on macOS                  |\n| Terminal setup   | `Shift+Enter`  | After `\u002Fterminal-setup`           |\n| Control sequence | `Ctrl+J`       | Line feed character for multiline |\n| Paste mode       | Paste directly | For code blocks, logs             |\n\n\u003Ch3 id=\"quick-commands\">Quick Commands\u003C\u002Fh3>\n\n| Shortcut     | Description       | Notes                                 |\n| :----------- | :---------------- | :------------------------------------ |\n| `\u002F` at start | Command or skill  | See built-in commands and skills      |\n| `!` at start | Bash mode         | Run commands directly, add to context |\n| `@`          | File path mention | Trigger file path autocomplete        |\n\n> [!Tip]\n> **PDF Page Ranges:** Use the `pages` parameter with the Read tool for PDFs (e.g., `pages: \"1-5\"`). Large PDFs (>10 pages) return a lightweight reference when @-mentioned instead of being inlined.\n\n\u003Ch2 id=\"vim-mode\">Vim Mode\u003C\u002Fh2>\n\n> [!Note]\n> Enable vim-style editing with `\u002Fvim` command or configure permanently via `\u002Fconfig`.\n\n\u003Ch3 id=\"vim-mode-switching\">Vim Mode Switching\u003C\u002Fh3>\n\n| Command | Action                      | From mode |\n| :------ | :-------------------------- | :-------- |\n| `Esc`   | Enter NORMAL mode           | INSERT    |\n| `i`     | Insert before cursor        | NORMAL    |\n| `I`     | Insert at beginning of line | NORMAL    |\n| `a`     | Insert after cursor         | NORMAL    |\n| `A`     | Insert at end of line       | NORMAL    |\n| `o`     | Open line below             | NORMAL    |\n| `O`     | Open line above             | NORMAL    |\n\n\u003Ch3 id=\"vim-navigation\">Vim Navigation\u003C\u002Fh3>\n\n| Command         | Action                    |\n| :-------------- | :------------------------ |\n| `h`\u002F`j`\u002F`k`\u002F`l` | Move left\u002Fdown\u002Fup\u002Fright   |\n| `w`             | Next word                 |\n| `e`             | End of word               |\n| `b`             | Previous word             |\n| `0`             | Beginning of line         |\n| `$`             | End of line               |\n| `^`             | First non-blank character |\n| `gg`            | Beginning of input        |\n| `G`             | End of input              |\n\n\u003Ch3 id=\"vim-editing\">Vim Editing\u003C\u002Fh3>\n\n| Command        | Action                  |\n| :------------- | :---------------------- |\n| `x`            | Delete character        |\n| `dd`           | Delete line             |\n| `D`            | Delete to end of line   |\n| `dw`\u002F`de`\u002F`db` | Delete word\u002Fto end\u002Fback |\n| `cc`           | Change line             |\n| `C`            | Change to end of line   |\n| `cw`\u002F`ce`\u002F`cb` | Change word\u002Fto end\u002Fback |\n| `.`            | Repeat last change      |\n\n> [!Tip]\n> Configure your preferred line break behavior in terminal settings. Run `\u002Fterminal-setup` to install Shift+Enter binding for iTerm2, VS Code, Kitty, Alacritty, Zed, Warp, and WezTerm.\n\n\u003Ch2 id=\"command-history\">Command History\u003C\u002Fh2>\n\n> Claude Code maintains command history for the current session:\n\n```\n* History is stored per working directory\n* Cleared with `\u002Fclear` command\n* Use Up\u002FDown arrows to navigate (see keyboard shortcuts above)\n* **Ctrl+R**: Reverse search through history (if supported by terminal)\n* **Note**: History expansion (`!`) is disabled by default\n```\n\n---\n\n\u003Ch1 id=\"advanced-features\">Advanced Features\u003C\u002Fh1>\n\n\u003Ch2 id=\"thinking-keywords\">Thinking Keywords\u003C\u002Fh2>\n\n> [!Note]\n> **Gives Claude extra pre-answer planning time by adding ONE of these keywords to your prompt.**\n> **Order (lowest → highest) token consumption**\n>\n> \u003Ctable>\u003Ctr>\u003Ctd>\n>\n> > **\u003Ckbd>think\u003C\u002Fkbd> -------------> Lowest**\n>\n> > **\u003Ckbd>think hard\u003C\u002Fkbd>**\n>\n> > **\u003Ckbd>think harder\u003C\u002Fkbd>**\n>\n> > **\u003Ckbd>ultrathink\u003C\u002Fkbd> --------> Highest**\n>\n> \u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftable>\n\n\u003Ch3 id=\"this-makes-claude-spend-more-time\">This makes Claude spend more time:\u003C\u002Fh3>\n\n1. **Planning the solution**\n2. #### breaking down steps\n3. #### weighing alternatives\u002Ftrade-offs\n4. #### checking constraints & edge cases\n   > > #### Higher levels usually increase **latency** and **token usage** pick the smallest that works.\n\n\u003Ch5 id=\"thinking-examples\">Examples\u003C\u002Fh5>\n\n```md\n# Small boost\n\nclaude -p \"Think. Outline a plan to refactor the auth module.\"\n\n# Medium boost\n\nclaude -p \"Think harder. Draft a migration plan from REST to gRPC.\"\n\n# Max boost\n\nclaude -p \"Ultrathink. Propose a step-by-step strategy to fix flaky payment tests and add guardrails.\"\n```\n\n\u003Ch2 id=\"fast-mode\">Fast Mode\u003C\u002Fh2>\n\n> [!Note]\n> **Fast Mode provides accelerated response times for Opus 4.6, optimized for rapid iteration and quick tasks.**\n\n**How to enable Fast Mode:**\n\n```bash\n# Enable fast mode in the REPL (requires extra-usage first)\n\u002Fextra-usage\n\u002Ffast\n\n# Or toggle during conversation\n# The status bar will show when Fast Mode is active\n```\n\n**Key features:**\n\n- **Faster responses** - Reduced latency for quick tasks\n- **Available for Opus 4.6** - New in version 2.1.36\n- **Requires extra-usage** - Must enable `\u002Fextra-usage` first\n\n**When to use Fast Mode:**\n\n- Quick code reviews and edits\n- Rapid prototyping\n- Simple questions and commands\n- Iterative debugging\n\n> Fast Mode trades some depth for speed. Use normal mode for complex analysis and planning tasks.\n\n\u003Ch2 id=\"plan-mode\">Plan Mode\u003C\u002Fh2>\n\n> [!Note]\n> **Plan Mode instructs Claude to analyze the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely.**\n\n**When to use Plan Mode:**\n\n- **Multi-step implementation**: When your feature requires making edits to many files\n- **Code exploration**: When you want to research the codebase thoroughly before changing anything\n- **Interactive development**: When you want to iterate on the direction with Claude\n\n**How to enable Plan Mode:**\n\n```bash\n# Start a new session in Plan Mode\nclaude --permission-mode plan\n\n# Or toggle during session with Shift+Tab\n# (cycles through: Normal → Auto-Accept → Plan Mode)\n\n# Enter plan mode from the prompt\n\u002Fplan\n\n# Run headless queries in Plan Mode\nclaude --permission-mode plan -p \"Analyze the authentication system and suggest improvements\"\n```\n\n**Configure Plan Mode as default:**\n\n```json\n\u002F\u002F .claude\u002Fsettings.json\n{\n  \"permissions\": {\n    \"defaultMode\": \"plan\"\n  }\n}\n```\n\n---\n\n\u003Ch2 id=\"background-tasks\">Background Tasks\u003C\u002Fh2>\n\n> [!Note]\n> **Claude Code supports running bash commands in the background, allowing you to continue working while long-running processes execute.**\n\n**How to use background tasks:**\n\n| Method        | Description                                                                |\n| :------------ | :------------------------------------------------------------------------- |\n| Prompt Claude | Ask Claude to \"run this in the background\"                                 |\n| `Ctrl+B`      | Move a running Bash tool invocation to background (tmux users press twice) |\n\n**Key features:**\n\n- Output is buffered and Claude can retrieve it using the TaskOutput tool\n- Background tasks have unique IDs for tracking and output retrieval\n- Background tasks are automatically cleaned up when Claude Code exits\n- Use `\u002Ftasks` to list and manage background tasks\n\n**Common backgrounded commands:**\n\n- Build tools (webpack, vite, make)\n- Package managers (npm, yarn, pnpm)\n- Test runners (jest, pytest)\n- Development servers\n- Long-running processes (docker, terraform)\n\n**Bash mode with `!` prefix:**\n\n```bash\n# Run bash commands directly without Claude interpretation\n! npm test\n! git status\n! ls -la\n```\n\n**Disable background tasks:**\n\n```bash\nexport CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1\n```\n\n---\n\n\u003Ch2 id=\"remote-sessions\">Remote Sessions\u003C\u002Fh2>\n\n> [!Note]\n> **For subscribers: Use `--remote` to start tasks on claude.ai and `--teleport` to resume them locally.**\n\n**Start a remote session:**\n\n```bash\n# Create a new web session on claude.ai with task description\nclaude --remote \"Fix the login bug\"\n```\n\n**Resume a remote session:**\n\n```bash\n# Resume a web session in your local terminal\nclaude --teleport\n\n# Or use the slash command\n\u002Fteleport\n```\n\n---\n\n\u003Ch2 id=\"claude-in-chrome\">Claude in Chrome\u003C\u002Fh2>\n\nClaude Code can control Google Chrome for browser-based tasks like testing, web scraping, and UI verification.\n\n**Setup:**\n\n```bash\nclaude --chrome                    # Launch with Chrome integration\n```\n\n**Capabilities:**\n\n- Navigate to URLs, click elements, fill forms\n- Take screenshots and analyze page content\n- Execute JavaScript in the browser context\n- Interact with web applications for testing\n\n> [!NOTE]\n> Requires Google Chrome installed. Claude uses the Chrome DevTools Protocol for browser control.\n\n---\n\n\u003Ch2 id=\"sandbox-mode\">Sandbox Mode\u003C\u002Fh2>\n\nSandbox mode restricts the BashTool to run commands in an isolated environment, preventing modifications to your actual filesystem.\n\n```bash\n\u002Fsandbox              # Toggle sandbox mode on\u002Foff\n```\n\n**When sandboxed:**\n\n- File system writes are contained\n- Network access may be restricted\n- Useful for testing destructive commands safely\n\nAvailable on Linux and macOS. Use `claude --sandbox` to start in sandbox mode.\n\n---\n\n\u003Ch2 id=\"lsp-tool\">LSP Tool (Language Server Protocol)\u003C\u002Fh2>\n\nClaude Code integrates with language servers to provide IDE-level code intelligence:\n\n- **Go to Definition** — Jump to where a symbol is defined\n- **Find References** — Find all usages of a symbol across the codebase\n- **Hover Information** — Get type information and documentation\n\nThe LSP tool activates automatically when a compatible language server is available for the current project. This enables Claude to navigate codebases more precisely than text search alone.\n\n> Tool results exceeding 50,000 characters are automatically persisted to disk to manage context efficiently.\n\n---\n\n\u003Ch2 id=\"sub-agents\">Sub Agents\u003C\u002Fh2>\n\n> Sub‑Agents are purpose‑built helpers with their **own prompts, tools, and isolated context windows**. Treat this like a \"mixture‑of‑experts\" you **compose** per repo.\n\n\u003Ch3 id=\"built-in-subagents\">Built-in Subagents\u003C\u002Fh3>\n\nClaude Code includes built-in subagents that Claude automatically uses when appropriate:\n\n| Subagent            | Model        | Tools     | Purpose                                           |\n| :------------------ | :----------- | :-------- | :------------------------------------------------ |\n| **Explore**         | Haiku (fast) | Read-only | File discovery, code search, codebase exploration |\n| **Plan**            | Configurable | Read-only | Planning complex changes without making edits     |\n| **General-purpose** | Default      | Inherited | General task delegation                           |\n\n> Claude delegates to **Explore** when it needs to search or understand a codebase without making changes, keeping exploration results out of your main conversation context.\n\n**When to use subagents:**\n\n> - You need high signal responses (plans, reviews, diffs) without side quests.\n> - You want version‑controlled prompts and tool policies alongside the codebase.\n> - You work in PR‑driven teams and want scoped edits by role.\n> - The task produces verbose output you don't need in your main context.\n\n\u003Ch3 id=\"each-sub-agent-has-its-own-context\">Each Sub‑Agent Has Its Own Context\u003C\u002Fh3>\n\n**Design rules for your lineup**\n\n> - Define **one clear responsibility** per agent.\n> - Keep the **minimum** tool set needed for that role.\n> - Prefer **read‑only** agents for analysis\u002Freview tasks.\n> - Give edit powers to as few agents as possible.\n\n\u003Cimg width=\"700\" height=\"160\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_826a82b979ad.png\" \u002F>\n\n_Caption: Agents selection UI in the terminal._\n\n\u003Ch3 id=\"configure-agents\">Configure Agents\u003C\u002Fh3>\n\n> Keep agents **in the project** so they're versioned with the repo and evolve via PRs.\n\n\u003Ch3 id=\"agents-quick-start\">Quick start\u003C\u002Fh3>\n\n> Update CLI and open the agents panel\n\n```bash\nclaude update\n\u002Fagents\n```\n\n\u003Ch3 id=\"agent-scopes\">Subagent Scopes\u003C\u002Fh3>\n\n| Location                     | Scope                   | Priority    |\n| :--------------------------- | :---------------------- | :---------- |\n| `--agents` CLI flag          | Current session only    | 1 (highest) |\n| `.claude\u002Fagents\u002F`            | Current project         | 2           |\n| `~\u002F.claude\u002Fagents\u002F`          | All your projects       | 3           |\n| Plugin's `agents\u002F` directory | Where plugin is enabled | 4 (lowest)  |\n\n\u003Ch3 id=\"define-agents-via-cli\">Define Agents via CLI\u003C\u002Fh3>\n\n```bash\n# Define custom subagents dynamically via JSON\nclaude --agents '{\n  \"code-reviewer\": {\n    \"description\": \"Expert code reviewer. Use proactively after code changes.\",\n    \"prompt\": \"You are a senior code reviewer. Focus on code quality, security, and best practices.\",\n    \"tools\": [\"Read\", \"Grep\", \"Glob\", \"Bash\"],\n    \"model\": \"sonnet\"\n  },\n  \"debugger\": {\n    \"description\": \"Debugging specialist for errors and test failures.\",\n    \"prompt\": \"You are an expert debugger. Analyze errors, identify root causes, and provide fixes.\"\n  },\n  \"background-impl\": {\n    \"description\": \"Implements features in an isolated worktree in the background.\",\n    \"prompt\": \"Implement the requested feature. Commit when done.\",\n    \"isolation\": \"worktree\",\n    \"background\": true\n  }\n}'\n```\n\n\u003Ch3 id=\"create-your-core-agents\">Create your core agents\u003C\u002Fh3>\n\n> - **planner** (read‑only): turns features\u002Fissues into small, testable tasks; outputs a task list or plan.md.\n> - **codegen** (edit‑capable): implements tasks; limited to `src\u002F` + `tests\u002F`.\n> - **tester** (read‑only or patch‑only): writes _one_ failing test or a minimal repro.\n> - **reviewer** (read‑only): leaves structured review comments; never edits.\n> - **docs** (edit‑capable): updates `README.md`\u002F`docs\u002F` only.\n\n**\\*Policy** tip: Prefer **patch output** for edit‑capable agents so changes land through your normal Git workflow.\\*\n\n\u003Cimg width=\"700\" height=\"173\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_598513197c9a.png\" \u002F>\n\n_Caption: Choose only the tools an agent truly needs (e.g., advisory vs editing access)._\n\n\u003Ch3 id=\"example-prompts\">Example prompts\u003C\u002Fh3>\n\n> Keep prompts short, testable, and repo‑specific. Check them into `agents\u002F`:\n\n\u003Cimg width=\"700\" height=\"217\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_7571416e8ae3.png\" \u002F>\n\n_Caption: Example prompt for a **test‑coverage‑analyzer** agent._\n\n**tester.prompt.md (sample)**\n\n```\nRole: Write a single, focused failing test for the specific scenario I describe.\nScope: Only create\u002Fmodify tests under tests\u002F. Do not change src\u002F.\nOutput: A brief rationale + a unified diff or patch.\nIf the scenario is unclear, ask exactly one clarifying question.\n```\n\n\u003Ch3 id=\"expected-output\">Expected output\u003C\u002Fh3>\n\n> Your tester agent should produce a small diff or patch plus a short rationale:\n\n\u003Cimg width=\"700\" height=\"273\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_5c3365187106.png\" \u002F>\n\n_Caption: Example response from the **test‑coverage‑analyzer** agent._\n\n\u003Ch3 id=\"subagent-frontmatter\">Subagent Frontmatter Fields\u003C\u002Fh3>\n\nSubagent files use YAML frontmatter for configuration:\n\n```markdown\n---\nname: code-reviewer\ndescription: Reviews code for quality and best practices\ntools: Read, Glob, Grep\ndisallowedTools: Write, Edit\nmodel: sonnet\npermissionMode: default\nskills:\n  - api-conventions\n---\n\nYou are a code reviewer. Analyze the code and provide feedback.\n```\n\n| Field             | Required | Description                                                         |\n| :---------------- | :------- | :------------------------------------------------------------------ |\n| `name`            | Yes      | Unique identifier (lowercase, hyphens)                              |\n| `description`     | Yes      | When Claude should delegate to this subagent                        |\n| `tools`           | No       | Tools the subagent can use (inherits all if omitted)                |\n| `disallowedTools` | No       | Tools to deny, removed from inherited or specified list             |\n| `model`           | No       | Model: `sonnet`, `opus`, `haiku`, or `inherit` (default: sonnet)    |\n| `permissionMode`  | No       | `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |\n| `skills`          | No       | Skills to preload into the subagent's context                       |\n| `hooks`           | No       | Lifecycle hooks scoped to this subagent                             |\n| `memory`          | No       | Persistent memory scope: `user`, `project`, or `local`              |\n| `isolation`       | No       | Set to `worktree` to run the agent in an isolated git worktree      |\n| `background`      | No       | Set to `true` to run the agent as a background task                 |\n\n\u003Ch3 id=\"why-this-shift-matters\">Why This Shift Matters\u003C\u002Fh3>\n\n**Operational benefits**\n\n> - **Less context switching:** you stay in one mental mode; agents do the rest.\n> - **Cleaner PRs:** narrow prompts + limited tools → smaller, reviewable diffs.\n> - **Fewer regressions:** tester\u002Freviewer agents catch gaps before merge.\n> - **Repeatability:** prompts + policies live in the repo and travel with branches.\n\n**Security & governance**\n\n> - Limit write access by path (e.g., `src\u002F`, `tests\u002F`, `docs\u002F`).\n> - Favor read‑only analysis for high‑risk areas.\n> - Log\u002Fcommit assistant outputs as patches for auditability.\n\n\u003Ch3 id=\"a-mindset-shift\">A Mindset Shift\u003C\u002Fh3>\n\n**Do**\n\n> - Treat agents as teammates with job descriptions.\n> - Start read‑only; grant write access _last_.\n> - Keep prompts in version control and iterate via PR.\n\n**Don't**\n\n> - Ask one agent to plan, code, and test in a single turn.\n> - Give blanket write permissions.\n> - Accept multi‑file diffs when you asked for one test.\n\n---\n\n\u003Ch2 id=\"agent-teams\">Agent Teams (Research Preview)\u003C\u002Fh2>\n\n> [!Note]\n> **Agent Teams is an experimental feature enabling multiple Claude instances to work in parallel on a shared codebase autonomously.**\n\n**Enable Agent Teams:**\n\n```bash\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\n```\n\n**Key Concepts:**\n\n- Multiple Claude instances run in parallel on the same codebase\n- Each agent can specialize in different tasks (debugging, documentation, testing, etc.)\n- Agents communicate through git-based synchronization\n- Enables autonomous, long-running development workflows\n\n**Case Study: C Compiler Built by Agent Teams**\n\nAnthropic's research team demonstrated agent teams by tasking 16 parallel Claude instances to build a C compiler from scratch. Key results:\n\n| Metric              | Value                                  |\n| :------------------ | :------------------------------------- |\n| **Claude Sessions** | ~2,000                                 |\n| **API Cost**        | ~$20,000                               |\n| **Lines of Code**   | 100,000                                |\n| **Capability**      | Compiled Linux 6.9 on x86, ARM, RISC-V |\n| **Test Pass Rate**  | 99% on GCC torture test suite          |\n\n**Lessons for Agent Teams:**\n\n1. **Write high-quality tests** - The task verifier must be nearly perfect\n2. **Design for parallelism** - Agents should be able to work independently without blocking each other\n3. **Specialize agents** - Dedicate agents to specific roles (code quality, documentation, performance)\n4. **Maintain context files** - Keep READMEs and progress files updated for agent orientation\n\n> Read the full case study: [Building a C Compiler with Parallel Claudes](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fbuilding-c-compiler)\n\n---\n\n\u003Ch2 id=\"skills\">Skills (Custom Slash Commands)\u003C\u002Fh2>\n\n> [!Note]\n> **Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `\u002Fskill-name`.**\n\n\u003Ch3 id=\"skill-locations\">Skill Locations\u003C\u002Fh3>\n\n| Location                                 | Scope    | Description                                   |\n| :--------------------------------------- | :------- | :-------------------------------------------- |\n| `~\u002F.claude\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md` | Personal | All your projects                             |\n| `.claude\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md`   | Project  | This project only (commit to version control) |\n| `\u003Cplugin>\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md`  | Plugin   | Where plugin is enabled                       |\n\n> Project skills override personal skills with the same name. Files in `.claude\u002Fcommands\u002F` still work and support the same frontmatter.\n\n\u003Ch3 id=\"create-skill\">Create a Skill\u003C\u002Fh3>\n\n```bash\n# Create skill directory\nmkdir -p ~\u002F.claude\u002Fskills\u002Fexplain-code\n```\n\nCreate `~\u002F.claude\u002Fskills\u002Fexplain-code\u002FSKILL.md`:\n\n```markdown\n---\nname: explain-code\ndescription: Explains code with visual diagrams and analogies. Use when explaining how code works.\n---\n\nWhen explaining code, always include:\n\n1. **Start with an analogy**: Compare the code to something from everyday life\n2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships\n3. **Walk through the code**: Explain step-by-step what happens\n4. **Highlight a gotcha**: What's a common mistake or misconception?\n```\n\n**Use the skill:**\n\n```bash\n# Let Claude invoke automatically\nHow does this code work?\n\n# Or invoke directly\n\u002Fexplain-code src\u002Fauth\u002Flogin.ts\n```\n\n\u003Ch3 id=\"skill-frontmatter\">Skill Frontmatter Fields\u003C\u002Fh3>\n\n| Field                      | Required    | Description                                                 |\n| :------------------------- | :---------- | :---------------------------------------------------------- |\n| `name`                     | No          | Display name for the skill (uses directory name if omitted) |\n| `description`              | Recommended | What the skill does and when to use it                      |\n| `argument-hint`            | No          | Hint shown during autocomplete (e.g., `[filename]`)         |\n| `disable-model-invocation` | No          | Set `true` to prevent Claude from auto-invoking             |\n| `user-invocable`           | No          | Set `false` to hide from \u002F menu                             |\n| `allowed-tools`            | No          | Tools Claude can use without asking permission              |\n| `model`                    | No          | Model to use when this skill is active                      |\n| `context`                  | No          | Set to `fork` to run in a forked subagent context           |\n| `agent`                    | No          | Which subagent to use when `context: fork` is set           |\n| `hooks`                    | No          | Hooks scoped to this skill's lifecycle                      |\n\n\u003Ch3 id=\"skill-arguments\">Pass Arguments to Skills\u003C\u002Fh3>\n\nUse `$ARGUMENTS` placeholder to receive arguments:\n\n```markdown\n---\nname: fix-issue\ndescription: Fix a GitHub issue\ndisable-model-invocation: true\n---\n\nFix GitHub issue $ARGUMENTS following our coding standards.\n\n1. Read the issue description\n2. Implement the fix\n3. Write tests\n4. Create a commit\n```\n\n**Usage:** `\u002Ffix-issue 123`\n\n\u003Ch3 id=\"skill-dynamic-context\">Inject Dynamic Context\u003C\u002Fh3>\n\nUse `` !`command` `` syntax to run shell commands before the skill content is sent to Claude:\n\n```markdown\n---\nname: pr-summary\ndescription: Summarize changes in a pull request\ncontext: fork\nagent: Explore\n---\n\n## Pull request context\n\n- PR diff: !`gh pr diff`\n- PR comments: !`gh pr view --comments`\n- Changed files: !`gh pr diff --name-only`\n\n## Your task\n\nSummarize this pull request...\n```\n\n\u003Ch3 id=\"skill-subagent\">Run Skills in a Subagent\u003C\u002Fh3>\n\nAdd `context: fork` to run a skill in isolation:\n\n```markdown\n---\nname: deep-research\ndescription: Research a topic thoroughly\ncontext: fork\nagent: Explore\n---\n\nResearch $ARGUMENTS thoroughly:\n\n1. Find relevant files using Glob and Grep\n2. Read and analyze the code\n3. Summarize findings with specific file references\n```\n\n> The `agent` field can be `Explore`, `Plan`, `general-purpose`, or any custom subagent from `.claude\u002Fagents\u002F`.\n\n---\n\n\u003Ch2 id=\"plugin-system\">Plugin System\u003C\u002Fh2>\n\n> [!Note]\n> **Plugins extend Claude Code with custom commands, skills, agents, hooks, and MCP servers. Plugins can be loaded from local directories, Git repos, or the npm registry.**\n\n**Key commands:**\n\n```bash\n# Install a plugin from a Git repository\n\u002Fplugins install https:\u002F\u002Fgithub.com\u002Forg\u002Fclaude-plugin-example\n\n# Install from npm registry\n\u002Fplugins install @org\u002Fclaude-code-plugin\n\n# List installed plugins\n\u002Fplugins list\n\n# Enable \u002F disable a plugin\n\u002Fplugins enable \u003Cplugin-name>\n\u002Fplugins disable \u003Cplugin-name>\n\n# Validate a plugin's structure\n\u002Fplugins validate .\u002Fmy-plugin\n\n# Browse the plugin marketplace (community plugins)\n\u002Fplugins marketplace\n```\n\n**Plugin structure:**\n\n```\nmy-plugin\u002F\n├── plugin.json          # Plugin manifest (name, version, description)\n├── agents\u002F              # Custom agents (*.md frontmatter files)\n├── skills\u002F              # Custom skills (SKILL.md files)\n├── hooks\u002F               # Hook scripts\n├── commands\u002F            # Custom slash commands\n└── mcp-servers\u002F         # MCP server configurations\n```\n\n**Plugin scopes:**\n\n| Location              | Scope        | Notes                     |\n| :-------------------- | :----------- | :------------------------ |\n| `--plugin-dir .\u002Fpath` | Session only | CLI flag, not persisted   |\n| `.claude\u002Fplugins\u002F`    | Project      | Committed with the repo   |\n| `~\u002F.claude\u002Fplugins\u002F`  | User-global  | Available in all projects |\n\n**Plugin manifest (`plugin.json`):**\n\n```json\n{\n  \"name\": \"my-plugin\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A Claude Code plugin\",\n  \"agents\": [\"agents\u002F\"],\n  \"skills\": [\"skills\u002F\"],\n  \"hooks\": \"hooks\u002Fhooks.json\",\n  \"mcpServers\": \"mcp-servers\u002Fservers.json\"\n}\n```\n\n> Plugins auto-update by default. Set `FORCE_AUTOUPDATE_PLUGINS=1` to force updates even when the main updater is disabled, or override with `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` for slow repos.\n\n---\n\n\u003Ch2 id=\"worktree-isolation\">Worktree Isolation (v2.1.49+)\u003C\u002Fh2>\n\n> [!Note]\n> **The `--worktree` (`-w`) flag starts Claude in an isolated git worktree, allowing it to make changes in a separate branch without affecting your working directory.**\n\n**Usage:**\n\n```bash\n# Start Claude in an isolated worktree\nclaude -w \"implement the new feature\"\n\n# Claude will:\n# 1. Create a temporary git worktree from your current branch\n# 2. Run in that isolated worktree\n# 3. Commit changes and optionally create a PR\n# 4. Clean up the worktree when done\n```\n\n**Agent-level worktree isolation:**\n\n```markdown\n---\nname: background-coder\ndescription: Implements features in isolation\nisolation: worktree\nbackground: true\n---\n\nImplement the requested feature in this isolated worktree.\n```\n\n> Worktree isolation is especially powerful combined with `background: true` for agents, enabling parallel development workflows where multiple agents work on separate features simultaneously.\n\n---\n\n\u003Ch2 id=\"native-installer\">Native Installer (v2.1.15+)\u003C\u002Fh2>\n\n> [!Note]\n> **Claude Code now offers a native binary installer as an alternative to the npm global install. The native installer provides faster startup, auto-updates, and doesn't require Node.js on your PATH.**\n\n```bash\n# Start the native installer (interactive)\nclaude install\n\n# Migrate from npm global install to native installer\nclaude migrate-installer\n\n# Windows ARM64 is supported natively since v2.1.41\n```\n\n> The npm installation method (`npm install -g @anthropic-ai\u002Fclaude-code`) continues to work. A deprecation notice for npm-based installs was introduced in v2.1.15, but both methods are supported.\n\n---\n\n\u003Ch2 id=\"claude-auth\">Authentication CLI (v2.1.41+)\u003C\u002Fh2>\n\n> [!Note]\n> **Manage authentication directly from the CLI without entering the REPL.**\n\n```bash\n# Log in to your Anthropic account\nclaude auth login\n\n# Check current authentication status\nclaude auth status\n\n# Log out\nclaude auth logout\n```\n\n---\n\n\u003Ch2 id=\"claude-agents-cli\">Agent Management CLI (v2.1.50+)\u003C\u002Fh2>\n\n> [!Note]\n> **List and inspect all configured agents from the command line.**\n\n```bash\n# List all agents (project, user, plugin, CLI-defined)\nclaude agents\n```\n\n---\n\n\u003Ch2 id=\"remote-control\">Remote Control (v2.1.51+)\u003C\u002Fh2>\n\n> [!Note]\n> **The `claude remote-control` subcommand allows external tools and build systems to drive Claude Code programmatically.**\n\n```bash\n# Start Claude in remote-control mode\nclaude remote-control\n```\n\nThis is useful for IDE extensions, CI\u002FCD pipelines, or custom orchestration tools that want to interact with Claude Code via its SDK interface.\n\n---\n\n\u003Ch2 id=\"managed-settings\">Managed Settings (v2.1.51+)\u003C\u002Fh2>\n\n> [!Note]\n> **Enterprise administrators can push managed settings via macOS plist or Windows Registry, providing organization-wide configuration control.**\n\n**macOS (plist):**\n\nSettings can be deployed via MDM profiles to `\u002FLibrary\u002FManaged Preferences\u002Fcom.anthropic.claude-code.plist`.\n\n**Windows (Registry):**\n\nSettings can be deployed via Group Policy to `HKLM\\SOFTWARE\\Policies\\Anthropic\\ClaudeCode`.\n\n> Managed settings take precedence over user\u002Fproject settings and cannot be overridden by individual users.\n\n---\n\n\u003Ch2 id=\"model-updates\">Model Updates\u003C\u002Fh2>\n\n### Claude Sonnet 4.6 (February 17, 2026)\n\n> [!Note]\n> **Claude Sonnet 4.6 delivers frontier-level performance at Sonnet pricing ($3\u002F$15 per million tokens) with a 1M-token context window.**\n\n**Key highlights:**\n\n- **Approaches Opus-level performance** on coding, reasoning, and agent planning tasks\n- **1M token context window** (previously only available on Max plan for Sonnet 4.5)\n- **Improved coding benchmarks**: significant gains on SWE-bench, agentic coding, and multi-file refactoring\n- **Better long-context reasoning**: improved accuracy across needle-in-a-haystack and long-document tasks\n- **Enhanced computer use**: more reliable browser automation and GUI interaction\n- **Same pricing as Sonnet 4.5**: $3 input \u002F $15 output per million tokens\n\n**Use in Claude Code:**\n\n```bash\n# Set as default model\nclaude --model sonnet\n\n# Or pin the specific version\nclaude --model claude-sonnet-4-6-20260217\n\n# Configure in settings\nclaude config set model \"claude-sonnet-4-6-20260217\"\n```\n\n> Sonnet 4.5 with 1M context has been removed from the Max plan in favor of Sonnet 4.6. Claude Opus 4.6 (released in v2.1.32) remains available for the most demanding tasks.\n\n---\n\n\u003Ch2 id=\"insights\">Claude Code Insights\u003C\u002Fh2>\n\n> [!Note]\n> **The `\u002Finsights` command generates an interactive HTML report analyzing your coding habits from the past 30 days.**\n\n**Run Insights:**\n\n```bash\n# In Claude Code terminal\n\u002Finsights\n\n# Open the generated report\nstart ~\u002F.claude\u002Fusage-data\u002Freport.html     # Windows\nopen ~\u002F.claude\u002Fusage-data\u002Freport.html      # Mac\nxdg-open ~\u002F.claude\u002Fusage-data\u002Freport.html  # Linux\n```\n\n**How It Works:**\n\n1. **Session Collection** - Pulls session logs from `~\u002F.claude\u002Fprojects\u002F`, filters agent sub-sessions and short sessions\n2. **Metadata Extraction** - Extracts duration, token usage, tools used, languages detected, git activity\n3. **Facet Extraction** - Uses Haiku model to analyze transcripts and identify goals, satisfaction signals, friction points\n4. **Report Generation** - Creates interactive HTML report with personalized suggestions\n\n**Report Sections:**\n\n| Section               | Description                                                 |\n| :-------------------- | :---------------------------------------------------------- |\n| **What's Working**    | Your strengths and successful patterns                      |\n| **What's Hindering**  | Where Claude struggled or where you caused friction         |\n| **Friction Analysis** | Breakdown of problem areas with specific examples           |\n| **Stats Dashboard**   | Tool usage, language breakdown, coding time distribution    |\n| **Quick Wins**        | Copy-paste suggestions for CLAUDE.md improvements           |\n| **Features to Try**   | Personalized recommendations (skills, hooks, headless mode) |\n\n> Everything runs locally using the Anthropic API. Session data stays on your machine.\n\n---\n\n\u003Ch2 id=\"mcp-integration\">MCP Integration\u003C\u002Fh2>\n\n\u003Ch3 id=\"understanding-mcp-model-context-protocol\">Understanding MCP (Model Context Protocol)\u003C\u002Fh3>\n\n#### What is MCP?\n\n> MCP extends Claude's capabilities by connecting to external services, databases, APIs, and tools (filesystem, Puppeteer, GitHub, Context7 etc...)\n\n###### **MCP Architecture:**\n\n```\nClaude Code ←→ MCP Protocol ←→ MCP Servers ←→ External Services\n```\n\n\u003Ch3 id=\"claudeai-mcp-connectors\">claude.ai MCP Connectors\u003C\u002Fh3>\n\nClaude Code can use MCP servers configured in your claude.ai account, bringing cloud-hosted tools to your CLI workflow.\n\n```bash\n# Enabled by default — to opt out:\nexport ENABLE_CLAUDEAI_MCP_SERVERS=false\n```\n\nThis allows you to access the same MCP tool integrations available in claude.ai directly from the command line, without local MCP server configuration.\n\n\u003Ch3 id=\"mcp-setup--configuration\">MCP Setup & Configuration\u003C\u002Fh3>\n\n###### Basic MCP Commands\n\n```bash\nclaude mcp                   # Interactive MCP configuration\nclaude mcp list              # List configured servers\nclaude mcp add \u003Cname> \u003Ccmd>  # Add new server\nclaude mcp remove \u003Cname>     # Remove server\n```\n\n###### MCP Configuration File Location\n\n```bash\n~\u002F.claude.json      # Global File\n`.mcp.json`         # Project-scoped servers are stored in a File at your project's root directory\n```\n\n## Quick Start\n\n> **If you're in a hurry, here's the fastest way to add:**\n\n```bash\n# Add file system access (most commonly used)\nclaude mcp add filesystem -s user -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments ~\u002FDesktop\n\n# Verify if successful\nclaude mcp list\n```\n\n> **Responce if it worked like it should:**\n> \u003Cimg width=\"868\" height=\"192\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_76f4857af07e.png\" \u002F>\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n## Additional Methods:\n\n\u003Ctable>\u003Ctd>\n\n### 1. Command Line Addition\n\n> **Claude Code provides simple command line tools to add MCP servers:**\n\n```bash\n# Basic syntax\nclaude mcp add \u003Cname> \u003Ccommand> [parameters...]\n\n# Actual example: Add local file system access\nclaude mcp add my-filesystem -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n\n# Example with environment variables\nclaude mcp add api-server -e API_KEY=your-key-here -- \u002Fpath\u002Fto\u002Fserver\n```\n\n**OAuth for MCP Servers:**\n\n```bash\n# Add MCP server with pre-configured OAuth credentials\nclaude mcp add \u003Cname> --client-id \u003Cid> --client-secret \u003Csecret> -- \u003Ccmd>\n```\n\n> Some MCP servers (e.g., Slack) don't support Dynamic Client Registration and require pre-configured OAuth credentials.\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n### 2. Direct Configuration File Editing\n\n> Many developers find CLI wizards too cumbersome, especially when you have to restart if you make a mistake.\n>\n> Direct configuration file editing is more efficient:\n\n**1. Find configuration file location:**\n\n- macOS\u002FLinux: `~\u002F.claude.json`\n- Windows: `%USERPROFILE%\\.claude.json`\n\n**2. Edit configuration file:**\n\n```json\n{\n  \"mcpServers\": {\n    \"filesystem\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\n        \"-y\",\n        \"@modelcontextprotocol\u002Fserver-filesystem\",\n        \"\u002FUsers\u002Fusername\u002FDocuments\"\n      ],\n      \"env\": {}\n    },\n    \"github\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"your-github-token\"\n      }\n    }\n  }\n}\n```\n\n**3. Restart Claude Code to take effect**\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\u003Ctable>\u003Ctd>\n\n### 3. Project-level Configuration (Recommended for team collaboration)\n\n> If you want team members to all use the same MCP configuration:\n\n```bash\n# Add project-level MCP server\nclaude mcp add shared-tools -s project -- npx -y @your-team\u002Fmcp-tools\n```\n\n**This will create a `.mcp.json` file in the project root directory:**\n\n```json\n{\n  \"mcpServers\": {\n    \"shared-tools\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@your-team\u002Fmcp-tools\"],\n      \"env\": {}\n    }\n  }\n}\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n## MCP Server Scope Detailed\n\nUnderstanding scope is crucial to avoid \"server not found\" errors:\n\n### 1. Local Scope (Default)\n\n- Only available in current directory\n- Configuration stored in the projects section of `~\u002F.claude.json`\n- Suitable for: Personal project-specific tools\n\n### 2. User Scope (Global)\n\n- Available in all projects\n- Added using `-s user` flag\n- Suitable for: Common tools like file systems, database clients\n\n### 3. Project Scope (Team shared)\n\n- Shared through `.mcp.json` file\n- Added using `-s project` flag\n- Suitable for: Team-shared project-specific tools\n\n## Practical MCP Server Recommendations\n\n> **Here's the most worthwhile MCP server list to install:**\n\n### 1. File System Access\n\n```bash\nclaude mcp add filesystem -s user -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments ~\u002FProjects ~\u002FDesktop\n```\n\nUse: Let Claude directly read and write files, modify code\n\n### 2. GitHub Integration\n\n```bash\nclaude mcp add github -s user -e GITHUB_TOKEN=your-token -- npx -y @modelcontextprotocol\u002Fserver-github\n```\n\nUse: Manage issues, PRs, code reviews\n\n### 3. Web Browser Control\n\n```bash\nclaude mcp add puppeteer -s user -- npx -y @modelcontextprotocol\u002Fserver-puppeteer\n```\n\nUse: Automated web operations, crawling, testing\n\n### 4. Database Connection (PostgreSQL)\n\n```bash\nclaude mcp add postgres -s user -e DATABASE_URL=your-db-url -- npx -y @modelcontextprotocol\u002Fserver-postgres\n```\n\nUse: Directly query and manipulate databases\n\n### 5. Fetch Tool (API Calls)\n\n```bash\nclaude mcp add fetch -s user -- npx -y @kazuph\u002Fmcp-fetch\n```\n\nUse: Call various REST APIs\n\n### 6. Search Engine\n\n```bash\nclaude mcp add search -s user -e BRAVE_API_KEY=your-key -- npx -y @modelcontextprotocol\u002Fserver-brave-search\n```\n\nUse: Search for latest information\n\n### 7. Slack Integration\n\n```bash\nclaude mcp add slack -s user -e SLACK_TOKEN=your-token -- npx -y @modelcontextprotocol\u002Fserver-slack\n```\n\nUse: Send messages, manage channels\n\n### 8. Time Management\n\n```bash\nclaude mcp add time -s user -- npx -y @modelcontextprotocol\u002Fserver-time\n```\n\nUse: Time zone conversion, date calculation\n\n### 9. Memory Storage\n\n```bash\nclaude mcp add memory -s user -- npx -y @modelcontextprotocol\u002Fserver-memory\n```\n\nUse: Save information across conversations\n\n### 10. Sequential Thinking (Thought Chain)\n\n```bash\nclaude mcp add thinking -s user -- npx -y @modelcontextprotocol\u002Fserver-sequential-thinking\n```\n\nUse: Step-by-step thinking for complex problems\n\n## Common Errors and Solutions\n\n### Error 1: Tool Name Validation Failed\n\n```\nAPI Error 400: \"tools.11.custom.name: String should match pattern '^[a-zA-Z0-9_-]{1,64}$'\"\n```\n\n**Solution**:\n\n- Ensure server name only contains letters, numbers, underscores and hyphens\n- Name length should not exceed 64 characters\n- Don't use special characters or spaces\n\n### Error 2: MCP Server Not Found\n\n```\nMCP server 'my-server' not found\n```\n\n**Solution**:\n\n1. Check if scope settings are correct\n2. Run `claude mcp list` to confirm server has been added\n3. Ensure you're in the correct directory (for local scope)\n4. Restart Claude Code\n\n### Error 3: Protocol Version Error\n\n```\n\"protocolVersion\": \"Required\"\n```\n\n**Solution**: This is a known bug in Claude Code, temporary solutions:\n\n1. Use wrapper scripts\n2. Ensure MCP server returns correct protocol version\n3. Update to latest version of Claude Code\n\n### Error 4: Windows Path Issues\n\n```\nError: Cannot find module 'C:UsersusernameDocuments'\n```\n\n**Solution**: Windows paths need to use forward slashes or double backslashes:\n\n```bash\n# Wrong\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem C:\\Users\\username\\Documents\n\n# Correct\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem C:\u002FUsers\u002Fusername\u002FDocuments\n# or\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem C:\\\\Users\\\\username\\\\Documents\n```\n\n### Error 5: Permission Issues\n\n```\nPermission denied\n```\n\n**Solution**:\n\n1. macOS\u002FLinux: Use `sudo` (not recommended) or modify file permissions\n2. Windows: Run as administrator\n3. Best method: Install MCP servers in user directory\n\n## Debugging Techniques\n\nWhen encountering problems, these debugging methods can help you quickly locate issues:\n\n### 1. Enable Debug Mode\n\n```bash\nclaude --debug\n```\n\n### 2. View MCP Status\n\nIn Claude Code, enter:\n\n```\n\u002Fmcp\n```\n\n### 3. View Log Files\n\n**macOS\u002FLinux:**\n\n```bash\ntail -f ~\u002FLibrary\u002FLogs\u002FClaude\u002Fmcp*.log\n```\n\n**Windows:**\n\n```cmd\ntype \"%APPDATA%\\Claude\\logs\\mcp*.log\"\n```\n\n### 4. Manually Test Server\n\n```bash\n# Directly run server command to see if there's output\nnpx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n```\n\n## Special Notes for International Users\n\n### 1. Non-English Path Issues\n\nAvoid using non-English characters in paths:\n\n```bash\n# Avoid\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002F文档\n\n# Recommended\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n```\n\n### 2. Proxy Configuration\n\nIf you're using a proxy:\n\n```bash\n# Set npm proxy\nnpm config set proxy http:\u002F\u002Fyour-proxy:port\nnpm config set https-proxy http:\u002F\u002Fyour-proxy:port\n\n# Then add MCP server\nclaude mcp add ...\n```\n\n### 3. Mirror Sources\n\nUse mirror sources to accelerate downloads:\n\n```bash\n# Temporary use\nclaude mcp add fs -- npx -y --registry=https:\u002F\u002Fregistry.npmjs.org @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n\n# Or permanent setting\nnpm config set registry https:\u002F\u002Fregistry.npmjs.org\n```\n\n## Best Practice Recommendations\n\n1. **Add as needed**: Don't add too many MCP servers at once, it will affect performance\n2. **Regular cleanup**: Use `claude mcp remove \u003Cname>` to delete unused servers\n3. **Security first**: Only add trusted MCP servers, especially those requiring network access\n4. **Backup configuration**: Regularly backup `~\u002F.claude.json` file\n5. **Team collaboration**: Use project scope to share common configurations\n\n## Advanced Techniques\n\n### 1. Create Custom MCP Server\n\nIf existing MCP servers can't meet your needs, you can create your own:\n\n```javascript\n\u002F\u002F my-mcp-server.js\nimport { Server } from \"@modelcontextprotocol\u002Fsdk\";\n\nconst server = new Server({\n  name: \"my-custom-server\",\n  version: \"1.0.0\",\n});\n\nserver.setRequestHandler(\"tools\u002Flist\", async () => {\n  return {\n    tools: [\n      {\n        name: \"my_custom_tool\",\n        description: \"Custom tool\",\n        inputSchema: {\n          type: \"object\",\n          properties: {\n            input: { type: \"string\" },\n          },\n        },\n      },\n    ],\n  };\n});\n\nserver.start();\n```\n\n### 2. Batch Configuration Script\n\nCreate a script to configure all common MCP servers at once:\n\n```bash\n#!\u002Fbin\u002Fbash\n# setup-mcp.sh\n\necho \"Configuring common MCP servers...\"\n\n# File system\nclaude mcp add filesystem -s user -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments ~\u002FProjects\n\n# GitHub\nread -p \"Enter GitHub Token: \" github_token\nclaude mcp add github -s user -e GITHUB_TOKEN=$github_token -- npx -y @modelcontextprotocol\u002Fserver-github\n\n# Other servers...\n\necho \"MCP servers configured successfully!\"\n```\n\n\u003Ch3 id=\"popular-mcp-servers\">Popular MCP Servers\u003C\u002Fh3>\n\n#### Development Tools\n\n```bash\n# npm install -g git-mcp-server\n\n# claude mcp add git \"git-mcp-server\"\n# claude mcp add github \"github-mcp-server --token $GITHUB_TOKEN\"\n```\n\n#### Database Integration\n\n```bash\nnpm install -g postgres-mcp-server\nnpm install -g mysql-mcp-server\nnpm install -g sqlite-mcp-server\n\n# Setup examples may look like this:\n# export POSTGRES_URL=\"postgresql:\u002F\u002Fuser:password@localhost:5432\u002Fmydb\"\n# claude mcp add postgres \"postgres-mcp-server --url $POSTGRES_URL\"\n```\n\n#### MCP Tool Permissions\n\n```bash\n# Allow specific MCP tools\nclaude --allowedTools \"mcp__git__commit,mcp__git__push\"\n\n# Allow all tools from specific server\nclaude --allowedTools \"mcp__postgres__*\"\n\n# Combined with built-in tools\nclaude --allowedTools \"Edit,View,mcp__git__*\"\n```\n\n\u003Ch2 id=\"hooks-system\">Hooks System\u003C\u002Fh2>\n\n> This page provides reference documentation for implementing hooks in Claude Code.\n\n> [!TIP]\n> For a quickstart guide with examples, see [Get started with Claude Code hooks](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fhooks-guide).\n\n\u003Ch3 id=\"hooks-configuration\">Configuration\u003C\u002Fh3>\n\nClaude Code hooks are configured in your [settings files](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fsettings):\n\n- `~\u002F.claude\u002Fsettings.json` - User settings\n- `.claude\u002Fsettings.json` - Project settings\n- `.claude\u002Fsettings.local.json` - Local project settings (not committed)\n- Enterprise managed policy settings\n\n#### Structure\n\nHooks are organized by matchers, where each matcher can have multiple hooks:\n\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"ToolPattern\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"your-command-here\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n#### HTTP Hooks (v2.1.63+)\n\nIn addition to shell commands, hooks can POST JSON to a URL and receive a JSON response:\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"http\",\n            \"url\": \"https:\u002F\u002Fhooks.example.com\u002Fvalidate\",\n            \"timeout\": 10\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nHTTP hooks send the same JSON payload that `command` hooks receive via stdin, as a POST body. The response JSON follows the same output schema. This is useful for centralized policy enforcement or remote hook execution without local scripts.\n\n- **matcher**: Pattern to match tool names, case-sensitive (only applicable for\n  `PreToolUse` and `PostToolUse`)\n  - Simple strings match exactly: `Write` matches only the Write tool\n  - Supports regex: `Edit|Write` or `Notebook.*`\n  - Use `*` to match all tools. You can also use empty string (`\"\"`) or leave\n    `matcher` blank.\n- **hooks**: Array of commands to execute when the pattern matches\n  - `type`: `\"command\"` (shell command) or `\"http\"` (POST JSON to a URL, v2.1.63+)\n  - `command`: The bash command to execute (can use `$CLAUDE_PROJECT_DIR`\n    environment variable)\n  - `timeout`: (Optional) How long a command should run, in seconds, before\n    canceling that specific command.\n\nFor events like `UserPromptSubmit`, `Notification`, `Stop`, and `SubagentStop`\nthat don't use matchers, you can omit the matcher field:\n\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\u002Fpath\u002Fto\u002Fprompt-validator.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n#### Project-Specific Hook Scripts\n\nYou can use the environment variable `CLAUDE_PROJECT_DIR` (only available when\nClaude Code spawns the hook command) to reference scripts stored in your project,\nensuring they work regardless of Claude's current directory:\n\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Write|Edit\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Fcheck-style.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n\u003Ch3 id=\"hook-events\">Hook Events\u003C\u002Fh3>\n\n#### PreToolUse\n\nRuns after Claude creates tool parameters and before processing the tool call.\n\n**Common matchers:**\n\n- `Task` - Subagent tasks (see [subagents documentation](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fsub-agents))\n- `Bash` - Shell commands\n- `Glob` - File pattern matching\n- `Grep` - Content search\n- `Read` - File reading\n- `Edit`, `MultiEdit` - File editing\n- `Write` - File writing\n- `WebFetch`, `WebSearch` - Web operations\n\n#### PostToolUse\n\nRuns immediately after a tool completes successfully.\n\nRecognizes the same matcher values as PreToolUse.\n\n#### Notification\n\nRuns when Claude Code sends notifications. Notifications are sent when:\n\n1. Claude needs your permission to use a tool. Example: \"Claude needs your\n   permission to use Bash\"\n2. The prompt input has been idle for at least 60 seconds. \"Claude is waiting\n   for your input\"\n\n#### UserPromptSubmit\n\nRuns when the user submits a prompt, before Claude processes it. This allows you\nto add additional context based on the prompt\u002Fconversation, validate prompts, or\nblock certain types of prompts.\n\n#### Stop\n\nRuns when the main Claude Code agent has finished responding. Does not run if\nthe stoppage occurred due to a user interrupt.\n\n#### SubagentStop\n\nRuns when a Claude Code subagent (Task tool call) has finished responding.\n\n#### TeammateIdle\n\nTriggered when an agent teammate becomes idle (multi-agent workflows).\n\n#### TaskCompleted\n\nTriggered when a background task completes (multi-agent workflows).\n\n#### ConfigChange\n\nFires when Claude Code configuration files change (e.g., settings, CLAUDE.md, `.mcp.json`). Useful for reloading external state or triggering side effects on config edits.\n\n#### WorktreeCreate\n\nFires when Claude creates a new git worktree (via `--worktree` \u002F `-w` flag or `isolation: worktree` in agent definitions). Useful for setting up worktree-specific resources.\n\n#### WorktreeRemove\n\nFires when a git worktree is cleaned up after use. Useful for tearing down worktree-specific resources.\n\n#### Setup\n\nTriggered via `--init`, `--init-only`, or `--maintenance` CLI flags. Useful for one-time project setup tasks, plugin installation, or maintenance scripts.\n\n#### PermissionRequest\n\nFires when Claude shows a permission prompt to the user. Useful for logging or automating permission decisions.\n\n#### PreCompact\n\nRuns before Claude Code is about to run a compact operation.\n\n**Matchers:**\n\n- `manual` - Invoked from `\u002Fcompact`\n- `auto` - Invoked from auto-compact (due to full context window)\n\n#### SessionStart\n\nRuns when Claude Code starts a new session or resumes an existing session (which\ncurrently does start a new session under the hood). Useful for loading in\ndevelopment context like existing issues or recent changes to your codebase.\n\n**Matchers:**\n\n- `startup` - Invoked from startup\n- `resume` - Invoked from `--resume`, `--continue`, or `\u002Fresume`\n- `clear` - Invoked from `\u002Fclear`\n\n\u003Ch3 id=\"hook-input\">Hook Input\u003C\u002Fh3>\n\nHooks receive JSON data via stdin containing session information and\nevent-specific data:\n\n```typescript\n{\n  \u002F\u002F Common fields\n  session_id: string\n  transcript_path: string  \u002F\u002F Path to conversation JSON\n  cwd: string              \u002F\u002F The current working directory when the hook is invoked\n\n  \u002F\u002F Event-specific fields\n  hook_event_name: string\n  ...\n}\n```\n\n#### PreToolUse Input\n\nThe exact schema for `tool_input` depends on the tool.\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"PreToolUse\",\n  \"tool_name\": \"Write\",\n  \"tool_input\": {\n    \"file_path\": \"\u002Fpath\u002Fto\u002Ffile.txt\",\n    \"content\": \"file content\"\n  }\n}\n```\n\n#### PostToolUse Input\n\nThe exact schema for `tool_input` and `tool_response` depends on the tool.\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"PostToolUse\",\n  \"tool_name\": \"Write\",\n  \"tool_input\": {\n    \"file_path\": \"\u002Fpath\u002Fto\u002Ffile.txt\",\n    \"content\": \"file content\"\n  },\n  \"tool_response\": {\n    \"filePath\": \"\u002Fpath\u002Fto\u002Ffile.txt\",\n    \"success\": true\n  }\n}\n```\n\n#### Notification Input\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"Notification\",\n  \"message\": \"Task completed successfully\"\n}\n```\n\n#### UserPromptSubmit Input\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"UserPromptSubmit\",\n  \"prompt\": \"Write a function to calculate the factorial of a number\"\n}\n```\n\n#### Stop and SubagentStop Input\n\n`stop_hook_active` is true when Claude Code is already continuing as a result of\na stop hook. Check this value or process the transcript to prevent Claude Code\nfrom running indefinitely.\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"~\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"hook_event_name\": \"Stop\",\n  \"stop_hook_active\": true,\n  \"last_assistant_message\": \"I've completed all the requested changes.\"\n}\n```\n\n> The `last_assistant_message` field (v2.1.47+) contains the final text Claude produced before stopping. Useful for validating completeness or logging outcomes.\n\n#### PreCompact Input\n\nFor `manual`, `custom_instructions` comes from what the user passes into\n`\u002Fcompact`. For `auto`, `custom_instructions` is empty.\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"~\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"hook_event_name\": \"PreCompact\",\n  \"trigger\": \"manual\",\n  \"custom_instructions\": \"\"\n}\n```\n\n#### SessionStart Input\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"~\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"hook_event_name\": \"SessionStart\",\n  \"source\": \"startup\"\n}\n```\n\n\u003Ch3 id=\"hook-output\">Hook Output\u003C\u002Fh3>\n\nThere are two ways for hooks to return output back to Claude Code. The output\ncommunicates whether to block and any feedback that should be shown to Claude\nand the user.\n\n#### Simple: Exit Code\n\nHooks communicate status through exit codes, stdout, and stderr:\n\n- **Exit code 0**: Success. `stdout` is shown to the user in transcript mode\n  (CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is\n  added to the context.\n- **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process\n  automatically. See per-hook-event behavior below.\n- **Other exit codes**: Non-blocking error. `stderr` is shown to the user and\n  execution continues.\n\n> [!WARNING]\n> Reminder: Claude Code does not see stdout if the exit code is 0, except for\n> the `UserPromptSubmit` hook where stdout is injected as context.\n\n##### Exit Code 2 Behavior\n\n| Hook Event         | Behavior                                                           |\n| ------------------ | ------------------------------------------------------------------ |\n| `PreToolUse`       | Blocks the tool call, shows stderr to Claude                       |\n| `PostToolUse`      | Shows stderr to Claude (tool already ran)                          |\n| `Notification`     | N\u002FA, shows stderr to user only                                     |\n| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |\n| `Stop`             | Blocks stoppage, shows stderr to Claude                            |\n| `SubagentStop`     | Blocks stoppage, shows stderr to Claude subagent                   |\n| `PreCompact`       | N\u002FA, shows stderr to user only                                     |\n| `SessionStart`     | N\u002FA, shows stderr to user only                                     |\n\n#### Advanced: JSON Output\n\nHooks can return structured JSON in `stdout` for more sophisticated control:\n\n##### Common JSON Fields\n\nAll hook types can include these optional fields:\n\n```json\n{\n  \"continue\": true, \u002F\u002F Whether Claude should continue after hook execution (default: true)\n  \"stopReason\": \"string\" \u002F\u002F Message shown when continue is false\n  \"suppressOutput\": true, \u002F\u002F Hide stdout from transcript mode (default: false)\n}\n```\n\nIf `continue` is false, Claude stops processing after the hooks run.\n\n- For `PreToolUse`, this is different from `\"permissionDecision\": \"deny\"`, which\n  only blocks a specific tool call and provides automatic feedback to Claude.\n- For `PostToolUse`, this is different from `\"decision\": \"block\"`, which\n  provides automated feedback to Claude.\n- For `UserPromptSubmit`, this prevents the prompt from being processed.\n- For `Stop` and `SubagentStop`, this takes precedence over any\n  `\"decision\": \"block\"` output.\n- In all cases, `\"continue\" = false` takes precedence over any\n  `\"decision\": \"block\"` output.\n\n`stopReason` accompanies `continue` with a reason shown to the user, not shown\nto Claude.\n\n##### `PreToolUse` Decision Control\n\n`PreToolUse` hooks can control whether a tool call proceeds.\n\n- `\"allow\"` bypasses the permission system. `permissionDecisionReason` is shown\n  to the user but not to Claude. (_Deprecated `\"approve\"` value + `reason` has\n  the same behavior._)\n- `\"deny\"` prevents the tool call from executing. `permissionDecisionReason` is\n  shown to Claude. (_`\"block\"` value + `reason` has the same behavior._)\n- `\"ask\"` asks the user to confirm the tool call in the UI.\n  `permissionDecisionReason` is shown to the user but not to Claude.\n\n```json\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"PreToolUse\",\n    \"permissionDecision\": \"allow\" | \"deny\" | \"ask\",\n    \"permissionDecisionReason\": \"My reason here (shown to user)\"\n  },\n  \"decision\": \"approve\" | \"block\" | undefined, \u002F\u002F Deprecated for PreToolUse but still supported\n  \"reason\": \"Explanation for decision\" \u002F\u002F Deprecated for PreToolUse but still supported\n}\n```\n\n##### `PostToolUse` Decision Control\n\n`PostToolUse` hooks can control whether a tool call proceeds.\n\n- `\"block\"` automatically prompts Claude with `reason`.\n- `undefined` does nothing. `reason` is ignored.\n\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"Explanation for decision\"\n}\n```\n\n##### `UserPromptSubmit` Decision Control\n\n`UserPromptSubmit` hooks can control whether a user prompt is processed.\n\n- `\"block\"` prevents the prompt from being processed. The submitted prompt is\n  erased from context. `\"reason\"` is shown to the user but not added to context.\n- `undefined` allows the prompt to proceed normally. `\"reason\"` is ignored.\n- `\"hookSpecificOutput.additionalContext\"` adds the string to the context if not\n  blocked.\n\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"Explanation for decision\",\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"UserPromptSubmit\",\n    \"additionalContext\": \"My additional context here\"\n  }\n}\n```\n\n##### `Stop`\u002F`SubagentStop` Decision Control\n\n`Stop` and `SubagentStop` hooks can control whether Claude must continue.\n\n- `\"block\"` prevents Claude from stopping. You must populate `reason` for Claude\n  to know how to proceed.\n- `undefined` allows Claude to stop. `reason` is ignored.\n\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"Must be provided when Claude is blocked from stopping\"\n}\n```\n\n##### `SessionStart` Decision Control\n\n`SessionStart` hooks allow you to load in context at the start of a session.\n\n- `\"hookSpecificOutput.additionalContext\"` adds the string to the context.\n\n```json\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"SessionStart\",\n    \"additionalContext\": \"My additional context here\"\n  }\n}\n```\n\n##### Exit Code Example: Bash Command Validation\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\nimport json\nimport re\nimport sys\n\n# Define validation rules as a list of (regex pattern, message) tuples\nVALIDATION_RULES = [\n    (\n        r\"\\bgrep\\b(?!.*\\|)\",\n        \"Use 'rg' (ripgrep) instead of 'grep' for better performance and features\",\n    ),\n    (\n        r\"\\bfind\\s+\\S+\\s+-name\\b\",\n        \"Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance\",\n    ),\n]\n\n\ndef validate_command(command: str) -> list[str]:\n    issues = []\n    for pattern, message in VALIDATION_RULES:\n        if re.search(pattern, command):\n            issues.append(message)\n    return issues\n\n\ntry:\n    input_data = json.load(sys.stdin)\nexcept json.JSONDecodeError as e:\n    print(f\"Error: Invalid JSON input: {e}\", file=sys.stderr)\n    sys.exit(1)\n\ntool_name = input_data.get(\"tool_name\", \"\")\ntool_input = input_data.get(\"tool_input\", {})\ncommand = tool_input.get(\"command\", \"\")\n\nif tool_name != \"Bash\" or not command:\n    sys.exit(1)\n\n# Validate the command\nissues = validate_command(command)\n\nif issues:\n    for message in issues:\n        print(f\"• {message}\", file=sys.stderr)\n    # Exit code 2 blocks tool call and shows stderr to Claude\n    sys.exit(2)\n```\n\n##### JSON Output Example: UserPromptSubmit to Add Context and Validation\n\n> [!NOTE]\n> For `UserPromptSubmit` hooks, you can inject context using either method:\n>\n> - Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`)\n> - JSON output: Provides more control over the behavior\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\nimport json\nimport sys\nimport re\nimport datetime\n\n# Load input from stdin\ntry:\n    input_data = json.load(sys.stdin)\nexcept json.JSONDecodeError as e:\n    print(f\"Error: Invalid JSON input: {e}\", file=sys.stderr)\n    sys.exit(1)\n\nprompt = input_data.get(\"prompt\", \"\")\n\n# Check for sensitive patterns\nsensitive_patterns = [\n    (r\"(?i)\\b(password|secret|key|token)\\s*[:=]\", \"Prompt contains potential secrets\"),\n]\n\nfor pattern, message in sensitive_patterns:\n    if re.search(pattern, prompt):\n        # Use JSON output to block with a specific reason\n        output = {\n            \"decision\": \"block\",\n            \"reason\": f\"Security policy violation: {message}. Please rephrase your request without sensitive information.\"\n        }\n        print(json.dumps(output))\n        sys.exit(0)\n\n# Add current time to context\ncontext = f\"Current time: {datetime.datetime.now()}\"\nprint(context)\n\n\"\"\"\nThe following is also equivalent:\nprint(json.dumps({\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"UserPromptSubmit\",\n    \"additionalContext\": context,\n  },\n}))\n\"\"\"\n\n# Allow the prompt to proceed with the additional context\nsys.exit(0)\n```\n\n##### JSON Output Example: PreToolUse with Approval\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\nimport json\nimport sys\n\n# Load input from stdin\ntry:\n    input_data = json.load(sys.stdin)\nexcept json.JSONDecodeError as e:\n    print(f\"Error: Invalid JSON input: {e}\", file=sys.stderr)\n    sys.exit(1)\n\ntool_name = input_data.get(\"tool_name\", \"\")\ntool_input = input_data.get(\"tool_input\", {})\n\n# Example: Auto-approve file reads for documentation files\nif tool_name == \"Read\":\n    file_path = tool_input.get(\"file_path\", \"\")\n    if file_path.endswith((\".md\", \".mdx\", \".txt\", \".json\")):\n        # Use JSON output to auto-approve the tool call\n        output = {\n            \"decision\": \"approve\",\n            \"reason\": \"Documentation file auto-approved\",\n            \"suppressOutput\": True  # Don't show in transcript mode\n        }\n        print(json.dumps(output))\n        sys.exit(0)\n\n# For other cases, let the normal permission flow proceed\nsys.exit(0)\n```\n\n\u003Ch3 id=\"working-with-mcp-tools\">Working with MCP Tools\u003C\u002Fh3>\n\nClaude Code hooks work seamlessly with\n[Model Context Protocol (MCP) tools](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fmcp). When MCP servers\nprovide tools, they appear with a special naming pattern that you can match in\nyour hooks.\n\n#### MCP Tool Naming\n\nMCP tools follow the pattern `mcp__\u003Cserver>__\u003Ctool>`, for example:\n\n- `mcp__memory__create_entities` - Memory server's create entities tool\n- `mcp__filesystem__read_file` - Filesystem server's read file tool\n- `mcp__github__search_repositories` - GitHub server's search tool\n\n#### Configuring Hooks for MCP Tools\n\nYou can target specific MCP tools or entire MCP servers:\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"mcp__memory__.*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo 'Memory operation initiated' >> ~\u002Fmcp-operations.log\"\n          }\n        ]\n      },\n      {\n        \"matcher\": \"mcp__.*__write.*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\u002Fhome\u002Fuser\u002Fscripts\u002Fvalidate-mcp-write.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n\u003Ch3 id=\"hooks-examples\">Examples\u003C\u002Fh3>\n\n> [!TIP]\n> For practical examples including code formatting, notifications, and file protection, see [More Examples](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fhooks-guide#more-examples) in the get started guide.\n\n\u003Ch3 id=\"security-considerations\">Security Considerations\u003C\u002Fh3>\n\n#### Disclaimer\n\n**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on\nyour system automatically. By using hooks, you acknowledge that:\n\n- You are solely responsible for the commands you configure\n- Hooks can modify, delete, or access any files your user account can access\n- Malicious or poorly written hooks can cause data loss or system damage\n- Anthropic provides no warranty and assumes no liability for any damages\n  resulting from hook usage\n- You should thoroughly test hooks in a safe environment before production use\n\nAlways review and understand any hook commands before adding them to your\nconfiguration.\n\n\u003Ch3 id=\"hooks-security\">Hooks Security Considerations\u003C\u002Fh3>\n\nHere are some key practices for writing more secure hooks:\n\n1. **Validate and sanitize inputs** - Never trust input data blindly\n2. **Always quote shell variables** - Use `\"$VAR\"` not `$VAR`\n3. **Block path traversal** - Check for `..` in file paths\n4. **Use absolute paths** - Specify full paths for scripts (use\n   `$CLAUDE_PROJECT_DIR` for the project path)\n5. **Skip sensitive files** - Avoid `.env`, `.git\u002F`, keys, etc.\n\n#### Configuration Safety\n\nDirect edits to hooks in settings files don't take effect immediately. Claude\nCode:\n\n1. Captures a snapshot of hooks at startup\n2. Uses this snapshot throughout the session\n3. Warns if hooks are modified externally\n4. Requires review in `\u002Fhooks` menu for changes to apply\n\nThis prevents malicious hook modifications from affecting your current session.\n\n\u003Ch3 id=\"hook-execution-details\">Hook Execution Details\u003C\u002Fh3>\n\n- **Timeout**: 60-second execution limit by default, configurable per command.\n  - A timeout for an individual command does not affect the other commands.\n- **Parallelization**: All matching hooks run in parallel\n- **Environment**: Runs in current directory with Claude Code's environment\n  - The `CLAUDE_PROJECT_DIR` environment variable is available and contains the\n    absolute path to the project root directory\n- **Input**: JSON via stdin\n- **Output**:\n  - PreToolUse\u002FPostToolUse\u002FStop: Progress shown in transcript (Ctrl-R)\n  - Notification: Logged to debug only (`--debug`)\n\n\u003Ch3 id=\"hooks-debugging\">Debugging\u003C\u002Fh3>\n\n#### Basic Troubleshooting\n\nIf your hooks aren't working:\n\n1. **Check configuration** - Run `\u002Fhooks` to see if your hook is registered\n2. **Verify syntax** - Ensure your JSON settings are valid\n3. **Test commands** - Run hook commands manually first\n4. **Check permissions** - Make sure scripts are executable\n5. **Review logs** - Use `claude --debug` to see hook execution details\n\nCommon issues:\n\n- **Quotes not escaped** - Use `\\\"` inside JSON strings\n- **Wrong matcher** - Check tool names match exactly (case-sensitive)\n- **Command not found** - Use full paths for scripts\n\n#### Advanced Debugging\n\nFor complex hook issues:\n\n1. **Inspect hook execution** - Use `claude --debug` to see detailed hook\n   execution\n2. **Validate JSON schemas** - Test hook input\u002Foutput with external tools\n3. **Check environment variables** - Verify Claude Code's environment is correct\n4. **Test edge cases** - Try hooks with unusual file paths or inputs\n5. **Monitor system resources** - Check for resource exhaustion during hook\n   execution\n6. **Use structured logging** - Implement logging in your hook scripts\n\n#### Debug Output Example\n\nUse `claude --debug` to see hook execution details:\n\n```\n[DEBUG] Executing hooks for PostToolUse:Write\n[DEBUG] Getting matching hook commands for PostToolUse with query: Write\n[DEBUG] Found 1 hook matchers in settings\n[DEBUG] Matched 1 hooks for query \"Write\"\n[DEBUG] Found 1 hook commands to execute\n[DEBUG] Executing hook command: \u003CYour command> with timeout 60000ms\n[DEBUG] Hook command completed with status 0: \u003CYour stdout>\n```\n\nProgress messages appear in transcript mode (Ctrl-R) showing:\n\n- Which hook is running\n- Command being executed\n- Success\u002Ffailure status\n- Output or error messages\n\n---\n\n\u003Ch1 id=\"security--permissions\">Security & Permissions\u003C\u002Fh1>\n\n#### Tool Permission Patterns\n\n```bash\n# Allow specific tools (read\u002Fedit files)\nclaude --allowedTools \"Edit,Read\"\n\n# Allow tool categories incl. Bash (but still scoped below)\nclaude --allowedTools \"Edit,Read,Bash\"\n\n# Scoped permissions (all git commands)\nclaude --allowedTools \"Bash(git:*)\"\n\n# Multiple scopes (git + npm)\nclaude --allowedTools \"Bash(git:*),Bash(npm:*)\"\n```\n\n\u003Ch2 id=\"dangerous-mode\">Dangerous Mode\u003C\u002Fh2>\n\n> [!Warning]\n> NEVER use in Production systems, shared machines, or any systems with important data\n> Only use with isolated environments like a **Docker container**, using this mode can cause data loss and comprimise your system!\n>\n> `claude --dangerously-skip-permissions`\n\n\u003Ch1 id=\"automation--integration\">Automation & Integration\u003C\u002Fh1>\n\n\u003Ch2 id=\"automation--scripting-with-claude-code\">Automation & Scripting with Claude Code\u003C\u002Fh2>\n\n> GitHub Actions you can copy\u002Fpaste :p\n\n1. **Install the Claude GitHub App** on your org\u002Frepo (required for Actions to comment on PRs\u002Fissues).\n2. In your repo, add a secret **`ANTHROPIC_API_KEY`** Settings → Secrets and variables → Actions → New repository secret\n3. Copy the workflows below into **`.github\u002Fworkflows\u002F`**.\n4. Open a **test PR** (or a new issue) to see them run.\n\n> [!TIP]\n> Pin Actions to a release tag (e.g. `@v1`) when you adopt them long‑term. The snippets below use branch tags for readability.\n\n\u003Ch2 id=\"auto-pr-review-inline-comments\">Auto PR Review (inline comments)\u003C\u002Fh2>\n\n> **Creates a structured review (with inline comments) as soon as a PR opens or updates.**\n\n**File:** `.github\u002Fworkflows\u002Fclaude-pr-auto-review.yml`\n\n```yaml\nname: Auto review PRs\non:\n  pull_request:\n    types: [opened, synchronize, reopened, ready_for_review]\n\npermissions:\n  contents: read\n  pull-requests: write\n\njobs:\n  auto-review:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with:\n          fetch-depth: 1\n\n      - name: Claude PR review\n        uses: anthropics\u002Fclaude-code-action@main\n        with:\n          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}\n          # Claude will fetch the diff and leave inline comments\n          direct_prompt: |\n            Review this pull request’s diff for correctness, readability, testing, performance, and DX.\n            Prefer specific, actionable suggestions. Use inline comments where relevant.\n          # GitHub tools permitted during the run:\n          allowed_tools: >-\n            mcp__github__get_pull_request_diff,\n            mcp__github__create_pending_pull_request_review,\n            mcp__github__add_comment_to_pending_review,\n            mcp__github__submit_pending_pull_request_review\n```\n\n\u003Ch2 id=\"security-review-on-every-pr\">Security Review on Every PR\u003C\u002Fh2>\n\n> **Runs a focused security scan and comments findings directly on the PR.**\n\n**File:** `.github\u002Fworkflows\u002Fclaude-security-review.yml`\n\n```yaml\nname: Security Review\non:\n  pull_request:\n\npermissions:\n  contents: read\n  pull-requests: write\n\njobs:\n  security:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with:\n          ref: ${{ github.event.pull_request.head.sha || github.sha }}\n          fetch-depth: 2\n\n      - name: Claude Code Security Review\n        uses: anthropics\u002Fclaude-code-security-review@main\n        with:\n          claude-api-key: ${{ secrets.ANTHROPIC_API_KEY }}\n          comment-pr: true\n          # Optional:\n          # exclude-directories: \"docs,examples\"\n          # claudecode-timeout: \"20\"\n          # claude-model: \"claude-sonnet-4-6-20260217\"\n```\n\n\u003Ch2 id=\"issue-triage-suggest-labels--severity\">Issue Triage (suggest labels & severity)\u003C\u002Fh2>\n\n> **When a new issue opens, Claude proposes labels\u002Fseverity and posts a tidy triage comment. You can enable **auto‑apply labels** by flipping a single flag**\n\n**File:** `.github\u002Fworkflows\u002Fclaude-issue-triage.yml`\n\n```yaml\nname: Claude Issue Triage\non:\n  issues:\n    types: [opened, edited, reopened]\n\npermissions:\n  contents: read\n  issues: write\n\njobs:\n  triage:\n    runs-on: ubuntu-latest\n    env:\n      CLAUDE_MODEL: claude-sonnet-4-6-20260217\n    steps:\n      - name: Collect context & similar issues\n        id: gather\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        run: |\n          TITLE=\"${{ github.event.issue.title }}\"\n          BODY=\"${{ github.event.issue.body }}\"\n          # naive similar search by title words\n          Q=$(echo \"$TITLE\" | tr -dc '[:alnum:] ' | awk '{print $1\" \"$2\" \"$3\" \"$4}')\n          gh api -X GET search\u002Fissues -f q=\"repo:${{ github.repository }} is:issue $Q\" -f per_page=5 > similars.json\n          echo \"$TITLE\" > title.txt\n          echo \"$BODY\" > body.txt\n\n      - name: Ask Claude for triage JSON\n        env:\n          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}\n        run: |\n          cat > payload.json \u003C\u003C 'JSON'\n          {\n            \"model\": \"${{ env.CLAUDE_MODEL }}\",\n            \"max_tokens\": 1500,\n            \"system\": \"You are a pragmatic triage engineer. Be specific, cautious with duplicates.\",\n            \"messages\": [{\n              \"role\": \"user\",\n              \"content\": [{\n                \"type\":\"text\",\n                \"text\":\"Given the issue and similar candidates, produce STRICT JSON with keys: labels (array of strings), severity (one of: low, medium, high, critical), duplicate_url (string or empty), comment_markdown (string brief). Do not include any extra keys.\"\n              },\n              {\"type\":\"text\",\"text\":\"Issue title:\\n\"},\n              {\"type\":\"text\",\"text\": (include from file) },\n              {\"type\":\"text\",\"text\":\"\\n\\nIssue body:\\n\"},\n              {\"type\":\"text\",\"text\": (include from file) },\n              {\"type\":\"text\",\"text\":\"\\n\\nSimilar issues (JSON):\\n\"},\n              {\"type\":\"text\",\"text\": (include from file) }]\n            }]\n          }\n          JSON\n          # Inject files safely\n          jq --arg title \"$(cat title.txt)\" '.messages[0].content[2].text = $title' payload.json \\\n          | jq --arg body \"$(cat body.txt)\" '.messages[0].content[4].text = $body' \\\n          | jq --arg sims \"$(cat similars.json)\" '.messages[0].content[6].text = $sims' > payload.final.json\n\n          curl -s https:\u002F\u002Fapi.anthropic.com\u002Fv1\u002Fmessages \\\n            -H \"x-api-key: $ANTHROPIC_API_KEY\" \\\n            -H \"anthropic-version: 2023-06-01\" \\\n            -H \"content-type: application\u002Fjson\" \\\n            -d @payload.final.json > out.json\n          jq -r '.content[0].text' out.json > triage.json || echo '{}' > triage.json\n          # Validate JSON to avoid posting garbage\n          jq -e . triage.json >\u002Fdev\u002Fnull 2>&1 || echo '{\"labels\":[],\"severity\":\"low\",\"duplicate_url\":\"\",\"comment_markdown\":\"(triage failed to parse)\"}' > triage.json\n\n      - name: Apply labels (optional)\n        if: ${{ false }} # flip to `true` to auto-apply labels\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const triage = JSON.parse(require('fs').readFileSync('triage.json','utf8'))\n            if (triage.labels?.length) {\n              await github.rest.issues.addLabels({\n                owner: context.repo.owner,\n                repo: context.repo.repo,\n                issue_number: context.issue.number,\n                labels: triage.labels\n              })\n            }\n\n      - name: Post triage comment\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const fs = require('fs')\n            const triage = JSON.parse(fs.readFileSync('triage.json','utf8'))\n            const md = `### 🤖 Triage\n            - **Suggested labels:** ${triage.labels?.join(', ') || '—'}\n            - **Severity:** ${triage.severity || '—'}\n            ${triage.duplicate_url ? `- **Possible duplicate:** ${triage.duplicate_url}\\n` : ''}\n            ---\n            ${triage.comment_markdown || ''}`\n            await github.rest.issues.createComment({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              issue_number: context.issue.number,\n              body: md\n            })\n```\n\n> [!NOTE]\n> The triage workflow posts a **suggestion comment** by default. Flip the `Apply labels` step to `true` if you want labels applied automatically.\n>\n> ### Configuration & Customization\n>\n> - **Model selection**: set `CLAUDE_MODEL` (e.g., `claude-sonnet-4-6-20260217`) where shown.\n> - **Secrets**: `ANTHROPIC_API_KEY` is required. The built‑in `GITHUB_TOKEN` is sufficient for posting comments and applying labels.\n> - **Permissions**: each workflow declares the least privileges it needs (`pull-requests: write` and\u002For `issues: write`). Adjust only if your org requires stricter policies.\n> - **Scope**: use `paths:` filters on triggers to limit when workflows run (e.g., only for `\u002Fsrc` or exclude `\u002Fdocs`).\n>\n> ### Troubleshooting\n>\n> Check the **Actions logs** first—most issues are missing secrets\u002Fpermissions or a mis‑indented YAML block.\n>\n> - **No comments appear on PRs**: Verify the Claude GitHub App is installed and the workflow has `pull-requests: write` permission.\n> - **403 when applying labels**: Ensure the job or step has `issues: write`. The default `GITHUB_TOKEN` must have access to this repo.\n> - **Anthropic API errors**: Confirm `ANTHROPIC_API_KEY` is set at repository (or org) level and not expired.\n> - **“YAML not well‑formed”**: Validate spacing—two spaces per nesting level; no tabs.\n\n---\n\n\u003Ch1 id=\"help--troubleshooting\">Help & Troubleshooting\u003C\u002Fh1>\n\n> [!TIP]\n> **Q:`claude` not found, but `npx claude` works?**\n>\n> > **A: Your `PATH` is missing the npm global bin. See the `PATH` issue section for [`Windows`](#windowspath) or [`Linux`](#linuxpath)**\n>\n> **Q:** **Which Node.js version do I need?**\n>\n> > **A:** **Node.js **18+** (ideally **20+**). Check with `node --version`.**\n>\n> **Q: Where do I see logs**\n>\n> > **A: Run `claude doctor` and `claude --verbose` the diagnostic window will point to log locations.**\n>\n> **Q: Do I need to reboot after editing PATH?**\n>\n> > **A: No reboot required, but you \u003Cmark>must\u003C\u002Fmark> open a \u003Cmark>new\u003C\u002Fmark> terminal window.**\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"debug-quick-commands\">Debug Quick Commands\u003C\u002Fh2>\n\n_Check the output of `claude doctor` for log locations and environment checks._\n\n> [!Note]\n>\n> ```bash\n> claude                  # Open Claude UI (if on PATH)\n> claude --version        # Show CLI version (e.g., 1.0.xx)\n> claude update           # Update the CLI (if supported)\n>\n> claude doctor           # Open diagnostic \u002F debug window\n> npx claude \u002Fdoctor      # Opens diagnostic\u002Fdebug window\n>\n> claude --debug          # Launch claude with diagnostics\n> claude --verbose        # Verbose logging\n>\n> where claude            # Windows (cmd)\n> which claude            # macOS\u002FLinux (bash\u002Fzsh)\n>\n> npm bin -g              # Linux Verify your global bin path\n> npm prefix -g           # Windows Verify your global bin path\n> ```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"linuxpath\">Path Temp Fix\u003C\u002Fh2>\n\n**Your **PATH** likely doesn’t include the global npm bin directory.**\n\n> [!Note]\n>\n> #### Windows (CMD):\n>\n> ```bash\n> set PATH=%USERPROFILE%\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;%PATH%\n> where claude\n> claude --debug\n> ```\n>\n> #### Windows (PowerShell):\n>\n> ```powershell\n> $env:Path = \"$env:USERPROFILE\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;$env:Path\"\n> where claude\n> claude --debug\n> ```\n>\n> #### Linux\u002FMacOS (bash\u002Fzsh)\n>\n> ```bash\n> export PATH=\"$(npm config get prefix)\u002Fbin:$HOME\u002F.local\u002Fbin:$PATH\"\n> which claude\n> claude doctor\n> ```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"windowspath\">Windows Path Perm Fix\u003C\u002Fh2>\n\n**Replace `\u003Cyou>` with your own Windows username (without the angle brackets)**\n\n- **Start → type: \u003Ckbd>Environment Variables\u003C\u002Fkbd>**\n- **Open \u003Ckbd>Edit the system environment variables\u003C\u002Fkbd> → \u003Ckbd>Environment Variables\u003C\u002Fkbd>**\n- **Under \u003Ckbd>User variables for\u003C\u002Fkbd> \u003Cmark>\u003Cyou>\u003C\u002Fmark> select `Path` → `Edit` → `New` add:**\n\n```path\nC:\\Users\\\u003Cyou>\\AppData\\Roaming\\npm\nC:\\Program Files\\nodejs\u003C\u002Fkbd>\n```\n\n> **Optional locations to add:**\n\n```path\nC:\\Users\\\u003Cyou>\\.claude\\local\\bin\nC:\\Users\\\u003Cyou>\\.local\\bin\n```\n\n- **Remove duplicates, any entry containing `%PATH%`, and stray quotes (`\"`). Click `OK`.**\n- **Open a `new` Command Prompt\u002FPowerShell and verify:**\n\n```C\nwhere claude\nclaude doctor\n```\n\n> [!Tip]\n>\n> ### Optional Run directly (when PATH is broken)\n>\n> > **Windows (PowerShell\u002Fcmd)**\n>\n> ```powershell\n> \"%USERPROFILE%\\AppData\\Roaming\\npm\\claude.cmd\" --version\n> \"%USERPROFILE%\\AppData\\Roaming\\npm\\claude.cmd\" doctor\n> ```\n>\n> > **Or via npx:**\n>\n> ```\n> npx claude doctor\n> ```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"installation--nodejs-issues\">Installation \u002F Node.js Issues\u003C\u002Fh3>\n\n**Must be Node 18+ (20+ recommended)**\n\n```bash\nnode --version\n```\n\n**Clean uninstall**\n\n```bash\nnpm uninstall -g @anthropic-ai\u002Fclaude-code\n```\n\n**Fresh install**\n\n```bash\nnpm install  -g @anthropic-ai\u002Fclaude-code\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"authentication-issues\">Authentication Issues\u003C\u002Fh3>\n> *Verify your Anthropic API key is available to the CLI.*\n\n**PowerShell (Windows):**\n\n```powershell\necho $env:ANTHROPIC_API_KEY\nclaude -p \"test\" --verbose\n```\n\n**bash\u002Fzsh (macOS\u002FLinux):**\n\n```bash\necho $ANTHROPIC_API_KEY\nclaude -p \"test\" --verbose\n```\n\n_If the variable is empty set it for your shell\u002Fprofile or use your OS keychain\u002Fsecrets manager._\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"permission--allowed-tools-issues\">Permission \u002F Allowed Tools Issues\u003C\u002Fh3>\n\n**Inspect permissions**\n\n```bash\nclaude config get allowedTools\n```\n\n**Reset permissions**\n\n```bash\nclaude config set allowedTools \"[]\"\n```\n\n**Minimal safe set (example)**\n\n```bash\nclaude config set allowedTools '[\"Edit\",\"View\"]'\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"mcp-model-context-protocol-issues\">MCP (Model Context Protocol) Issues\u003C\u002Fh3>\n\n> **Debug MCP servers**\n\n```bash\nclaude --debug\n```\n\n> **List & remove MCP servers**\n\n```bash\nclaude mcp list\nclaude mcp remove \u003Cserver-name>\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"full-clean-reinstall-windows--powershell\">Full Clean Reinstall (Windows \u002F PowerShell)\u003C\u002Fh2>\n\n> [!Caution]\n> **The following removes Claude Code binaries, caches, and config under your user profile**\n\n> 1. Uninstall the global npm package\n\n```powershell\nnpm uninstall -g @anthropic-ai\u002Fclaude-code\n```\n\n> 2. Remove leftover shim files\n\n```powershell\nRemove-Item -LiteralPath \"$env:USERPROFILE\\AppData\\Roaming\\npm\\claude*\" -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\AppData\\Roaming\\npm\\node_modules\\@anthropic-ai\\claude-code\" -Recurse -Force -ErrorAction SilentlyContinue\n```\n\n> 3. Delete cached installer & native files\n\n```powershell\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\\downloads\\*\" -Recurse -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\\local\\bin\\claude.exe\" -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\\local\" -Recurse -Force -ErrorAction SilentlyContinue\n```\n\n> 4. Remove config and project-local files\n\n```powershell\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude.json\" -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\" -Recurse -Force -ErrorAction SilentlyContinue\n```\n\n> 5. Reinstall\n\n```powershell\nnpm install -g @anthropic-ai\u002Fclaude-code\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"one-shot-health-check-copypaste\">One‑Shot Health Check (copy\u002Fpaste)\u003C\u002Fh2>\n\n**Windows (PowerShell):**\n\n```powershell\nWrite-Host \"`n=== Node & npm ===\"; node --version; npm --version\nWrite-Host \"`n=== Where is claude? ===\"; where claude\nWrite-Host \"`n=== Try doctor ===\"; try { claude doctor } catch { Write-Host \"claude not on PATH\" }\nWrite-Host \"`n=== API key set? ===\"; if ($env:ANTHROPIC_API_KEY) { \"Yes\" } else { \"No\" }\n```\n\n**macOS\u002FLinux (bash\u002Fzsh):**\n\n```bash\necho \"=== Node & npm ===\"; node --version; npm --version\necho \"=== Where is claude? ===\"; which claude || echo \"claude not on PATH\"\necho \"=== Try doctor ===\"; claude doctor || true\necho \"=== API key set? ===\"; [ -n \"$ANTHROPIC_API_KEY\" ] && echo Yes || echo No\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n---\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"appendix-useful-paths\">Appendix: Useful Paths\u003C\u002Fh2>\n\n- **Windows npm global bin:** `C:\\Users\\\u003Cyou>\\AppData\\Roaming\\npm`\n- **Windows Node.js:** `C:\\Program Files\\nodejs`\n- **Claude local data (Win):** `C:\\Users\\\u003Cyou>\\.claude\\`\n- **Claude config (Win):** `C:\\Users\\\u003Cyou>\\.claude.json`\n- **macOS\u002FLinux npm global bin:** `$(npm config get prefix)\u002Fbin` (often `\u002Fusr\u002Flocal\u002Fbin` or `$HOME\u002F.npm-global\u002Fbin`)\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ch2 id=\"best-practices\">Best Practices\u003C\u002Fh2>\n\n> Curated guidance for safe, fast, and correct use of the Claude Code CLI and interactive REPL. All commands and flags here match the current Anthropic docs as of **Feb 28, 2026**.\n\n\u003Ch2 id=\"effective-prompting\">Effective Prompting\u003C\u002Fh2>\n\n```bash\n# Good: Specific and detailed\nclaude \"Review UserAuth.js for security vulnerabilities, focusing on JWT handling\"\n\n# Bad: Vague\nclaude \"check my code\"\n```\n\nTip: `claude \"query\"` starts the interactive REPL pre-seeded with your prompt; `claude -p \"query\"` runs **print mode** (non‑interactive) and exits.\n\n---\n\n\u003Ch2 id=\"security-best-practices-main\">Security Best Practices\u003C\u002Fh2>\n\n1. **Start with minimal permissions**\n   - Prefer explicit allows and denies, either on the CLI or in settings files.\n\n   ```bash\n   # Allow only what you need for this run\n   claude --allowedTools \"Read\" \"Grep\" \"LS\" \"Bash(npm run test:*)\"\n   ```\n\n   Or commit a project policy at `.claude\u002Fsettings.json`:\n\n   ```json\n   {\n     \"permissions\": {\n       \"allow\": [\"Read\", \"Grep\", \"LS\", \"Bash(npm run test:*)\"],\n       \"deny\": [\n         \"WebFetch\",\n         \"Bash(curl:*)\",\n         \"Read(.\u002F.env)\",\n         \"Read(.\u002Fsecrets\u002F**)\"\n       ]\n     }\n   }\n   ```\n\n2. **Handle secrets correctly**\n   - Use environment variables for SDK\u002Fautomation flows:\n\n   ```bash\n   export ANTHROPIC_API_KEY=\"your_key\"   # for SDK\u002Fprint mode\n   ```\n\n   - In the interactive REPL, prefer `\u002Flogin` instead of hard‑coding tokens.\n   - Deny access to sensitive files in settings (replaces older `ignorePatterns`):\n\n   ```json\n   {\n     \"permissions\": {\n       \"deny\": [\"Read(.\u002F.env)\", \"Read(.\u002F.env.*)\", \"Read(.\u002Fsecrets\u002F**)\"]\n     }\n   }\n   ```\n\n3. **Audit permissions regularly**\n\n   ```bash\n   # Project settings\n   claude config list\n   claude config get permissions.allow\n   claude config get permissions.deny\n\n   # Global settings\n   claude config list -g\n   ```\n\n4. **Avoid bypass modes in production**\n   - Do **not** use `--dangerously-skip-permissions` outside isolated\u002Fdev sandboxes.\n   - For unattended runs, combine narrow `--allowedTools` with `--disallowedTools` and project settings.\n\n---\n\n\u003Ch2 id=\"performance-tips\">Performance Tips\u003C\u002Fh2>\n\n1. **Use machine‑readable output in automations**\n\n   ```bash\n   claude -p \"summarize this error log\" --output-format json\n   # valid: text | json | stream-json\n   ```\n\n2. **Bound non‑interactive work**\n\n   ```bash\n   claude -p \"run type checks and summarize failures\" --max-turns 3\n   # optionally also bound thinking:\n   export MAX_THINKING_TOKENS=20000\n   ```\n\n3. **Keep sessions tidy**\n\n   ```bash\n   # Retain recent sessions only (default is 30 days)\n   claude config set -g cleanupPeriodDays 20\n   ```\n\n4. **Limit context scope**\n\n   ```bash\n   # Grant access only to relevant paths to reduce scanning\u002Fnoise\n   claude --add-dir .\u002Fservices\u002Fapi .\u002Fpackages\u002Fui\n   ```\n\n5. **Pick the right model**\n   - CLI aliases: `--model sonnet` or `--model opus` (latest of that family).\n   - As of Feb 2026, **Sonnet 4.6** is the default Sonnet — frontier performance at Sonnet pricing with a 1M-token context window.\n   - For reproducibility in settings, pin a full model ID (e.g., `\"claude-sonnet-4-6-20260217\"`).\n\n---\n\n\u003Ch2 id=\"monitoring--alerting\">Monitoring & Alerting\u003C\u002Fh2>\n\n**1) Health checks**\nUse the built‑in **doctor** command to verify installation and environment.\n\n```bash\n# Every 15 minutes\n*\u002F15 * * * * \u002Fusr\u002Flocal\u002Fbin\u002Fclaude doctor >\u002Fdev\u002Fnull 2>&1 || \\\nmail -s \"Claude Code doctor failed\" admin@company.com \u003C\u002Fdev\u002Fnull\n```\n\n**2) Log analysis batch job**\n\n```bash\n# Daily analysis with non-interactive JSON output (print mode)\n0 6 * * * tail -1000 \u002Fvar\u002Flog\u002Fapp.log | \\\nclaude -p \"Analyze errors, regressions, and suspect patterns; output JSON.\" \\\n--output-format json > \u002Ftmp\u002Fdaily-analysis.json\n```\n\n**3) Telemetry (optional)**\nClaude Code emits OpenTelemetry metrics\u002Fevents. Set exporters in settings\u002Fenv (e.g., OTLP) and ship to your observability stack (Datadog, Honeycomb, Prometheus\u002FGrafana, etc.).\n\n---\n\n\u003Ch2 id=\"collaboration-best-practices\">Collaboration Best Practices\u003C\u002Fh2>\n\n\u003Ch3 id=\"team-workflows\">Team Workflows\u003C\u002Fh3>\n\n**1) Share versioned configuration**\n\n```jsonc\n\u002F\u002F .claude\u002Fsettings.json (checked into the repo)\n{\n  \"permissions\": {\n    \"allow\": [\n      \"Read\",\n      \"Grep\",\n      \"LS\",\n      \"Bash(npm run lint)\",\n      \"Bash(npm run test:*)\",\n    ],\n    \"deny\": [\n      \"WebFetch\",\n      \"Read(.\u002F.env)\",\n      \"Read(.\u002F.env.*)\",\n      \"Read(.\u002Fsecrets\u002F**)\",\n    ],\n  },\n  \u002F\u002F Pin a model here for reproducibility if desired, using a full model ID:\n  \"model\": \"claude-sonnet-4-6-20260217\",\n}\n```\n\n**2) Documentation automation**\n\n```bash\n# Update docs with explicit tasks\nclaude \"Update README.md to reflect the latest API endpoints and examples.\"\nclaude \"Generate TypeScript types from schema.prisma and write to \u002Ftypes.\"\n```\n\n**3) Code review standards**\n\n```bash\n# Review a local diff with constrained tools\ngit fetch origin main\ngit diff origin\u002Fmain...HEAD > \u002Ftmp\u002Fdiff.patch\nclaude --allowedTools \"Read\" \"Grep\" \"Bash(git:*)\" \\\n  \"Review \u002Ftmp\u002Fdiff.patch using team standards:\n   - Security best practices\n   - Performance considerations\n   - Code style compliance\n   - Test coverage adequacy\"\n```\n\n\u003Ch3 id=\"knowledge-sharing\">Knowledge Sharing\u003C\u002Fh3>\n\n**1) Project runbooks**\n\n```bash\nclaude \"Create a deployment runbook for this app: steps, checks, rollback.\"\nclaude \"Document onboarding for new developers: setup, commands, conventions.\"\n```\n\n**2) Architecture docs**\n\n```bash\nclaude \"Update architecture docs to reflect new microservices.\"\nclaude \"Create sequence diagrams for the authentication flow.\"\n```\n\n> Tip: Keep durable context in **CLAUDE.md** at the project root. In the REPL, use `\u002Fmemory` to manage it and `@path` to import file content into prompts.\n\n---\n\n\u003Ch2 id=\"common-pitfalls-to-avoid\">Common Pitfalls to Avoid\u003C\u002Fh2>\n\n\u003Ch3 id=\"security-pitfalls\">Security\u003C\u002Fh3>\n\n**❌ Don’t**\n\n- Use `--dangerously-skip-permissions` on production systems\n- Hard‑code secrets in commands\u002Fconfig\n- Grant overly broad permissions (e.g., `Bash(*)`)\n- Run with elevated privileges unnecessarily\n\n**✅ Do**\n\n- Store secrets in env vars and credential helpers\n- Start from minimal `permissions.allow` and expand gradually\n- Audit with `claude config list` \u002F `claude config get`\n- Isolate risky operations in containers\u002FVMs\n\n\u003Ch3 id=\"performance-pitfalls\">Performance\u003C\u002Fh3>\n\n**❌ Don’t**\n\n- Load an entire monorepo when you only need a package\n- Max out thinking\u002Fturn budgets for simple tasks\n- Ignore session cleanup\n\n**✅ Do**\n\n- Use `--add-dir` for focused context\n- Right‑size with `--max-turns` and `MAX_THINKING_TOKENS`\n- Set `cleanupPeriodDays` to prune old sessions\n\n\u003Ch3 id=\"workflow-pitfalls\">Workflow\u003C\u002Fh3>\n\n**❌ Don’t**\n\n- Skip project context (`CLAUDE.md`)\n- Use vague prompts\n- Ignore errors\u002Flogs\n- Automate without testing\n\n**✅ Do**\n\n- Maintain and update `CLAUDE.md`\n- Be specific and goal‑oriented in prompts\n- Monitor via logs\u002FOTel as appropriate\n- Test automation in safe environments first\n\n---\n\n\u003Ch1 id=\"third-party-integrations\">Third-Party Integrations\u003C\u002Fh1>\n\n\u003Ch2 id=\"deepseek-integration\">DeepSeek Integration\u003C\u002Fh2>\n\n1. ###### Have claude Code installed\n\n```\nnpm install -g @anthropic-ai\u002Fclaude-code\n```\n\n2. ###### Config Environment Variables\n\n```bash\nexport ANTHROPIC_BASE_URL=https:\u002F\u002Fapi.deepseek.com\u002Fanthropic\nexport ANTHROPIC_AUTH_TOKEN=${YOUR_API_KEY}\nexport ANTHROPIC_MODEL=deepseek-chat\nexport ANTHROPIC_SMALL_FAST_MODEL=deepseek-chat\n```\n\n3. ###### Now all you need to do is launch `claude`\n\nFind more information from the [Official Deepseek Docs](https:\u002F\u002Fapi-docs.deepseek.com\u002Fguides\u002Fanthropic_api)\n","\u003Cdiv align=\"center\">\n\n\u003Ch2 id=\"claude-code-community-guide\">Claude 代码社区指南\u003C\u002Fh2>\n\n_如需更新和贡献，请访问 [官方 Claude 代码文档](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview)_\n\n![Claude Code](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002F@anthropic-ai\u002Fclaude-code?label=Claude%20Code&logo=anthropic)\n[![状态](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FStatus-Active-brightgreen)](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code)\n[![许可证](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-Anthropic-orange)](https:\u002F\u002Fclaude.ai\u002Fcode)\n\n\u003C\u002Fdiv>\n\n\u003Cdiv align=\"center\">\n\n\u003Ckbd>\n\n| 版块                                           | 状态 | 其他资源 |\n| ------------------------------------------------- | ------ |------ |\n| 入门                       |✅|\u003Ckbd> **Claude-Code** [**变更日志**](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fclaude-code-guide\u002Fblob\u002Fmain\u002FCHANGELOG.md)\u003C\u002Fkbd> |\n| 配置与环境变量 |✅|\u003Ckbd>**Claude-Code 通过** [**Discord**](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fclaude-code-discord)\u003C\u002Fkbd> |\n| 命令与使用                      |✅|\u003Ckbd>安全代理 [SKILL.md](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fclaude-code-guide\u002Ftree\u002Fmain\u002Fskills)\u003C\u002Fkbd> |\n| 界面与输入                     |✅|\u003Ckbd>让代理创建 [SKILL.md](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fagent-skills-authoring)\u003C\u002Fkbd> |\n| 高级功能                     |✅|\u003Ckbd>954+ 代理 [技能](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fantigravity-awesome-skills)\u003C\u002Fkbd> |\n| 自动化与集成              |✅|\u003Ckbd>免费 AI [资源](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fno-cost-ai)\u003C\u002Fkbd>  |\n| 帮助与故障排除                |✅|\u003Ckbd>250+ Mermaid [模板](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fmermaid-templates)\u003C\u002Fkbd>  |\n| 第三方集成              |✅|\u003Ckbd>Discord 通信 [MCP](https:\u002F\u002Fgithub.com\u002Fzebbern\u002Fdiscord-mcp-agent)\u003C\u002Fkbd> |\n\n\n\u003C\u002Fkbd>\n\n\u003C\u002Fdiv>\n\n---\n\n\u003Ch3 id=\"content\">内容\u003C\u002Fh3>\n\n_快速链接:_ [安装](#quick-start) · [命令](#claude-commands) · [快捷键](#keyboard-shortcuts) · [MCP](#mcp-integration) · [故障排除](#help--troubleshooting)\n\n- **[入门](#getting-started)**\n  - [快速入门](#quick-start)\n  - [初始设置](#initial-setup)\n\n- **[配置与环境](#configuration--environment)**\n  - [环境变量](#environment-variables)\n  - [配置文件](#configuration-files)\n\n- **[命令与使用](#commands--usage)**\n  - [斜杠命令参考](#claude-commands)\n  - [CLI 快速参考](#cheat-sheet)\n\n- **[界面与输入](#interface--input)**\n  - [键盘快捷键](#keyboard-shortcuts)\n  - [Vim 模式](#vim-mode)\n\n- **[高级功能](#advanced-features)**\n  - [思考模式](#thinking-keywords)\n  - [计划模式](#plan-mode)\n  - [快速模式](#fast-mode)\n  - [后台任务](#background-tasks)\n  - [Chrome 中的 Claude](#claude-in-chrome)\n  - [沙盒模式](#sandbox-mode)\n  - [LSP 工具](#lsp-tool)\n  - [远程会话](#remote-sessions)\n  - [子代理](#sub-agents)\n  - [代理团队](#agent-teams)\n  - [技能](#skills)\n  - [插件系统](#plugin-system)\n  - [工作树隔离](#worktree-isolation)\n  - [MCP 集成](#mcp-integration)\n  - [钩子系统](#hooks-system)\n  - [原生安装程序](#native-installer)\n  - [认证 CLI](#claude-auth)\n  - [代理管理 CLI](#claude-agents-cli)\n  - [远程控制](#remote-control)\n  - [托管设置](#managed-settings)\n  - [模型更新](#model-updates)\n  - [洞察](#insights)\n\n- **[安全与权限](#security--permissions)**\n  - [危险模式](#dangerous-mode)\n  - [安全最佳实践](#security-best-practices-main)\n\n- **[自动化与集成](#automation--integration)**\n  - [自动化与脚本](#automation--scripting-with-claude-code)\n  - [自动 PR 审核](#auto-pr-review-inline-comments)\n  - [问题分类](#issue-triage-suggest-labels--severity)\n\n- **[帮助与故障排除](#help--troubleshooting)**\n  - [安装问题](#installation--nodejs-issues)\n  - [MCP 问题](#mcp-model-context-protocol-issues)\n  - [最佳实践](#best-practices)\n\n- **[第三方集成](#third-party-integrations)**\n  - [DeepSeek 集成](#deepseek-integration)\n\n---\n\n\u003Ch1 id=\"getting-started\">开始使用\u003C\u002Fh1>\n\n**启用 Claude 完成任务时的声音提醒：**\n\n> \u003Ckbd>claude config set --global preferredNotifChannel terminal_bell\u003C\u002Fkbd>\n\n\u003Ch2 id=\"quick-start\">快速入门\u003C\u002Fh2>\n\n> [!TIP]\n> **在终端中输入 \u003Cmark>claude\u003C\u002Fmark> 或 \u003Cmark>npx claude\u003C\u002Fmark> 即可启动界面**\n>\n> **前往 [帮助与故障排除](#help--troubleshooting) 解决问题...**\n\n```C\n# 原生安装程序（推荐 — 无需 Node.js）⭐️\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Windows\n\u002F* 通过 CMD（原生）      *\u002F curl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.cmd -o install.cmd && install.cmd && del install.cmd\n\u002F* 通过 Powershell        *\u002F irm https:\u002F\u002Fclaude.ai\u002Finstall.ps1 | iex\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# macOS \u002F Linux \u002F WSL\n\u002F* 通过终端          *\u002F curl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Arch\n\u002F* 通过终端          *\u002F yay -S claude-code*\u002F\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n# 替代方案（npm）— 已被原生安装程序取代\n# 需要 Node.js 18+\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Windows\n\u002F* 通过 CMD（npm）         *\u002F npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# macOS\n\u002F* 通过终端          *\u002F brew install node && npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Linux\n\u002F* 通过终端          *\u002F sudo apt update && sudo apt install -y nodejs npm\n\u002F* 通过终端          *\u002F npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n# WSL\u002FGIT\n\u002F* 通过终端          *\u002F npm install -g @anthropic-ai\u002Fclaude-code\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# Docker\n\u002F* Windows (CMD)         *\u002F docker run -it --rm -v \"%cd%:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim bash -lc \"npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude\"\n\u002F* macOS\u002FLinux (bash\u002Fzsh)*\u002F docker run -it --rm -v \"$PWD:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim bash -lc 'npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude'\n\u002F* 无 bash 备用      *\u002F docker run -it --rm -v \"$PWD:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim sh -lc 'npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude'\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# 检查 claude 是否安装正确\n\u002F* Linux                 *\u002F which claude\n\u002F* Windows               *\u002F where claude\n\u002F* 通用                  *\u002F claude --version\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n# 常见管理\n\u002F*claude config          *\u002F 配置设置\n\u002F*claude mcp list        *\u002F 设置 MCP 服务器，你也可以将 \"list\" 替换为 add\u002Fremove\n\u002F*claude \u002Fagents         *\u002F 为不同任务配置\u002F设置子代理\n\u002F*claude update          *\u002F 更新到最新版本\n```\n\n---\n\n> [!Tip]\n> \u003Cins>**通过终端打开项目到 VS Code \u002F Cursor**\u003C\u002Fins>\n>\n> ### $ - \u003Ckbd>cd \u002Fpath\u002Fto\u002Fproject\u003C\u002Fkbd>\n>\n> ### $ - \u003Ckbd>code .\u003C\u002Fkbd>\n>\n> **请确保在你的 VS Code \u002F Cursor 中已安装 \u003Cmark>(Claude Code 扩展)\u003C\u002Fmark>**\n\n---\n\n\u003Ch2 id=\"system-requirements\">系统要求\u003C\u002Fh2>\n\n> - 操作系统：macOS 10.15+、Ubuntu 20.04+\u002FDebian 10+，或 Windows 10\u002F11 或 WSL\n\n> - 硬件：最低 4GB 内存，建议 8GB+\n\n> - 软件：Node.js 18+ 或 git 2.23+（可选）以及 GitHub 或 GitLab CLI 用于 PR 流程（可选）\n> - _Node.js 仅在使用 npm 安装时需要。原生安装程序自带运行时环境。_\n\n> - 网络：用于 API 调用的连接\n\n> - Node.js 18+ _(仅在使用 npm 安装时需要；原生安装程序自带运行时环境)_\n\n---\n\n\u003Ch2 id=\"initial-setup\">初始设置\u003C\u002Fh2>\n\n> [!Tip]\n> **从 [Anthropic 控制台](https:\u002F\u002Fconsole.anthropic.com) 获取 API 密钥**\n>\n> **切勿提交真实密钥，请使用 git 忽略文件、操作系统密钥存储或秘密管理工具**\n\n```C\n# 通用\n\u002F* 开始登录流程                    *\u002F claude \u002Flogin\n\u002F* 设置长期有效认证令牌  *\u002F claude setup-token\n\u002F* 通过 Anthropic 账户认证     *\u002F claude auth login\n----------------------------------------------------------------------------------------------------------------------------------\n# Windows\n\u002F* 设置 API 密钥        *\u002F set ANTHROPIC_API_KEY=sk-your-key-here-here\n\u002F* CMD 掩码检查   *\u002F echo OK: %ANTHROPIC_API_KEY:~0,8%***\n\u002F* 设置持久密钥 *\u002F setx ANTHROPIC_API_KEY \"sk-your-key-here-here\"\n\u002F* CMD 取消设置密钥      *\u002F set ANTHROPIC_API_KEY=\n----------------------------------------------------------------------------------------------------------------------------------\n# Linux\n\u002F* 设置 API 密钥        *\u002F export ANTHROPIC_API_KEY=\"sk-your-key-here-here\"\n\u002F* 掩码检查       *\u002F echo \"OK: ${ANTHROPIC_API_KEY:0:8}***\"\n\u002F* 移除会话     *\u002F unset ANTHROPIC_API_KEY\n----------------------------------------------------------------------------------------------------------------------------------\n# Powershell\n\u002F* PS 会话         *\u002F $env:ANTHROPIC_API_KEY = \"sk-your-key-here-here\"\n\u002F* PS 掩码检查    *\u002F \"OK: $($env:ANTHROPIC_API_KEY.Substring(0,8))***\"\n\u002F* PS 持久化         *\u002F [Environment]::SetEnvironmentVariable(\"ANTHROPIC_API_KEY\",\"sk-your-key-here-here\",\"User\")\n\u002F* PS 更换密钥      *\u002F $env:ANTHROPIC_API_KEY = \"sk-new-key\"\n\u002F* PS 删除密钥      *\u002F Remove-Item Env:\\ANTHROPIC_API_KEY\n----------------------------------------------------------------------------------------------------------------------------------\n# 其他...\n# persist-bash\u002F*      *\u002F echo 'export ANTHROPIC_API_KEY=\"sk-your-key-here-here\"' >> ~\u002F.bashrc && source ~\u002F.bashrc\n# persist-zsh \u002F*      *\u002F echo 'export ANTHROPIC_API_KEY=\"sk-your-key-here-here\"' >> ~\u002F.zshrc  && source ~\u002F.zshrc\n# persist-fish\u002F*      *\u002F fish -lc 'set -Ux ANTHROPIC_API_KEY sk-your-key-here-here'\n----------------------------------------------------------------------------------------------------------------------------------\n```\n\n---\n\n\u003Ch1 id=\"configuration--environment\">配置与环境\u003C\u002Fh1>\n\n\u003Ch2 id=\"environment-variables\">环境变量\u003C\u002Fh2>\n\n> **你也可以在 settings.json 的 \"env\" 键下设置这些变量，以实现自动应用。**\n\n> [!重要]\n> **Windows 用户请将 \u003Ckbd>export\u003C\u002Fkbd> 替换为 \u003Ckbd>set\u003C\u002Fkbd> 或 \u003Ckbd>setx\u003C\u002Fkbd> 以实现永久设置**\n\n```bash\n\n# 环境变量开关（放入 ~\u002F.bashrc 或 ~\u002F.zshrc）\nexport ANTHROPIC_API_KEY=\"sk-your-key-here-here\"      # 作为 X-Api-Key 头发送的 API 密钥（交互式使用：\u002Flogin）\nexport ANTHROPIC_AUTH_TOKEN=\"my-auth-token\"           # 自定义 Authorization 头；Claude 会自动添加 \"Bearer \" 前缀\nexport ANTHROPIC_CUSTOM_HEADERS=\"X-Trace-Id: 12345\"   # 额外的请求头（格式：名称: 值）\n\nexport ANTHROPIC_MODEL=\"claude-sonnet-4-6-20260217\"                # 自定义要使用的模型名称\nexport ANTHROPIC_DEFAULT_SONNET_MODEL=\"claude-sonnet-4-6-20260217\" # 默认 Sonnet 模型别名\nexport ANTHROPIC_DEFAULT_OPUS_MODEL=\"claude-opus-4-6-20260130\"   # 默认 Opus 模型别名（Opus 4.6 现已可用）\nexport ANTHROPIC_SMALL_FAST_MODEL=\"haiku-model\"                  # 用于后台任务的 Haiku 级模型（占位符）\nexport ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=\"REGION\"            # 覆盖 Bedrock 上小型快速模型的 AWS 区域（占位符）\n\nexport AWS_BEARER_TOKEN_BEDROCK=\"bedrock_...\"         # 用于身份验证的 Amazon Bedrock API 密钥\u002F令牌\n\nexport BASH_DEFAULT_TIMEOUT_MS=60000                  # 长时间运行 Bash 命令的默认超时时间（毫秒）\nexport BASH_MAX_TIMEOUT_MS=300000                     # 允许的长时间运行 Bash 命令的最大超时时间（毫秒）\nexport BASH_MAX_OUTPUT_LENGTH=20000                   # 在中间截断之前，Bash 输出的最大字符数\n\nexport CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1     # （0 或 1）每次执行完 Bash 命令后返回原始项目目录\nexport CLAUDE_BASH_NO_LOGIN=1                         # 设置为 1 时，BashTool 不使用登录 Shell。默认行为已在 v2.1.51 中更改（仅在回退时使用登录 Shell）。\nexport CLAUDE_CODE_API_KEY_HELPER_TTL_MS=600000       # 使用 apiKeyHelper 时刷新凭据的时间间隔（毫秒）\nexport CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL=1            # （0 或 1）跳过 IDE 扩展的自动安装\nexport CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096             # 大多数请求的最大输出标记数\n\nexport CLAUDE_CODE_USE_BEDROCK=1                      # （0 或 1）使用 Amazon Bedrock\nexport CLAUDE_CODE_USE_VERTEX=0                       # （0 或 1）使用 Google Vertex AI\nexport CLAUDE_CODE_SKIP_BEDROCK_AUTH=0                # （0 或 1）跳过 Bedrock 的 AWS 身份验证（例如通过 LLM 网关）\nexport CLAUDE_CODE_SKIP_VERTEX_AUTH=0                 # （0 或 1）跳过 Vertex 的 Google 身份验证（例如通过 LLM 网关）\n\nexport CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=0     # （0 或 1）禁用非必要流量（等同于下方的 DISABLE_*）\nexport CLAUDE_CODE_DISABLE_TERMINAL_TITLE=0           # （0 或 1）禁用终端标题的自动更新\n\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1         # （0 或 1）启用代理团队研究预览\nexport CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 # （0 或 1）从 --add-dir 路径加载 CLAUDE.md\nexport CLAUDE_CODE_ENABLE_TASKS=false                 # 设置为“false”以禁用新的任务系统\n\nexport DISABLE_AUTOUPDATER=0                          # （0 或 1）禁用自动更新（覆盖 autoUpdates 设置）\nexport DISABLE_BUG_COMMAND=0                          # （0 或 1）禁用 \u002Fbug 命令\nexport DISABLE_COST_WARNINGS=0                        # （0 或 1）禁用成本警告消息\nexport DISABLE_ERROR_REPORTING=0                      # （0 或 1）退出 Sentry 错误报告\nexport DISABLE_NON_ESSENTIAL_MODEL_CALLS=0            # （0 或 1）禁用非关键路径的模型调用\nexport DISABLE_TELEMETRY=0                            # （0 或 1）退出 Statsig 遥测\n\nexport HTTP_PROXY=\"http:\u002F\u002Fproxy:8080\"                 # HTTP 代理服务器 URL\nexport HTTPS_PROXY=\"https:\u002F\u002Fproxy:8443\"               # HTTPS 代理服务器 URL\n\nexport MAX_THINKING_TOKENS=0                          # （0 或 1，用于关闭或开启）强制为模型设置思考预算\nexport MCP_TIMEOUT=120000                             # MCP 服务器启动超时时间（毫秒）\nexport MCP_TOOL_TIMEOUT=60000                         # MCP 工具执行超时时间（毫秒）\nexport MAX_MCP_OUTPUT_TOKENS=25000                    # MCP 工具响应中允许的最大标记数（默认 25000）\n\nexport USE_BUILTIN_RIPGREP=0                          # （0 或 1）设置为 0 以使用系统安装的 rg，而非捆绑版本\n\nexport VERTEX_REGION_CLAUDE_3_5_HAIKU=\"REGION\"        # Vertex AI 上 Claude 3.5 Haiku 的区域覆盖（旧版模型家族名称）\nexport VERTEX_REGION_CLAUDE_3_5_SONNET=\"REGION\"       # Vertex AI 上 Claude 3.5 Sonnet 的区域覆盖（旧版模型家族名称）\nexport VERTEX_REGION_CLAUDE_3_7_SONNET=\"REGION\"       # Vertex AI 上 Claude 3.7 Sonnet 的区域覆盖（旧版模型家族名称）\n# 注意：CLAUDE_3_5_* 和 CLAUDE_3_7_* 使用旧版模型家族名称，未来版本可能会更新。\nexport VERTEX_REGION_CLAUDE_4_0_OPUS=\"REGION\"         # Vertex AI 上 Claude 4.0 Opus 的区域覆盖\nexport VERTEX_REGION_CLAUDE_4_0_SONNET=\"REGION\"       # Vertex AI 上 Claude 4.0 Sonnet 的区域覆盖\nexport VERTEX_REGION_CLAUDE_4_1_OPUS=\"REGION\"         # Vertex AI 上 Claude 4.1 Opus 的区域覆盖\nexport VERTEX_REGION_CLAUDE_4_6_OPUS=\"REGION\"         # Vertex AI 上 Claude 4.6 Opus 的区域覆盖\nexport VERTEX_REGION_CLAUDE_4_6_SONNET=\"REGION\"       # Vertex AI 上 Claude 4.6 Sonnet 的区域覆盖\n\n# ── v2.1.32–2.1.63 版本新增功能 ──────────────────────────────────────────────────────\nexport CLAUDE_CODE_SIMPLE=1                            # 极简模式：禁用 MCP 工具、附件、钩子、CLAUDE.md 和技能\nexport CLAUDE_CODE_DISABLE_1M_CONTEXT=1                # 禁用 100 万 token 上下文窗口（使用默认较短上下文）\nexport CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1          # 完全禁用后台任务\nexport CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1        # 退出实验性测试功能\nexport CLAUDE_CODE_AUTO_CONNECT_IDE=false              # 禁用启动时自动连接 IDE\nexport CLAUDE_CODE_TMPDIR=\"\u002Fcustom\u002Ftmp\"                # 覆盖 Claude Code 使用的临时目录\nexport CLAUDE_CODE_SHELL=\"\u002Fbin\u002Fzsh\"                    # 覆盖 shell 检测（强制指定特定 shell）\nexport CLAUDE_CODE_SHELL_PREFIX=\"command-wrapper\"      # 为 Claude 运行的每个 shell 命令添加前缀\u002F包装\nexport CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS=50000   # 覆盖 Read 工具的最大输出 token 数\nexport CLAUDE_CODE_PROXY_RESOLVES_HOSTS=true           # 让 HTTP\u002FHTTPS 代理处理 DNS 解析\nexport CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=30000         # 在空闲 N 毫秒后自动退出 SDK 模式\nexport CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS=30000         # 插件 git 操作的超时时间（毫秒）\nexport CLAUDE_CODE_ACCOUNT_UUID=\"uuid\"                 # 覆盖账户 UUID（SDK \u002F 自动化流程）\nexport CLAUDE_CODE_USER_EMAIL=\"user@example.com\"       # 覆盖用户邮箱（SDK \u002F 自动化流程）\nexport CLAUDE_CODE_ORGANIZATION_UUID=\"uuid\"            # 覆盖组织 UUID（SDK \u002F 自动化流程）\nexport ENABLE_CLAUDEAI_MCP_SERVERS=false               # 退出 claude.ai 同步的 MCP 服务器\nexport FORCE_AUTOUPDATE_PLUGINS=1                      # 允许插件自动更新，即使主更新程序已禁用\nexport IS_DEMO=1                                       # 演示模式 — 隐藏 UI 中的邮箱\u002F组织信息\nexport NO_PROXY=\"localhost,127.0.0.1\"                  # 对指定主机绕过代理（逗号分隔）\n\n```\n\n\u003Ch2 id=\"global-config-options\">全局配置选项\u003C\u002Fh2>\n\n```bash\nclaude config set -g theme dark                               # 主题：dark | light | light-daltonized | dark-daltonized\nclaude config set -g preferredNotifChannel iterm2_with_bell   # 通知通道：iterm2 | iterm2_with_bell | terminal_bell | notifications_disabled\nclaude config set -g autoUpdates true                         # 自动下载并安装更新（重启后生效）\nclaude config set -g verbose true                             # 显示完整的 bash\u002F命令输出\n\nclaude config set -g attribution false                        # 在 git 提交\u002FPR 中省略“co-authored-by Claude”\nclaude config set -g forceLoginMethod claudeai                 # 限制登录方式：claudeai | console\nclaude config set -g model \"claude-sonnet-4-6-20260217\"       # 默认模型覆盖\nclaude config set -g statusLine '{\"type\":\"command\",\"command\":\"~\u002F.claude\u002Fstatusline.sh\"}'  # 自定义状态栏\n\nclaude config set -g enableAllProjectMcpServers true              # 自动批准 .mcp.json 中的所有 MCP 服务器\nclaude config set -g enabledMcpjsonServers '[\"memory\",\"github\"]'  # 批准特定的 MCP 服务器\nclaude config set -g disabledMcpjsonServers '[\"filesystem\"]'      # 拒绝特定的 MCP 服务器\n```\n\n\u003Ch2 id=\"configuration-files\">配置文件\u003C\u002Fh2>\n\n（内存类型）Claude Code 提供四种按层级结构排列的内存位置，每种都有不同的用途：\n\n| 内存类型                | 位置                                                                                                                                                | 用途                                             | 使用场景示例                                                    | 共享对象                     |\n| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |\n| **企业策略**      | macOS: `\u002FLibrary\u002FApplication Support\u002FClaudeCode\u002FCLAUDE.md`\u003Cbr \u002F>Linux: `\u002Fetc\u002Fclaude-code\u002FCLAUDE.md`\u003Cbr \u002F>Windows: `C:\\ProgramData\\ClaudeCode\\CLAUDE.md` | IT\u002FDevOps 管理的组织级指令 | 公司编码规范、安全策略、合规要求 | 组织内所有用户       |\n| **项目内存**         | `.\u002FCLAUDE.md`                                                                                                                                           | 团队共享的项目指导说明            | 项目架构、编码规范、通用工作流             | 通过源代码管理工具与团队成员共享 |\n| **用户内存**            | `~\u002F.claude\u002FCLAUDE.md`                                                                                                                                   | 适用于所有项目的个人偏好               | 代码风格偏好、个人工具快捷方式                 | 仅您自己（所有项目）         |\n| **项目内存（本地）** | `.\u002FCLAUDE.local.md`                                                                                                                                     | 仅针对当前项目的个人偏好（被 git 忽略） | 您的沙盒 URL、首选测试数据、个人自定义设置           | 仅您自己（当前项目）      |\n| **项目规则**          | `.claude\u002Frules\u002F*.md`                                                                                                                                    | 模块化的项目规则（与 CLAUDE.md 一起加载）  | 代码检查规则、API 规范、目录级标准              | 通过源代码管理工具与团队成员共享 |\n\n> 所有内存文件在 Claude Code 启动时会自动加载到上下文中。层级较高的文件优先加载，作为更具体记忆的基础。\n\n#### `.claude\u002Frules\u002F` 目录（v2.0.64+）\n\n`.claude\u002Frules\u002F` 目录允许您将项目说明拆分为多个独立的 Markdown 文件，而不是使用一个大型的 `CLAUDE.md` 文件。该目录下的每个 `*.md` 文件都会自动与 `CLAUDE.md` 一同加载到上下文中。这非常有用：\n\n- **模块化组织**：分离不同关注点（例如 `api-conventions.md`、`testing-rules.md`）\n- **按目录覆盖**：嵌套的 `rules\u002F` 目录可以应用作用域限定的规则\n- **团队协作**：不同团队成员可以通过 PR 审查分别负责不同的规则文件\n\n#### 自动内存（v2.1.32+）\n\nClaude 现在会在您的会话过程中自动将有用上下文保存到记忆中。这些管理的记忆包括项目规范、工具偏好以及 Claude 在与您协作时观察到的架构决策等。您可以使用 `\u002Fmemory` 命令来查看和管理自动保存的记忆。\n\n---\n\n\u003Ch1 id=\"commands--usage\">命令与用法\u003C\u002Fh1>\n\n\u003Ch2 id=\"claude-commands\">斜杠命令参考\u003C\u002Fh2>\n\n| 命令                   | 用途                                                                                                  |\n| :------------------------ | :------------------------------------------------------------------------------------------------------- |\n| `\u002Fadd-dir`                | 添加额外的工作目录                                                                       |\n| `\u002Fagents`                 | 管理用于特定任务的自定义 AI 子代理                                                     |\n| `\u002Fbug`                    | 报告错误（将对话发送至 Anthropic）                                                            |\n| `\u002Fclear`                  | 清除对话历史                                                                               |\n| `\u002Fcompact [instructions]` | 缩短对话，可选指定关注点说明                                                    |\n| `\u002Fconfig`                 | 打开设置界面（“配置”选项卡）                                                             |\n| `\u002Fcontext`                | 以彩色网格形式可视化当前上下文使用情况                                                        |\n| `\u002Fcopy`                   | 将对话内容复制到剪贴板                                                                   |\n| `\u002Fcost`                   | 显示 token 使用统计信息和计费信息                                                      |\n| `\u002Fdebug`                  | 排查当前会话并诊断问题                                                         |\n| `\u002Fdoctor`                 | 检查 Claude Code 安装状态                                                               |\n| `\u002Fexit`                   | 退出 REPL                                                                                            |\n| `\u002Fexport [filename]`      | 将当前对话导出到文件或剪贴板                                                           |\n| `\u002Fextra-usage`            | 启用额外使用模式（需在使用 `\u002Ffast` 之前启用）                                                        |\n| `\u002Ffast`                   | 切换快速模式，以加速 Opus 4.6 的响应                                                      |\n| `\u002Ffork`                   | 将当前对话分叉为一个新的会话                                                         |\n| `\u002Fhelp`                   | 获取使用帮助                                                                                           |\n| `\u002Finit`                   | 使用 CLAUDE.md 指南初始化项目                                                                  |\n| `\u002Finsights`               | 生成交互式 HTML 报告，分析您的编码习惯                                         |\n| `\u002Fkeybindings`            | 配置自定义键盘快捷键                                                                      |\n| `\u002Flogin`                  | 切换 Anthropic 账户                                                                                |\n| `\u002Flogout`                 | 退出 Anthropic 账户                                                                     |\n| `\u002Fmcp`                    | 管理 MCP 服务器连接和 OAuth 认证                                                       |\n| `\u002Fmemory`                 | 编辑 CLAUDE.md 内存文件                                                                              |\n| `\u002Fmodel`                  | 选择或更换 AI 模型                                                                            |\n| `\u002Fpermissions`            | 查看或更新工具权限                                                                          |\n| `\u002Fplan`                   | 直接从提示符进入计划模式                                                                 |\n| `\u002Fplugins`                | 管理插件（安装、启用、禁用、插件市场）                                                   |\n| `\u002Fpr_comments`            | 查看拉取请求评论                                                                               |\n| `\u002Frename \u003Cname>`          | 重命名当前会话，便于识别                                                     |\n| `\u002Fresume [session]`       | 根据会话 ID 或名称恢复对话，或打开会话选择器                                              |\n| `\u002Freview`                 | 请求代码审查                                                                                      |\n| `\u002Frules`                  | 查看并管理 `.claude\u002Frules\u002F` 目录（模块化项目规则）                                       |\n| `\u002Frewind`                 | 将对话和\u002F或代码回退到先前的点                                                  |\n| `\u002Fsandbox`                | 查看沙盒依赖状态及安装说明                                            |\n| `\u002Fstats`                  | 可视化每日使用情况、会话历史、连续使用天数以及模型偏好                                   |\n| `\u002Fsettings`               | 打开设置界面（`\u002Fconfig` 的别名）                                                            |\n| `\u002Fsimplify`               | 简化选定的代码或对话（内置技能）                                                   |\n| `\u002Fstatus`                 | 打开设置界面（“状态”选项卡），显示版本、模型、账户                                     |\n| `\u002Fstatusline`             | 设置 Claude Code 的状态栏 UI                                                                      |\n| `\u002Ftasks`                  | 列出并管理后台任务                                                                         |\n| `\u002Fteleport`               | 从 claude.ai 恢复远程会话（仅限订阅用户）                                                |\n| `\u002Fterminal-setup`         | 安装 Shift+Enter 键绑定以实现换行（适用于 iTerm2、VS Code、Kitty、Alacritty、Zed、Warp 和 WezTerm） |\n| `\u002Fremote-env`             | 配置远程环境设置                                                                    |\n| `\u002Ftheme`                  | 更改颜色主题                                                                                   |\n| `\u002Ftodos`                  | 列出当前待办事项                                                                                  |\n| `\u002Fusage`                  | 显示计划使用限制和速率限制状态（订阅计划）                                        |\n| `\u002Fvim`                    | 进入 vim 模式，可在插入模式和命令模式之间切换                                          |\n| `\u002Fbatch`                  | 对多个文件执行批量操作（内置技能）                                                   |\n\n\u003Ch2 id=\"command-line-flags\">命令行标志\u003C\u002Fh2>\n\n| 标志 \u002F 命令                                       | 描述                                                                                                                                                  | 示例                                                                                |\n| :--------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------- |\n| `-d, --debug`                                        | 启用调试模式（显示详细的调试输出）。                                                                                                             | `claude -d -p \"query\"`                                                                 |\n| `--include-partial-messages`                         | 通过 CLI 标志支持部分消息流式传输                                                                                                               |\n| `--mcp-debug`                                        | [已弃用] MCP 调试模式（显示 MCP 服务器错误）。请改用 `--debug`。                                                                                | `claude --mcp-debug`                                                                   |\n| `--verbose`                                          | 覆盖配置中的详细模式设置（显示扩展日志记录\u002F逐步输出）。                                                                    | `claude --verbose`                                                                     |\n| `-p, --print`                                        | 打印响应并退出（适用于管道输出）。                                                                                                          | `claude -p \"query\"`                                                                    |\n| `--output-format \u003Cformat>`                           | 输出格式（仅与 `--print` 一起使用）：`text`（默认）、`json`（单个结果）或 `stream-json`（实时流式传输）。                                  | `claude -p \"query\" --output-format json`                                               |\n| `--input-format \u003Cformat>`                            | 输入格式（仅与 `--print` 一起使用）：`text`（默认）或 `stream-json`（实时流式输入）。                                                      | `claude -p --output-format stream-json --input-format stream-json`                     |\n| `--replay-user-messages`                             | 将来自标准输入的用户消息重新发送回标准输出以进行确认 — **仅在** `--input-format=stream-json` **和** `--output-format=stream-json` **时有效**。 | `claude --input-format stream-json --output-format stream-json --replay-user-messages` |\n| `--allowedTools`, `--allowed-tools \u003Ctools...>`       | 允许使用的工具名称列表，以逗号或空格分隔（例如 `\"Bash(git:*) Edit\"`）。                                                                               | `--allowed-tools \"Bash(git:*)\" Edit\"`                                                  |\n| `--disallowedTools`, `--disallowed-tools \u003Ctools...>` | 禁止使用的工具名称列表，以逗号或空格分隔（例如 `\"Bash(git:*) Edit\"`）。                                                                                | `--disallowed-tools \"Edit\"`                                                            |\n| `--mcp-config \u003Cconfigs...>`                          | 从 JSON 文件或字符串中加载 MCP 服务器（以空格分隔）。                                                                                               | `claude --mcp-config .\u002Fmcp-servers.json`                                               |\n| `--strict-mcp-config`                                | 仅使用 `--mcp-config` 中指定的 MCP 服务器，忽略其他 MCP 配置。                                                                                 | `claude --mcp-config .\u002Fa.json --strict-mcp-config`                                     |\n| `--append-system-prompt \u003Cprompt>`                    | 将系统提示附加到默认系统提示（适用于打印模式）。                                                                                  | `claude -p --append-system-prompt \"Do X then Y\"`                                       |\n| `--permission-mode \u003Cmode>`                           | 会话的权限模式（选项包括 `acceptEdits`、`bypassPermissions`、`default`、`plan`）。                                                     | `claude --permission-mode plan`                                                        |\n| `--permission-prompt-tool \u003Ctool>`                    | 指定一个 MCP 工具来处理非交互模式下的权限提示。                                                                                    | `claude -p --permission-prompt-tool mcp_auth_tool \"query\"`                             |\n| `--fallback-model \u003Cmodel>`                           | 当默认模型过载时，启用自动回退到指定模型（注意：根据帮助信息，仅适用于 `--print`）。                                    | `claude -p --fallback-model claude-haiku-20240307 \"query\"`                             |\n| `--model \u003Cmodel>`                                    | 当前会话使用的模型。接受别名，如 `sonnet`\u002F`opus` 或完整的模型名称（例如 `claude-sonnet-4-6-20260217`）。                                | `claude --model sonnet`                                                                |\n| `--settings \u003Cfile-or-json>`                          | 从 JSON 文件或 JSON 字符串中加载额外的设置。                                                                                                  | `claude --settings .\u002Fsettings.json`                                                    |\n| `--add-dir \u003Cdirectories...>`                         | 允许工具访问的额外目录。                                                                                                              | `claude --add-dir ..\u002Fapps ..\u002Flib`                                                      |\n| `--ide`                                              | 如果恰好有一个有效的 IDE 可用，则在启动时自动连接到 IDE。                                                                            | `claude --ide`                                                                         |\n| `-c, --continue`                                     | 继续当前目录中的最近一次对话。                                                                                              | `claude --continue`                                                                    |\n| `-r, --resume [sessionId]`                           | 恢复对话；提供会话 ID 或交互式选择一个。                                                                                     | `claude -r \"abc123\"`                                                                   |\n| `--session-id \u003Cuuid>`                                | 使用特定的会话 ID 进行对话（必须是有效的 UUID）。                                                                                       | `claude --session-id 123e4567-e89b-12d3-a456-426614174000`                             |\n| `--agents \u003Cjson>`                                    | 通过 JSON 动态定义自定义子代理（格式参见子代理文档）。                                                                                 | `claude --agents '{\"reviewer\":{\"description\":\"Reviews code\",\"prompt\":\"...\"}}'`         |\n| `--agent \u003Cname>`                                     | 指定当前会话的特定代理。                                                                                                            | `claude --agent my-custom-agent`                                                       |\n| `--chrome`                                           | 启用 Chrome 浏览器集成，用于网页自动化和测试。                                                                                            | `claude --chrome`                                                                      |\n| `--no-chrome`                                        | 禁用本次会话的 Chrome 浏览器集成。                                                                                                         | `claude --no-chrome`                                                                   |\n| `--remote`                                           | 使用提供的任务描述在 claude.ai 上创建一个新的网页会话。                                                                                    | `claude --remote \"Fix the login bug\"`                                                  |\n| `--teleport`                                         | 在本地终端中恢复网页会话。                                                                                                                 | `claude --teleport`                                                                    |\n| `--fork-session`                                     | 恢复时，创建一个新的会话 ID，而不是重复使用原来的会话。                                                                                      | `claude --resume abc123 --fork-session`                                                |\n| `--json-schema \u003Cschema>`                             | 在代理完成任务后，获取符合 JSON Schema 的验证后 JSON 输出（仅限打印模式）。                                                                    | `claude -p --json-schema '{\"type\":\"object\",...}' \"query\"`                              |\n| `--max-budget-usd \u003Camount>`                          | 在停止之前，API 调用的最大美元金额（仅限打印模式）。                                                                               | `claude -p --max-budget-usd 5.00 \"query\"`                                              |\n| `--max-turns \u003Cn>`                                    | 限制代理执行的轮次数量（仅限打印模式）。达到限制时将报错退出。                                                                    | `claude -p --max-turns 3 \"query\"`                                                      |\n| `--betas \u003Cheaders>`                                  | 包含在 API 请求中的测试版标头（仅限 API 密钥用户）。                                                                                                | `claude --betas interleaved-thinking`                                                  |\n| `--tools \u003Ctools>`                                    | 限制 Claude 可以使用的内置工具。使用 `\"\"` 禁用所有工具，使用 `\"default\"` 使用所有工具，或指定具体工具名称。                                              | `claude --tools \"Bash,Edit,Read\"`                                                      |\n| `--system-prompt \u003Cprompt>`                           | 用自定义文本替换整个系统提示（适用于交互式和打印模式）。                                                                    | `claude --system-prompt \"You are a Python expert\"`                                     |\n| `--system-prompt-file \u003Cfile>`                        | 从文件加载系统提示，替换默认提示（仅限打印模式）。                                                                              | `claude -p --system-prompt-file .\u002Fcustom-prompt.txt \"query\"`                           |\n| `--append-system-prompt-file \u003Cfile>`                 | 从文件加载额外的系统提示文本，并将其附加到默认提示上（仅限打印模式）。                                                                      | `claude -p --append-system-prompt-file .\u002Fextra-rules.txt \"query\"`                      |\n| `--plugin-dir \u003Cdir>`                                 | 仅为此会话从目录加载插件（可重复）。                                                                                            | `claude --plugin-dir .\u002Fmy-plugins`                                                     |\n| `--setting-sources \u003Csources>`                        | 要加载的设置来源列表，以逗号分隔（用户、项目、本地）。                                                                                      | `claude --setting-sources user,project`                                                |\n| `--no-session-persistence`                           | 禁用会话持久化，使会话不会保存到磁盘（仅限打印模式）。                                                                             | `claude -p --no-session-persistence \"query\"`                                           |\n| `--disable-slash-commands`                           | 禁用本次会话的所有技能和斜杠命令。                                                                                                      | `claude --disable-slash-commands`                                                      |\n| `--dangerously-skip-permissions`                     | 跳过所有权限检查（仅限受信任的沙盒环境）。                                                                                                   | `claude --dangerously-skip-permissions`                                                |\n| `--worktree`, `-w`                                   | 在隔离的 git 工作树中开始（v2.1.49）。                                                                                                                 | `claude -w \"implement feature\"`                                                        |\n| `--from-pr \u003Curl>`                                    | 从拉取请求 URL 开始会话（v2.1.27）。                                                                                                             | `claude --from-pr https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\u002Fpull\u002F123`                                |\n| `--init`                                             | 触发 Setup 钩子事件（v2.1.10）。                                                                                                                          | `claude --init`                                                                        |\n| `--init-only`                                        | 运行 Setup 钩子并退出（v2.1.10）。                                                                                                                           | `claude --init-only`                                                                   |\n| `--maintenance`                                      | 在维护模式下运行 Setup 钩子（v2.1.10）。                                                                                                                | `claude --maintenance`                                                                 |\n| `-v, --version`                                      | 显示已安装的 `claude` CLI 版本。                                                                                                                     | `claude --version`                                                                     |\n| `-h, --help`                                         | 显示帮助\u002F用法。                                                                                                                                        | `claude --help`                                                                        |\n\n> `--output-format json` 标志对于脚本编写和自动化特别有用，允许你以编程方式解析 Claude 的响应。\n\n\u003Ch2 id=\"cheat-sheet\">CLI 快速参考与配置示例\u003C\u002Fh2>\n\n```md\n\n\n## Claude 备忘录\n\n# 基础 \u002F 交互式\n\nclaude # 启动交互式 REPL\nclaude \"解释这个项目\" # 启动带有提示的 REPL\nclaude -p \"总结 README.md\" # 非交互式打印模式（基于 SDK）\ncat logs.txt | claude -p \"解释\" # 将输入通过管道传递给 Claude 并退出\nclaude -c # 继续最近的对话（--continue 的别名）\nclaude -r \"\u003Csession-id>\" \"完成这个\" # 通过 ID 恢复特定会话（--resume 的别名）\nclaude --model claude-sonnet-4-6-20260217 # 为本次运行选择模型\nclaude --max-turns 3 -p \"检查代码\" # 在打印模式下限制代理式轮次\nclaude --replay-user-messages # 将用户消息回放至标准输出，用于调试或 SDK 工作流\n\n# 更新与安装\n\nclaude update # 手动更新 Claude Code\nclaude doctor # 诊断安装\u002F版本及设置\nclaude install # 启动原生二进制安装程序（测试版）\nclaude migrate-installer # 从全局 npm 安装迁移到本地安装程序\n\n# 身份验证（v2.1.41+）\n\nclaude auth login # 登录你的 Anthropic 账户\nclaude auth status # 检查身份验证状态\nclaude auth logout # 注销\n\n# 代理管理（v2.1.50+）\n\nclaude agents # 列出所有已配置的代理（项目、用户、插件）\nclaude remote-control # 启动远程控制模式，用于外部工具\n\n# 配置：交互式向导 + 直接操作\n\nclaude config # 交互式配置向导\nclaude config get \u003Ckey> # 获取值（例如，claude config get theme）\nclaude config set \u003Ckey> \u003Cval> # 设置值（例如，claude config set theme dark）\nclaude config add \u003Ckey> \u003Cvals…> # 向数组类型键追加值（例如，claude config add env DEV=1）\nclaude config remove \u003Ckey> \u003Cvals…> # 从列表类型键中移除条目\nclaude config list # 显示当前项目的全部设置（默认为项目范围）\n\n# 示例项目范围设置\n\nclaude config set model \"claude-sonnet-4-6-20260217\" # 覆盖该项目的默认模型\nclaude config set attribution false # 禁用 git\u002FPR 中的“由 Claude 共同创作”署名\nclaude config set forceLoginMethod claudeai # 限制登录流程：claudeai | console\nclaude config set enableAllProjectMcpServers true # 自动批准 .mcp.json 中的所有 MCP 服务器\nclaude config set defaultMode \"acceptEdits\" # 设置默认权限模式\nclaude config set disableBypassPermissionsMode disable # 阻止绕过权限模式（示例键）\n\n# 管理列表设置（项目范围）\n\nclaude config add enabledMcpjsonServers github # 批准 .mcp.json 中的特定 MCP 服务器\nclaude config add enabledMcpjsonServers memory # 再添加一个\nclaude config remove enabledMcpjsonServers memory # 移除一条记录\nclaude config add disabledMcpjsonServers filesystem # 明确拒绝特定 MCP 服务器\n\n# 全局范围（使用 -g 或 --global）\n\nclaude config set -g autoUpdates false # 关闭全局自动更新\nclaude config set --global preferredNotifChannel iterm2_with_bell\nclaude config set -g theme dark # 主题：dark | light | light-daltonized | dark-daltonized\nclaude config set -g verbose true # 在所有地方显示完整的 bash\u002F命令输出\nclaude config get -g theme # 确认全局值\n\n# MCP（模型上下文协议）管理\n\nclaude mcp # 启动 MCP 向导 \u002F 配置 MCP 服务器\nclaude mcp list # 列出已配置的 MCP 服务器\nclaude mcp get \u003Cname> # 显示某服务器的详细信息\nclaude mcp remove \u003Cname> # 移除服务器\nclaude mcp add \u003Cname> \u003Ccommand> [args...] # 添加本地 stdio 服务器\nclaude mcp add --transport sse \u003Cname> \u003Curl> # 添加远程 SSE 服务器\nclaude mcp add --transport http \u003Cname> \u003Curl> # 添加远程 HTTP 服务器\nclaude mcp add \u003Cname> --env KEY=VALUE -- \u003Ccmd> [args...] # 将环境变量传递给服务器命令\nclaude mcp add --transport sse private-api https:\u002F\u002Fapi.example\u002Fmcp \\\n --header \"Authorization: Bearer TOKEN\" # 添加带认证头的服务器\nclaude mcp add-json \u003Cname> '\u003Cjson>' # 通过 JSON 数据块添加服务器\nclaude mcp add-from-claude-desktop # 从 Claude Desktop 导入服务器\nclaude mcp reset-project-choices # 重置对项目 .mcp.json 服务器的批准\nclaude mcp serve # 运行 Claude Code 本身作为 MCP stdio 服务器\n\n# 其他实用标志（打印 \u002F SDK 模式）\n\nclaude --add-dir ..\u002Fapps ..\u002Flib # 添加额外的工作目录\nclaude --allowedTools \"Bash(git log:\\*)\" \"Read\" # 允许列出的工具无需权限提示\nclaude --disallowedTools \"Edit\" # 禁止列出的工具无需权限提示\nclaude --append-system-prompt \"自定义指令\" # 向系统提示追加内容（仅限 -p 使用）\nclaude -p \"查询\" --output-format json --input-format stream-json # 控制脚本编写的 IO 格式\nclaude --verbose # 详细日志记录（逐步）\nclaude --dangerously-skip-permissions # 跳过权限提示（谨慎使用）\nclaude --permission-mode plan # 以计划模式启动（只读分析）\nclaude --max-turns 3 -p \"查询\" # 限制代理式轮次（仅限打印模式）\nclaude --max-budget-usd 5.00 -p \"查询\" # 限制每次会话的支出（仅限打印模式）\nclaude --json-schema '{\"type\":\"object\"}' -p \"查询\" # 获取经过验证的 JSON 输出\nclaude --chrome # 启用 Chrome 浏览器集成\nclaude --remote \"修复这个 bug\" # 在 claude.ai 上创建网络会话\nclaude --teleport # 在本地恢复网络会话\nclaude --agents '{\"name\":{...}}' # 通过 JSON 定义子代理\n\n# 会话管理\n\nclaude -c # 继续最近的对话\nclaude -r \"会话名称\" # 按名称或 ID 恢复\nclaude --fork-session -r abc123 # 分叉而非重复使用原始会话\nclaude -w \"实现功能\" # 在隔离的 git 工作树中开始\n\u002Frename auth-refactor # 为当前会话命名\n\u002Fresume # 打开会话选择器\n\u002Fexport output.md # 将对话导出到文件\n\u002Ffork # 分叉当前对话\n\n# 快速验证 \u002F 注意事项\n\n# - 默认情况下，'claude config' 的作用范围是项目；使用 -g\u002F--global 可影响所有项目。\n\n# - 设置优先级：企业 > CLI 参数 > 本地项目 > 共享项目 > 用户 (~\u002F.claude)。\n\n# - 仅在列表类型键上使用 'add' \u002F 'remove'（例如，enabledMcpjsonServers）。\n\n# - CLI 参考和发布说明是关于标志及最新功能的权威来源。\n```\n\n---\n\n\u003Ch1 id=\"interface--input\">界面与输入\u003C\u002Fh1>\n\n\u003Ch2 id=\"keyboard-shortcuts\">键盘快捷键\u003C\u002Fh2>\n\n| 快捷键                     | 描述                        | 上下文                                  |\n| :--------------------------- | :-------------------------- | :--------------------------------------- |\n| `Ctrl+C`                     | 取消当前输入或生成          | 标准中断                                 |\n| `Ctrl+D`                     | 退出 Claude Code 会话       | EOF 信号                                 |\n| `Ctrl+G`                     | 在默认文本编辑器中打开      | 编辑你的提示或自定义响应                 |\n| `Ctrl+L`                     | 清空终端屏幕                | 保留对话历史                             |\n| `Ctrl+O`                     | 切换详细输出                | 显示详细的工具使用和执行信息             |\n| `Ctrl+R`                     | 反向搜索命令历史            | 搜索之前的命令                           |\n| `Ctrl+V` 或 `Cmd+V` (iTerm2) | 粘贴剪贴板中的图片          | 粘贴图片或图片文件路径                   |\n| `Ctrl+B`                     | 后台运行任务                | 将 bash 命令和代理程序放到后台           |\n| `Ctrl+F`（按两次）           | 杀死所有后台代理            | 需要两次确认以停止代理                   |\n| `上\u002F下箭头`                 | 导航命令历史                | 回忆之前的输入                           |\n| `左\u002F右箭头`                 | 循环切换对话选项卡          | 在对话框的选项卡之间导航                 |\n| `Esc` + `Esc`                | 回退代码\u002F对话              | 恢复到之前的状态                         |\n| `Shift+Tab` 或 `Alt+M`       | 切换权限模式                | 在自动接受、计划、正常模式之间切换       |\n| `Option+P`（macOS） \u002F `Alt+P` | 切换模型                    | 切换模型而不清除提示                     |\n| `Option+T`（macOS） \u002F `Alt+T` | 切换扩展思考模式            | 启用或禁用扩展思考模式                   |\n\n\u003Ch3 id=\"text-editing\">文本编辑\u003C\u002Fh3>\n\n| 快捷键               | 描述                  | 上下文                               |\n| :--------------------- | :-------------------- | :------------------------------------ |\n| `Ctrl+K`               | 删除到行尾            | 存储已删除的文本以便粘贴             |\n| `Ctrl+U`               | 删除整行              | 存储已删除的文本以便粘贴             |\n| `Ctrl+Y`               | 粘贴已删除的文本      | 粘贴使用 Ctrl+K\u002FU 删除的文本         |\n| `Alt+Y`（在 Ctrl+Y 之后） | 循环粘贴历史          | 循环浏览之前删除的文本                 |\n| `Alt+B`                | 光标后移一个单词      | macOS 上需要 Option 键作为 Meta 键    |\n| `Alt+F`                | 光标前移一个单词      | macOS 上需要 Option 键作为 Meta 键    |\n\n\u003Ch3 id=\"multiline-input\">多行输入\u003C\u002Fh3>\n\n| 方法           | 快捷键       | 上下文                           |\n| :--------------- | :------------- | :-------------------------------- |\n| 快速转义     | `\\` + `Enter`  | 适用于所有终端            |\n| macOS 默认    | `Option+Enter` | macOS 的默认设置          |\n| 终端设置   | `Shift+Enter`  | 在执行 `\u002Fterminal-setup` 之后 |\n| 控制序列   | `Ctrl+J`       | 多行换行符字符            |\n| 粘贴模式   | 直接粘贴       | 用于代码块、日志等        |\n\n\u003Ch3 id=\"quick-commands\">快速命令\u003C\u002Fh3>\n\n| 快捷键     | 描述       | 注释                                 |\n| :----------- | :--------- | :------------------------------------ |\n| `\u002F` 开头 | 命令或技能  | 查看内置命令和技能                  |\n| `!` 开头 | Bash 模式   | 直接运行命令，并将其添加到上下文中  |\n| `@`          | 文件路径提及 | 触发文件路径自动补全                  |\n\n> [!Tip]\n> **PDF 页面范围：** 使用 Read 工具时，可以通过 `pages` 参数指定 PDF 的页面范围（例如，`pages: \"1-5\"`）。超过 10 页的大 PDF 在被 @ 提及时不会内联显示，而是返回一个轻量级引用。\n\n\u003Ch2 id=\"vim-mode\">Vim 模式\u003C\u002Fh2>\n\n> [!Note]\n> 可以通过 `\u002Fvim` 命令启用 Vim 风格的编辑，或者通过 `\u002Fconfig` 永久配置。\n\n\u003Ch3 id=\"vim-mode-switching\">Vim 模式切换\u003C\u002Fh3>\n\n| 命令 | 动作                      | 当前模式 |\n| :------ | :-------------------------- | :-------- |\n| `Esc`   | 进入 NORMAL 模式           | INSERT    |\n| `i`     | 在光标前插入              | NORMAL    |\n| `I`     | 在行首插入                | NORMAL    |\n| `a`     | 在光标后插入              | NORMAL    |\n| `A`     | 在行尾插入                | NORMAL    |\n| `o`     | 在当前行下方打开新行      | NORMAL    |\n| `O`     | 在当前行上方打开新行      | NORMAL    |\n\n\u003Ch3 id=\"vim-navigation\">Vim 导航\u003C\u002Fh3>\n\n| 命令         | 动作                    |\n| :-------------- | :------------------------ |\n| `h`\u002F`j`\u002F`k`\u002F`l` | 左\u002F下\u002F上\u002F右移动   |\n| `w`             | 移动到下一个单词                 |\n| `e`             | 移动到单词末尾                   |\n| `b`             | 移动到上一个单词                 |\n| `0`             | 行首                             |\n| `$`             | 行尾                             |\n| `^`             | 第一个非空白字符                 |\n| `gg`            | 输入开头                         |\n| `G`             | 输入结尾                         |\n\n\u003Ch3 id=\"vim-editing\">Vim 编辑\u003C\u002Fh3>\n\n| 命令        | 动作                  |\n| :------------- | :---------------------- |\n| `x`            | 删除字符              |\n| `dd`           | 删除一行              |\n| `D`            | 删除到行尾            |\n| `dw`\u002F`de`\u002F`db` | 删除单词\u002F到末尾\u002F到前面 |\n| `cc`           | 更改整行              |\n| `C`            | 更改到行尾            |\n| `cw`\u002F`ce`\u002F`cb` | 更改单词\u002F到末尾\u002F到前面 |\n| `.`            | 重复上次更改          |\n\n> [!Tip]\n> 在终端设置中配置你喜欢的换行行为。运行 `\u002Fterminal-setup` 可以为 iTerm2、VS Code、Kitty、Alacritty、Zed、Warp 和 WezTerm 安装 Shift+Enter 绑定。\n\n\u003Ch2 id=\"command-history\">命令历史\u003C\u002Fh2>\n\n> Claude Code 会为当前会话保存命令历史：\n\n```\n* 历史按工作目录存储\n* 可通过 `\u002Fclear` 命令清空\n* 使用上\u002F下箭头导航（参见上述键盘快捷键）\n* **Ctrl+R**：反向搜索历史（如果终端支持）\n* **注意**：默认情况下，历史展开功能（`!`）已被禁用\n```\n\n---\n\n\u003Ch1 id=\"advanced-features\">高级功能\u003C\u002Fh1>\n\n\u003Ch2 id=\"thinking-keywords\">思考关键词\u003C\u002Fh2>\n\n> [!Note]\n> **通过在提示中加入以下关键词之一，可为 Claude 提供额外的预答准备时间。**\n> **按消耗令牌数量由低到高排序**\n>\n> \u003Ctable>\u003Ctr>\u003Ctd>\n>\n> > **\u003Ckbd>think\u003C\u002Fkbd> -------------> 最低**\n>\n> > **\u003Ckbd>think hard\u003C\u002Fkbd>**\n>\n> > **\u003Ckbd>think harder\u003C\u002Fkbd>**\n>\n> > **\u003Ckbd>ultrathink\u003C\u002Fkbd> --------> 最高**\n>\n> \u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftable>\n\n\u003Ch3 id=\"this-makes-claude-spend-more-time\">这会让 Claude 花更多时间：\u003C\u002Fh3>\n\n1. **规划解决方案**\n2. #### 分解步骤\n3. #### 权衡替代方案\u002F取舍\n4. #### 检查约束条件与边界情况\n   > > #### 更高的级别通常会增加**延迟**和**令牌使用量**，请选择能工作的最小级别。\n\n\u003Ch5 id=\"thinking-examples\">示例\u003C\u002Fh5>\n\n```md\n\n\n# 小幅提升\n\nclaude -p \"思考。概述一个重构认证模块的计划。\"\n\n# 中度提升\n\nclaude -p \"更深入地思考。起草一个从 REST 迁移到 gRPC 的迁移计划。\"\n\n# 最大提升\n\nclaude -p \"超深度思考。提出一个逐步解决支付测试不稳定问题并添加防护机制的策略。\"\n```\n\n\u003Ch2 id=\"fast-mode\">快速模式\u003C\u002Fh2>\n\n> [!注意]\n> **快速模式为 Opus 4.6 提供加速响应时间，专为快速迭代和简单任务优化。**\n\n**如何启用快速模式：**\n\n```bash\n# 在 REPL 中启用快速模式（需先启用额外使用权限）\n\u002Fextra-usage\n\u002Ffast\n\n# 或在对话过程中切换\n# 状态栏会显示快速模式是否已激活\n```\n\n**主要特性：**\n\n- **更快的响应** - 缩短简单任务的延迟\n- **适用于 Opus 4.6** - 新增于版本 2.1.36\n- **需要额外使用权限** - 必须先启用 `\u002Fextra-usage`\n\n**何时使用快速模式：**\n\n- 快速代码审查和编辑\n- 快速原型开发\n- 简单的问题和命令\n- 迭代式调试\n\n> 快速模式以牺牲部分深度为代价换取速度。对于复杂分析和规划任务，请使用正常模式。\n\n\u003Ch2 id=\"plan-mode\">计划模式\u003C\u002Fh2>\n\n> [!注意]\n> **计划模式指示 Claude 以只读方式分析代码库，非常适合探索代码库、规划复杂变更或安全地审查代码。**\n\n**何时使用计划模式：**\n\n- **多步骤实现**：当您的功能需要修改多个文件时\n- **代码探索**：当您希望在进行任何更改之前彻底研究代码库时\n- **交互式开发**：当您希望与 Claude 一起迭代开发方向时\n\n**如何启用计划模式：**\n\n```bash\n# 以计划模式开始新会话\nclaude --permission-mode plan\n\n# 或在会话中通过 Shift+Tab 切换\n# （循环顺序：正常 → 自动接受 → 计划模式）\n\n# 从提示符进入计划模式\n\u002Fplan\n\n# 在计划模式下运行无头查询\nclaude --permission-mode plan -p \"分析认证系统并提出改进建议\"\n```\n\n**将计划模式设置为默认：**\n\n```json\n\u002F\u002F .claude\u002Fsettings.json\n{\n  \"permissions\": {\n    \"defaultMode\": \"plan\"\n  }\n}\n```\n\n---\n\n\u003Ch2 id=\"background-tasks\">后台任务\u003C\u002Fh2>\n\n> [!注意]\n> **Claude Code 支持在后台运行 bash 命令，让您可以在长时间运行的进程执行时继续工作。**\n\n**如何使用后台任务：**\n\n| 方法        | 描述                                                                |\n| :------------ | :------------------------------------------------------------------------- |\n| 向 Claude 提示 | 请求 Claude“在后台运行此命令”                                 |\n| `Ctrl+B`      | 将正在运行的 Bash 工具调用移动到后台（tmux 用户需按两次） |\n\n**主要特性：**\n\n- 输出会被缓冲，Claude 可以使用 TaskOutput 工具检索输出\n- 后台任务具有唯一 ID，便于跟踪和获取输出\n- 当 Claude Code 退出时，后台任务会自动清理\n- 使用 `\u002Ftasks` 可以列出和管理后台任务\n\n**常见的后台命令：**\n\n- 构建工具（webpack、vite、make）\n- 包管理器（npm、yarn、pnpm）\n- 测试运行器（jest、pytest）\n- 开发服务器\n- 长时间运行的进程（docker、terraform）\n\n**带有 `!` 前缀的 Bash 模式：**\n\n```bash\n# 直接运行 bash 命令，无需 Claude 解释\n! npm test\n! git status\n! ls -la\n```\n\n**禁用后台任务：**\n\n```bash\nexport CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1\n```\n\n---\n\n\u003Ch2 id=\"remote-sessions\">远程会话\u003C\u002Fh2>\n\n> [!注意]\n> **订阅用户可使用 `--remote` 在 claude.ai 上启动任务，并使用 `--teleport` 在本地恢复这些任务。**\n\n**启动远程会话：**\n\n```bash\n# 在 claude.ai 上创建包含任务描述的新 Web 会话\nclaude --remote \"修复登录错误\"\n```\n\n**恢复远程会话：**\n\n```bash\n# 在本地终端恢复 Web 会话\nclaude --teleport\n\n# 或者使用斜杠命令\n\u002Fteleport\n```\n\n---\n\n\u003Ch2 id=\"claude-in-chrome\">Claude 在 Chrome 中\u003C\u002Fh2>\n\nClaude Code 可以控制 Google Chrome 浏览器，用于执行基于浏览器的任务，例如测试、网页抓取和 UI 验证。\n\n**设置：**\n\n```bash\nclaude --chrome                    # 启动时集成 Chrome\n```\n\n**功能：**\n\n- 导航到 URL、点击页面元素、填写表单\n- 截取屏幕截图并分析页面内容\n- 在浏览器上下文中执行 JavaScript\n- 与 Web 应用程序交互以进行测试\n\n> [!注意]\n> 需要安装 Google Chrome。Claude 使用 Chrome DevTools 协议来控制浏览器。\n\n---\n\n\u003Ch2 id=\"sandbox-mode\">沙盒模式\u003C\u002Fh2>\n\n沙盒模式会将 BashTool 限制在一个隔离的环境中运行命令，从而防止对您实际文件系统的任何修改。\n\n```bash\n\u002Fsandbox              # 切换沙盒模式的开启或关闭\n```\n\n**在沙盒模式下：**\n\n- 文件系统写操作被限制在沙盒内\n- 网络访问可能会受到限制\n- 适合安全地测试破坏性命令\n\n该功能适用于 Linux 和 macOS。您可以使用 `claude --sandbox` 来以沙盒模式启动。\n\n---\n\n\u003Ch2 id=\"lsp-tool\">LSP 工具（语言服务器协议）\u003C\u002Fh2>\n\nClaude Code 集成了语言服务器，提供 IDE 级别的代码智能：\n\n- **转到定义** — 跳转到符号的定义处\n- **查找引用** — 查找整个代码库中某个符号的所有用法\n- **悬停信息** — 获取类型信息和文档\n\n当当前项目有兼容的语言服务器可用时，LSP 工具会自动激活。这使得 Claude 能够比仅通过文本搜索更精确地导航代码库。\n\n> 当工具结果超过 50,000 字符时，会自动持久化到磁盘，以便高效管理上下文。\n\n---\n\n\u003Ch2 id=\"sub-agents\">子代理\u003C\u002Fh2>\n\n> 子代理是专门构建的帮助程序，它们拥有各自的提示词、工具和独立的上下文窗口。您可以将其视为一种“专家混合体”，根据每个仓库的需求进行组合。\n\n\u003Ch3 id=\"built-in-subagents\">内置子代理\u003C\u002Fh3>\n\nClaude Code 包含一些内置子代理，Claude 会在适当的时候自动使用它们：\n\n| 子代理            | 模型        | 工具     | 用途                                           |\n| :------------------ | :----------- | :-------- | :------------------------------------------------ |\n| **Explore**         | Haiku（快速） | 只读     | 文件发现、代码搜索、代码库探索                 |\n| **Plan**            | 可配置       | 只读     | 规划复杂变更而不进行编辑                       |\n| **通用型**          | 默认         | 继承     | 一般任务委派                                   |\n\n> 当 Claude 需要搜索或理解代码库而无需进行更改时，它会委托给 **Explore** 子代理，这样探索的结果就不会进入您的主要对话上下文中。\n\n**何时使用子代理：**\n\n> - 您需要高信号响应（计划、评审、差异），而不需要额外的支线任务。\n> - 您希望提示词和工具策略能够与代码库一起版本化。\n> - 您在以 PR 为主导的团队中工作，并希望按角色进行范围限定的编辑。\n> - 任务会产生大量输出，而这些输出并不需要保留在您的主要上下文中。\n\n\u003Ch3 id=\"each-sub-agent-has-its-own-context\">每个子代理都有自己的上下文\u003C\u002Fh3>\n\n**为您的代理阵容设计规则**\n\n> - 为每个代理定义一个明确的责任。\n> - 保留该角色所需的最少工具集。\n> - 对于分析\u002F评审任务，优先选择只读代理。\n> - 尽可能减少具有编辑权限的代理数量。\n\n\u003Cimg width=\"700\" height=\"160\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_826a82b979ad.png\" \u002F>\n\n_图注：终端中的代理选择界面。_\n\n\u003Ch3 id=\"configure-agents\">配置代理\u003C\u002Fh3>\n\n> 将代理保存在项目中，这样它们就能随仓库一起版本化，并通过 PR 不断演进。\n\n\u003Ch3 id=\"agents-quick-start\">快速入门\u003C\u002Fh3>\n\n> 更新 CLI 并打开代理面板\n\n```bash\nclaude update\n\u002Fagents\n```\n\n\u003Ch3 id=\"agent-scopes\">子代理的作用范围\u003C\u002Fh3>\n\n| 位置                     | 作用范围                   | 优先级    |\n| :--------------------------- | :---------------------- | :---------- |\n| `--agents` CLI 标志          | 仅当前会话                | 1（最高） |\n| `.claude\u002Fagents\u002F`            | 当前项目                  | 2           |\n| `~\u002F.claude\u002Fagents\u002F`          | 您的所有项目              | 3           |\n| 插件的 `agents\u002F` 目录       | 插件启用的位置            | 4（最低）  |\n\n\u003Ch3 id=\"define-agents-via-cli\">通过 CLI 定义代理\u003C\u002Fh3>\n\n```bash\n# 通过 JSON 动态定义自定义子代理\nclaude --agents '{\n  \"code-reviewer\": {\n    \"description\": \"专业代码评审员。在代码变更后主动使用。\",\n    \"prompt\": \"你是一位资深代码评审员。专注于代码质量、安全性及最佳实践。\",\n    \"tools\": [\"Read\", \"Grep\", \"Glob\", \"Bash\"],\n    \"model\": \"sonnet\"\n  },\n  \"debugger\": {\n    \"description\": \"专门处理错误和测试失败的调试专家。\",\n    \"prompt\": \"你是一位经验丰富的调试专家。分析错误、找出根本原因并提供修复方案。\"\n  },\n  \"background-impl\": {\n    \"description\": \"在后台的隔离工作树中实现功能。\",\n    \"prompt\": \"实现请求的功能。完成后提交更改。\",\n    \"isolation\": \"worktree\",\n    \"background\": true\n  }\n}'\n```\n\n\u003Ch3 id=\"create-your-core-agents\">创建您的核心代理\u003C\u002Fh3>\n\n> - **planner**（只读）：将功能\u002F问题分解为可测试的小任务；输出任务列表或 plan.md。\n> - **codegen**（可编辑）：负责实现任务；仅限于 `src\u002F` 和 `tests\u002F`。\n> - **tester**（只读或仅限补丁）：编写一条失败的测试用例或最小的复现代码。\n> - **reviewer**（只读）：留下结构化的评审意见；从不编辑。\n> - **docs**（可编辑）：仅更新 `README.md` 或 `docs\u002F`。\n\n**\\*政策** 提示：对于可编辑的代理，最好采用补丁输出的方式，这样更改可以通过您正常的 Git 工作流程落地。\\*\n\n\u003Cimg width=\"700\" height=\"173\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_598513197c9a.png\" \u002F>\n\n_图注：仅为代理分配其真正需要的工具（例如，咨询权限 vs 编辑权限）。_\n\n\u003Ch3 id=\"example-prompts\">示例提示词\u003C\u002Fh3>\n\n> 提示词应简短、可测试且针对特定仓库。请将其提交到 `agents\u002F` 目录中：\n\n\u003Cimg width=\"700\" height=\"217\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_7571416e8ae3.png\" \u002F>\n\n_图注：一个用于“测试覆盖率分析”代理的示例提示词。_\n\n**tester.prompt.md（样本）**\n\n```\n角色：为我描述的具体场景编写一条专注的失败测试用例。\n范围：仅在 tests\u002F 目录下创建或修改测试文件，不得更改 src\u002F。\n输出：简短的理由说明 + 统一的差异或补丁。\n如果场景不明确，请提出一个明确的问题。\n```\n\n\u003Ch3 id=\"expected-output\">预期输出\u003C\u002Fh3>\n\n> 您的测试代理应生成一个小的差异或补丁，以及一段简短的理由说明：\n\n\u003Cimg width=\"700\" height=\"273\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_5c3365187106.png\" \u002F>\n\n_图注：来自“测试覆盖率分析”代理的示例回复。_\n\n\u003Ch3 id=\"subagent-frontmatter\">子代理 Frontmatter 字段\u003C\u002Fh3>\n\n子代理文件使用 YAML frontmatter 进行配置：\n\n```markdown\n---\nname: code-reviewer\ndescription: 审查代码的质量和最佳实践\ntools: Read, Glob, Grep\ndisallowedTools: Write, Edit\nmodel: sonnet\npermissionMode: default\nskills:\n  - api-conventions\n---\n\n你是一名代码审查员。请分析代码并提供反馈。\n```\n\n| 字段             | 必填 | 描述                                                         |\n| :---------------- | :------- | :------------------------------------------------------------------ |\n| `name`            | 是      | 唯一标识符（小写，连字符）                              |\n| `description`     | 是      | 当 Claude 应该将任务委派给此子代理时                        |\n| `tools`           | 否       | 子代理可以使用的工具（若未指定，则继承所有工具）                |\n| `disallowedTools` | 否       | 禁止使用的工具，从继承或指定的列表中移除                          |\n| `model`           | 否       | 模型：`sonnet`、`opus`、`haiku` 或 `inherit`（默认：sonnet）    |\n| `permissionMode`  | 否       | `default`、`acceptEdits`、`dontAsk`、`bypassPermissions` 或 `plan` |\n| `skills`          | 否       | 预加载到子代理上下文中的技能                       |\n| `hooks`           | 否       | 作用于该子代理的生命周期钩子                             |\n| `memory`          | 否       | 持久化内存范围：`user`、`project` 或 `local`              |\n| `isolation`       | 否       | 设置为 `worktree` 可以让代理在隔离的 Git 工作树中运行      |\n| `background`      | 否       | 设置为 `true` 可以让代理作为后台任务运行                 |\n\n\u003Ch3 id=\"why-this-shift-matters\">为什么这一转变很重要\u003C\u002Fh3>\n\n**运营优势**\n\n> - **减少上下文切换：** 你只需保持一种思维模式；其余工作由代理完成。\n> - **更干净的 PR：** 精准的提示 + 有限的工具 → 更小、更易审查的差异。\n> - **更少的回归问题：** 测试员\u002F审查员代理会在合并前发现漏洞。\n> - **可重复性：** 提示和策略存储在仓库中，并随分支一起传播。\n\n**安全与治理**\n\n> - 限制按路径的写入权限（例如，`src\u002F`、`tests\u002F`、`docs\u002F`）。\n> - 对高风险区域优先采用只读分析。\n> - 将助手输出记录为补丁并提交，以提高可审计性。\n\n\u003Ch3 id=\"a-mindset-shift\">思维方式的转变\u003C\u002Fh3>\n\n**应该做**\n\n> - 将代理视为具有明确职责的团队成员。\n> - 先从只读开始；最后再授予写入权限。\n> - 将提示保存在版本控制系统中，并通过 PR 不断迭代。\n\n**不要做**\n\n> - 不要要求一个代理在一轮中同时完成计划、编码和测试。\n> - 不要给予全面的写入权限。\n> - 如果你只要求一个测试，就不要接受包含多份文件的差异。\n\n---\n\n\u003Ch2 id=\"agent-teams\">代理团队（研究预览）\u003C\u002Fh2>\n\n> [!注意]\n> **代理团队是一项实验性功能，允许多个 Claude 实例在共享代码库上自主并行工作。**\n\n**启用代理团队：**\n\n```bash\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\n```\n\n**关键概念：**\n\n- 多个 Claude 实例在同一代码库上并行运行\n- 每个代理可以专注于不同的任务（调试、文档编写、测试等）\n- 代理之间通过基于 Git 的同步机制进行沟通\n- 支持自主、长期的开发工作流\n\n**案例研究：由代理团队构建的 C 编译器**\n\nAnthropic 的研究团队通过指派 16 个并行的 Claude 实例从零开始构建 C 编译器，展示了代理团队的能力。主要成果如下：\n\n| 指标              | 数值                                  |\n| :------------------ | :------------------------------------- |\n| **Claude 会话数** | ~2,000                                 |\n| **API 费用**        | ~$20,000                               |\n| **代码行数**   | 100,000                                |\n| **能力**      | 在 x86、ARM 和 RISC-V 架构上编译 Linux 6.9 |\n| **测试通过率**  | 在 GCC 困难测试集中达到 99%          |\n\n**关于代理团队的经验教训：**\n\n1. **编写高质量的测试** - 任务验证者必须几乎完美\n2. **面向并行性设计** - 代理应能独立工作，互不阻塞\n3. **专业化分工** - 将代理分配到特定角色（代码质量、文档编写、性能优化等）\n4. **维护上下文文件** - 及时更新 README 和进度文件，以便代理快速定位\n\n> 阅读完整案例：[用并行 Claude 构建 C 编译器](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fbuilding-c-compiler)\n\n---\n\n\u003Ch2 id=\"skills\">技能（自定义斜杠命令）\u003C\u002Fh2>\n\n> [!注意]\n> **技能扩展了 Claude 的功能。创建一个包含说明的 `SKILL.md` 文件，Claude 会将其加入自己的工具箱。Claude 会在适当的时候使用这些技能，或者你可以直接通过 `\u002F技能名` 调用它们。**\n\n\u003Ch3 id=\"skill-locations\">技能的位置\u003C\u002Fh3>\n\n| 位置                                 | 范围    | 描述                                   |\n| :--------------------------------------- | :------- | :-------------------------------------------- |\n| `~\u002F.claude\u002Fskills\u002F\u003C技能名>\u002FSKILL.md` | 个人 | 适用于所有项目                             |\n| `.claude\u002Fskills\u002F\u003C技能名>\u002FSKILL.md`   | 项目  | 仅限当前项目（需提交到版本控制）         |\n| `\u003C插件>\u002Fskills\u002F\u003C技能名>\u002FSKILL.md`  | 插件   | 仅在插件启用时有效                       |\n\n> 项目级别的技能会覆盖同名的个人技能。位于 `.claude\u002Fcommands\u002F` 的文件仍然有效，并支持相同的 frontmatter。\n\n\u003Ch3 id=\"create-skill\">创建技能\u003C\u002Fh3>\n\n```bash\n\n\n# 创建技能目录\nmkdir -p ~\u002F.claude\u002Fskills\u002Fexplain-code\n```\n\n创建 `~\u002F.claude\u002Fskills\u002Fexplain-code\u002FSKILL.md`：\n\n```markdown\n---\nname: explain-code\ndescription: 用可视化图表和类比解释代码。用于解释代码的工作原理。\n---\n\n解释代码时，务必包括以下内容：\n\n1. **从类比入手**：将代码与日常生活中的事物进行对比\n2. **绘制图表**：使用 ASCII 艺术展示流程、结构或关系\n3. **逐行解释代码**：一步一步说明代码的执行过程\n4. **指出常见陷阱**：有哪些常见的错误或误解？\n```\n\n**使用该技能：**\n\n```bash\n# 让 Claude 自动调用\n这段代码是如何工作的？\n\n# 或直接调用\n\u002Fexplain-code src\u002Fauth\u002Flogin.ts\n```\n\n\u003Ch3 id=\"skill-frontmatter\">技能 Frontmatter 字段\u003C\u002Fh3>\n\n| 字段                      | 必填    | 描述                                                 |\n| :------------------------- | :---------- | :---------------------------------------------------------- |\n| `name`                     | 否          | 技能的显示名称（如未填写则使用目录名）                 |\n| `description`              | 推荐      | 该技能的功能及适用场景                                 |\n| `argument-hint`            | 否          | 自动补全时显示的提示信息（例如 `[filename]`）         |\n| `disable-model-invocation` | 否          | 设置为 `true` 可阻止 Claude 自动调用                  |\n| `user-invocable`           | 否          | 设置为 `false` 可从 `\u002F` 菜单中隐藏                   |\n| `allowed-tools`            | 否          | Claude 在无需请求权限的情况下可使用的工具             |\n| `model`                    | 否          | 当此技能激活时使用的模型                             |\n| `context`                  | 否          | 设置为 `fork` 可在分叉子代理上下文中运行               |\n| `agent`                    | 否          | 当设置 `context: fork` 时使用的子代理                 |\n| `hooks`                    | 否          | 作用于该技能生命周期的钩子                           |\n\n\u003Ch3 id=\"skill-arguments\">向技能传递参数\u003C\u002Fh3>\n\n使用 `$ARGUMENTS` 占位符接收参数：\n\n```markdown\n---\nname: fix-issue\ndescription: 修复 GitHub 问题\ndisable-model-invocation: true\n---\n\n按照我们的编码规范修复 GitHub 问题 $ARGUMENTS。\n\n1. 阅读问题描述\n2. 实现修复\n3. 编写测试\n4. 创建提交\n```\n\n**使用方法：** `\u002Ffix-issue 123`\n\n\u003Ch3 id=\"skill-dynamic-context\">注入动态上下文\u003C\u002Fh3>\n\n使用 `` !`command` `` 语法在技能内容发送给 Claude 之前运行 Shell 命令：\n\n```markdown\n---\nname: pr-summary\ndescription: 总结拉取请求中的更改\ncontext: fork\nagent: Explore\n---\n\n## 拉取请求上下文\n\n- PR 差异：!`gh pr diff`\n- PR 评论：!`gh pr view --comments`\n- 更改文件：!`gh pr diff --name-only`\n\n## 你的任务\n\n总结这个拉取请求...\n```\n\n\u003Ch3 id=\"skill-subagent\">在子代理中运行技能\u003C\u002Fh3>\n\n添加 `context: fork` 可使技能在隔离环境中运行：\n\n```markdown\n---\nname: deep-research\ndescription: 深入研究某个主题\ncontext: fork\nagent: Explore\n---\n\n深入研究 $ARGUMENTS：\n\n1. 使用 Glob 和 Grep 查找相关文件\n2. 阅读并分析代码\n3. 总结发现，并附上具体的文件引用\n```\n\n> `agent` 字段可以是 `Explore`、`Plan`、`general-purpose`，或来自 `.claude\u002Fagents\u002F` 的任何自定义子代理。\n\n---\n\n\u003Ch2 id=\"plugin-system\">插件系统\u003C\u002Fh2>\n\n> [!Note]\n> **插件通过自定义命令、技能、代理、钩子以及 MCP 服务器扩展 Claude Code。插件可以从本地目录、Git 仓库或 npm 注册表加载。**\n\n**关键命令：**\n\n```bash\n# 从 Git 仓库安装插件\n\u002Fplugins install https:\u002F\u002Fgithub.com\u002Forg\u002Fclaude-plugin-example\n\n# 从 npm 注册表安装\n\u002Fplugins install @org\u002Fclaude-code-plugin\n\n# 列出已安装的插件\n\u002Fplugins list\n\n# 启用或禁用插件\n\u002Fplugins enable \u003Cplugin-name>\n\u002Fplugins disable \u003Cplugin-name>\n\n# 验证插件结构\n\u002Fplugins validate .\u002Fmy-plugin\n\n# 浏览插件市场（社区插件）\n\u002Fplugins marketplace\n```\n\n**插件结构：**\n\n```\nmy-plugin\u002F\n├── plugin.json          # 插件清单（名称、版本、描述）\n├── agents\u002F              # 自定义代理 (*.md frontmatter 文件)\n├── skills\u002F              # 自定义技能 (SKILL.md 文件)\n├── hooks\u002F               # 钩子脚本\n├── commands\u002F            # 自定义斜杠命令\n└── mcp-servers\u002F         # MCP 服务器配置\n```\n\n**插件作用域：**\n\n| 位置              | 作用域        | 备注                     |\n| :-------------------- | :----------- | :------------------------ |\n| `--plugin-dir .\u002Fpath` | 仅会话期间 | CLI 标志，不会持久化   |\n| `.claude\u002Fplugins\u002F`    | 项目级别      | 随仓库一起提交         |\n| `~\u002F.claude\u002Fplugins\u002F`  | 用户全局      | 在所有项目中可用       |\n\n**插件清单 (`plugin.json`)：**\n\n```json\n{\n  \"name\": \"my-plugin\",\n  \"version\": \"1.0.0\",\n  \"description\": \"一个 Claude Code 插件\",\n  \"agents\": [\"agents\u002F\"],\n  \"skills\": [\"skills\u002F\"],\n  \"hooks\": \"hooks\u002Fhooks.json\",\n  \"mcpServers\": \"mcp-servers\u002Fservers.json\"\n}\n```\n\n> 插件默认自动更新。设置 `FORCE_AUTOUPDATE_PLUGINS=1` 可强制更新，即使主更新程序被禁用；也可通过 `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` 覆盖慢速仓库的更新。\n\n---\n\n\u003Ch2 id=\"worktree-isolation\">工作树隔离（v2.1.49+）\u003C\u002Fh2>\n\n> [!Note]\n> **`--worktree` (`-w`) 标志可在隔离的 Git 工作树中启动 Claude，使其能够在独立分支中进行更改，而不会影响您的工作目录。**\n\n**使用方法：**\n\n```bash\n# 在隔离的工作树中启动 Claude\nclaude -w \"implement the new feature\"\n\n# Claude 将执行以下操作：\n# 1. 从您当前分支创建一个临时 Git 工作树\n# 2. 在该隔离的工作树中运行\n# 3. 提交更改，并可选择创建拉取请求\n# 4. 完成后清理工作树\n```\n\n**代理级别的工作树隔离：**\n\n```markdown\n---\nname: background-coder\ndescription: 在隔离环境中实现功能\nisolation: worktree\nbackground: true\n---\n\n在此隔离的工作树中实现请求的功能。\n```\n\n> 工作树隔离与 `background: true` 结合使用时尤为强大，可支持多代理同时在不同功能上并行开发的工作流。\n\n---\n\n\u003Ch2 id=\"native-installer\">原生安装程序（v2.1.15+）\u003C\u002Fh2>\n\n> [!Note]\n> **Claude Code 现提供原生二进制安装程序，作为 npm 全局安装的替代方案。原生安装程序启动更快、可自动更新，且无需在 PATH 中配置 Node.js。**\n\n```bash\n# 启动原生安装程序（交互式）\nclaude install\n\n# 从 npm 全局安装迁移到原生安装程序\nclaude migrate-installer\n\n# 自 v2.1.41 起，Windows ARM64 已获得原生支持\n```\n\n> npm 安装方式（`npm install -g @anthropic-ai\u002Fclaude-code`）仍然有效。虽然自 v2.1.15 起已开始逐步淘汰基于 npm 的安装方式，但两种方法目前仍可并存。\n\n---\n\n\u003Ch2 id=\"claude-auth\">认证 CLI（v2.1.41+）\u003C\u002Fh2>\n\n> [!Note]\n> **无需进入 REPL，即可直接通过 CLI 管理认证。**\n\n```bash\n# 登录 Anthropic 账户\nclaude auth login\n\n# 检查当前认证状态\nclaude auth status\n\n# 注销\nclaude auth logout\n```\n\n---\n\n\u003Ch2 id=\"claude-agents-cli\">代理管理 CLI（v2.1.50+）\u003C\u002Fh2>\n\n> [!Note]\n> **可通过命令行列出并检查所有已配置的代理。**\n\n```bash\n# 列出所有代理\nclaude agents list\n\n# 查看特定代理的详细信息\nclaude agent inspect \u003Cagent-name>\n```\n\n> 此外，还可以通过 CLI 启动、停止或重启代理，从而实现更高效的管理流程。\n\n# 列出所有代理（项目、用户、插件、CLI 定义）\nclaude agents\n```\n\n---\n\n\u003Ch2 id=\"remote-control\">远程控制（v2.1.51+）\u003C\u002Fh2>\n\n> [!注意]\n> **`claude remote-control` 子命令允许外部工具和构建系统以编程方式驱动 Claude Code。**\n\n```bash\n# 以远程控制模式启动 Claude\nclaude remote-control\n```\n\n这对于希望通过其 SDK 接口与 Claude Code 交互的 IDE 扩展、CI\u002FCD 流水线或自定义编排工具非常有用。\n\n---\n\n\u003Ch2 id=\"managed-settings\">托管设置（v2.1.51+）\u003C\u002Fh2>\n\n> [!注意]\n> **企业管理员可以通过 macOS 的 plist 或 Windows 的注册表推送托管设置，从而实现组织范围内的配置控制。**\n\n**macOS（plist）：**\n\n可通过 MDM 配置文件将设置部署到 `\u002FLibrary\u002FManaged Preferences\u002Fcom.anthropic.claude-code.plist`。\n\n**Windows（注册表）：**\n\n可通过组策略将设置部署到 `HKLM\\SOFTWARE\\Policies\\Anthropic\\ClaudeCode`。\n\n> 托管设置优先于用户\u002F项目设置，且不能被单个用户覆盖。\n\n---\n\n\u003Ch2 id=\"model-updates\">模型更新\u003C\u002Fh2>\n\n### Claude Sonnet 4.6（2026年2月17日）\n\n> [!注意]\n> **Claude Sonnet 4.6 在 Sonnet 定价下实现了前沿级别的性能（每百万 tokens 3美元\u002F15美元），并拥有 100 万 tokens 的上下文窗口。**\n\n**主要亮点：**\n\n- **在编码、推理和智能体规划任务上接近 Opus 级别性能**\n- **100 万 tokens 上下文窗口**（此前仅在 Max 计划的 Sonnet 4.5 中可用）\n- **改进的编码基准测试**：在 SWE-bench、智能体式编码和多文件重构方面有显著提升\n- **更好的长上下文推理能力**：在“大海捞针”和长文档任务中的准确性有所提高\n- **增强的计算机使用能力**：更可靠的浏览器自动化和 GUI 交互\n- **与 Sonnet 4.5 相同的价格**：每百万 tokens 输入 3 美元 \u002F 输出 15 美元\n\n**在 Claude Code 中的使用方法：**\n\n```bash\n# 设置为默认模型\nclaude --model sonnet\n\n# 或者固定使用特定版本\nclaude --model claude-sonnet-4-6-20260217\n\n# 在设置中配置\nclaude config set model \"claude-sonnet-4-6-20260217\"\n```\n\n> 具有 1M 上下文的 Sonnet 4.5 已从 Max 计划中移除，取而代之的是 Sonnet 4.6。Claude Opus 4.6（在 v2.1.32 中发布）仍然适用于最苛刻的任务。\n\n---\n\n\u003Ch2 id=\"insights\">Claude Code Insights\u003C\u002Fh2>\n\n> [!注意]\n> **`\u002Finsights` 命令会生成一份交互式 HTML 报告，分析您过去 30 天的编码习惯。**\n\n**运行 Insights：**\n\n```bash\n# 在 Claude Code 终端中\n\u002Finsights\n\n# 打开生成的报告\nstart ~\u002F.claude\u002Fusage-data\u002Freport.html     # Windows\nopen ~\u002F.claude\u002Fusage-data\u002Freport.html      # Mac\nxdg-open ~\u002F.claude\u002Fusage-data\u002Freport.html  # Linux\n```\n\n**工作原理：**\n\n1. **会话收集** - 从 `~\u002F.claude\u002Fprojects\u002F` 中提取会话日志，过滤掉智能体子会话和短会话\n2. **元数据提取** - 提取持续时间、token 使用量、使用的工具、检测到的语言以及 Git 活动\n3. **特征提取** - 使用 Haiku 模型分析对话记录，识别目标、满意度信号和摩擦点\n4. **报告生成** - 创建包含个性化建议的交互式 HTML 报告\n\n**报告各部分：**\n\n| 部分               | 描述                                                 |\n| :-------------------- | :---------------------------------------------------------- |\n| **哪些方面有效**    | 您的优势和成功模式                      |\n| **哪些方面受阻**  | Claude 在哪些地方遇到困难，或者您在哪里造成了摩擦         |\n| **摩擦分析**       | 对问题区域的细分及具体示例           |\n| **统计仪表板**   | 工具使用情况、语言分布、编码时间分布    |\n| **快速改进点**        | 可直接复制粘贴的 CLAUDE.md 改进建议           |\n| **值得尝试的功能**   | 个性化推荐（技能、钩子、无头模式） |\n\n> 所有处理都在本地使用 Anthropic API 进行。会话数据始终保存在您的设备上。\n\n---\n\n\u003Ch2 id=\"mcp-integration\">MCP 集成\u003C\u002Fh2>\n\n\u003Ch3 id=\"understanding-mcp-model-context-protocol\">理解 MCP（模型上下文协议）\u003C\u002Fh3>\n\n#### 什么是 MCP？\n\n> MCP 通过连接外部服务、数据库、API 和工具（文件系统、Puppeteer、GitHub、Context7 等）来扩展 Claude 的功能。\n\n###### **MCP 架构：**\n\n```\nClaude Code ←→ MCP 协议 ←→ MCP 服务器 ←→ 外部服务\n```\n\n\u003Ch3 id=\"claudeai-mcp-connectors\">claude.ai 的 MCP 连接器\u003C\u002Fh3>\n\nClaude Code 可以使用您 claude.ai 账户中配置的 MCP 服务器，从而将云端托管的工具引入您的 CLI 工作流。\n\n```bash\n# 默认启用 — 如需禁用：\nexport ENABLE_CLAUDEAI_MCP_SERVERS=false\n```\n\n这使您能够直接从命令行访问 claude.ai 中提供的相同 MCP 工具集成，而无需进行本地 MCP 服务器配置。\n\n\u003Ch3 id=\"mcp-setup--configuration\">MCP 设置与配置\u003C\u002Fh3>\n\n###### 基本 MCP 命令\n\n```bash\nclaude mcp                   # 交互式 MCP 配置\nclaude mcp list              # 列出已配置的服务器\nclaude mcp add \u003Cname> \u003Ccmd>  # 添加新服务器\nclaude mcp remove \u003Cname>     # 移除服务器\n```\n\n###### MCP 配置文件位置\n\n```bash\n~\u002F.claude.json      # 全局文件\n`.mcp.json`         # 项目范围内的服务器存储在项目根目录下的文件中\n```\n\n## 快速入门\n\n> **如果您赶时间，这是最快的方法：**\n\n```bash\n# 添加文件系统访问权限（最常用）\nclaude mcp add filesystem -s user -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments ~\u002FDesktop\n\n# 验证是否成功\nclaude mcp list\n```\n\n> **如果一切正常，您将看到如下响应：**\n> \u003Cimg width=\"868\" height=\"192\" alt=\"image\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_readme_76f4857af07e.png\" \u002F>\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n## 其他方法：\n\n\u003Ctable>\u003Ctd>\n\n### 1. 命令行添加\n\n> **Claude Code 提供了简单的命令行工具来添加 MCP 服务器：**\n\n```bash\n# 基本语法\nclaude mcp add \u003C名称> \u003C命令> [参数...]\n\n# 实际示例：添加本地文件系统访问权限\nclaude mcp add my-filesystem -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n\n# 使用环境变量的示例\nclaude mcp add api-server -e API_KEY=your-key-here -- \u002Fpath\u002Fto\u002Fserver\n```\n\n**OAuth 用于 MCP 服务器：**\n\n```bash\n# 添加带有预配置 OAuth 凭证的 MCP 服务器\nclaude mcp add \u003C名称> --client-id \u003Cid> --client-secret \u003Csecret> -- \u003C命令>\n```\n\n> 一些 MCP 服务器（例如 Slack）不支持动态客户端注册，需要预先配置 OAuth 凭证。\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n### 2. 直接编辑配置文件\n\n> 很多开发者觉得 CLI 向导过于繁琐，尤其是在出错时需要重新启动的情况下。\n>\n> 直接编辑配置文件则更为高效：\n\n**1. 查找配置文件位置：**\n\n- macOS\u002FLinux：`~\u002F.claude.json`\n- Windows：`%USERPROFILE%\\.claude.json`\n\n**2. 编辑配置文件：**\n\n```json\n{\n  \"mcpServers\": {\n    \"filesystem\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\n        \"-y\",\n        \"@modelcontextprotocol\u002Fserver-filesystem\",\n        \"\u002FUsers\u002Fusername\u002FDocuments\"\n      ],\n      \"env\": {}\n    },\n    \"github\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-github\"],\n      \"env\": {\n        \"GITHUB_TOKEN\": \"your-github-token\"\n      }\n    }\n  }\n}\n```\n\n**3. 重启 Claude Code 以使更改生效**\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\u003Ctable>\u003Ctd>\n\n### 3. 项目级配置（推荐用于团队协作）\n\n> 如果希望团队成员都使用相同的 MCP 配置：\n\n```bash\n# 添加项目级 MCP 服务器\nclaude mcp add shared-tools -s project -- npx -y @your-team\u002Fmcp-tools\n```\n\n**这将在项目根目录下创建一个 `.mcp.json` 文件：**\n\n```json\n{\n  \"mcpServers\": {\n    \"shared-tools\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@your-team\u002Fmcp-tools\"],\n      \"env\": {}\n    }\n  }\n}\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n## MCP 服务器作用域详解\n\n理解作用域对于避免“未找到服务器”错误至关重要：\n\n### 1. 本地作用域（默认）\n\n- 仅在当前目录中可用\n- 配置存储在 `~\u002F.claude.json` 的 projects 部分\n- 适用场景：个人项目专用工具\n\n### 2. 用户作用域（全局）\n\n- 在所有项目中均可使用\n- 使用 `-s user` 标志添加\n- 适用场景：文件系统、数据库客户端等常用工具\n\n### 3. 项目作用域（团队共享）\n\n- 通过 `.mcp.json` 文件共享\n- 使用 `-s project` 标志添加\n- 适用场景：团队共享的项目专用工具\n\n## 实用 MCP 服务器推荐\n\n> **以下是值得安装的最有价值的 MCP 服务器列表：**\n\n### 1. 文件系统访问\n\n```bash\nclaude mcp add filesystem -s user -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments ~\u002FProjects ~\u002FDesktop\n```\n\n用途：让 Claude 直接读写文件、修改代码。\n\n### 2. GitHub 集成\n\n```bash\nclaude mcp add github -s user -e GITHUB_TOKEN=your-token -- npx -y @modelcontextprotocol\u002Fserver-github\n```\n\n用途：管理问题、PR 和代码评审。\n\n### 3. 网页浏览器控制\n\n```bash\nclaude mcp add puppeteer -s user -- npx -y @modelcontextprotocol\u002Fserver-puppeteer\n```\n\n用途：自动化网页操作、爬取和测试。\n\n### 4. 数据库连接（PostgreSQL）\n\n```bash\nclaude mcp add postgres -s user -e DATABASE_URL=your-db-url -- npx -y @modelcontextprotocol\u002Fserver-postgres\n```\n\n用途：直接查询和操作数据库。\n\n### 5. Fetch 工具（API 调用）\n\n```bash\nclaude mcp add fetch -s user -- npx -y @kazuph\u002Fmcp-fetch\n```\n\n用途：调用各种 REST API。\n\n### 6. 搜索引擎\n\n```bash\nclaude mcp add search -s user -e BRAVE_API_KEY=your-key -- npx -y @modelcontextprotocol\u002Fserver-brave-search\n```\n\n用途：搜索最新信息。\n\n### 7. Slack 集成\n\n```bash\nclaude mcp add slack -s user -e SLACK_TOKEN=your-token -- npx -y @modelcontextprotocol\u002Fserver-slack\n```\n\n用途：发送消息、管理频道。\n\n### 8. 时间管理\n\n```bash\nclaude mcp add time -s user -- npx -y @modelcontextprotocol\u002Fserver-time\n```\n\n用途：时区转换、日期计算。\n\n### 9. 内存存储\n\n```bash\nclaude mcp add memory -s user -- npx -y @modelcontextprotocol\u002Fserver-memory\n```\n\n用途：跨对话保存信息。\n\n### 10. 顺序思维（思维链）\n\n```bash\nclaude mcp add thinking -s user -- npx -y @modelcontextprotocol\u002Fserver-sequential-thinking\n```\n\n用途：针对复杂问题进行逐步思考。\n\n## 常见错误及解决方案\n\n### 错误 1：工具名称验证失败\n\n```\nAPI Error 400: \"tools.11.custom.name: 字符串应匹配模式 '^[a-zA-Z0-9_-]{1,64}$'\"\n```\n\n**解决方案**：\n\n- 确保服务器名称仅包含字母、数字、下划线和短横线。\n- 名称长度不得超过 64 个字符。\n- 不要使用特殊字符或空格。\n\n### 错误 2：未找到 MCP 服务器\n\n```\nMCP 服务器 'my-server' 未找到\n```\n\n**解决方案**：\n\n1. 检查作用域设置是否正确。\n2. 运行 `claude mcp list` 确认服务器已添加。\n3. 确保您位于正确的目录中（对于本地作用域）。\n4. 重启 Claude Code。\n\n### 错误 3：协议版本错误\n\n```\n\"protocolVersion\": \"必需\"\n```\n\n**解决方案**：这是 Claude Code 中的一个已知 bug，临时解决方法如下：\n\n1. 使用包装脚本。\n2. 确保 MCP 服务器返回正确的协议版本。\n3. 更新到最新版本的 Claude Code。\n\n### 错误 4：Windows 路径问题\n\n```\n错误：无法找到模块 'C:UsersusernameDocuments'\n```\n\n**解决方案**：Windows 路径需要使用正斜杠或双反斜杠：\n\n```bash\n# 错误\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem C:\\Users\\username\\Documents\n\n# 正确\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem C:\u002FUsers\u002Fusername\u002FDocuments\n# 或\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem C:\\\\Users\\\\username\\\\Documents\n```\n\n### 错误 5：权限问题\n\n```\n权限被拒绝\n```\n\n**解决方案**：\n\n1. macOS\u002FLinux：使用 `sudo`（不推荐）或修改文件权限。\n2. Windows：以管理员身份运行。\n3. 最佳方法：将 MCP 服务器安装在用户目录中。\n\n## 调试技巧\n\n遇到问题时，以下调试方法可以帮助您快速定位问题：\n\n### 1. 启用调试模式\n\n```bash\nclaude --debug\n```\n\n### 2. 查看 MCP 状态\n\n在 Claude Code 中输入：\n\n```\n\u002Fmcp\n```\n\n### 3. 查看日志文件\n\n**macOS\u002FLinux：**\n\n```bash\ntail -f ~\u002FLibrary\u002FLogs\u002FClaude\u002Fmcp*.log\n```\n\n**Windows：**\n\n```cmd\ntype \"%APPDATA%\\Claude\\logs\\mcp*.log\"\n```\n\n### 4. 手动测试服务器\n\n```bash\n# 直接运行服务器命令，查看是否有输出\nnpx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n```\n\n## 国际用户特别提示\n\n### 1. 非英文路径问题\n\n避免在路径中使用非英文字符：\n\n```bash\n# 避免\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002F文档\n\n# 推荐\nclaude mcp add fs -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n```\n\n### 2. 代理配置\n\n如果您正在使用代理：\n\n```bash\n# 设置 npm 代理\nnpm config set proxy http:\u002F\u002Fyour-proxy:port\nnpm config set https-proxy http:\u002F\u002Fyour-proxy:port\n\n# 然后添加 MCP 服务器\nclaude mcp add ...\n```\n\n### 3. 镜像源\n\n使用镜像源加速下载：\n\n```bash\n# 临时使用\nclaude mcp add fs -- npx -y --registry=https:\u002F\u002Fregistry.npmjs.org @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments\n\n# 或永久设置\nnpm config set registry https:\u002F\u002Fregistry.npmjs.org\n```\n\n## 最佳实践建议\n\n1. **按需添加**：不要一次性添加过多的 MCP 服务器，这会影响性能。\n2. **定期清理**：使用 `claude mcp remove \u003Cname>` 删除未使用的服务器。\n3. **安全第一**：仅添加受信任的 MCP 服务器，尤其是需要网络访问权限的服务器。\n4. **备份配置**：定期备份 `~\u002F.claude.json` 文件。\n5. **团队协作**：使用项目范围共享常用配置。\n\n## 高级技巧\n\n### 1. 创建自定义 MCP 服务器\n\n如果现有的 MCP 服务器无法满足您的需求，您可以创建自己的：\n\n```javascript\n\u002F\u002F my-mcp-server.js\nimport { Server } from \"@modelcontextprotocol\u002Fsdk\";\n\nconst server = new Server({\n  name: \"my-custom-server\",\n  version: \"1.0.0\",\n});\n\nserver.setRequestHandler(\"tools\u002Flist\", async () => {\n  return {\n    tools: [\n      {\n        name: \"my_custom_tool\",\n        description: \"自定义工具\",\n        inputSchema: {\n          type: \"object\",\n          properties: {\n            input: { type: \"string\" },\n          },\n        },\n      },\n    ],\n  };\n});\n\nserver.start();\n```\n\n### 2. 批量配置脚本\n\n创建一个脚本来一次性配置所有常用的 MCP 服务器：\n\n```bash\n#!\u002Fbin\u002Fbash\n# setup-mcp.sh\n\necho \"配置常用 MCP 服务器...\"\n\n# 文件系统\nclaude mcp add filesystem -s user -- npx -y @modelcontextprotocol\u002Fserver-filesystem ~\u002FDocuments ~\u002FProjects\n\n# GitHub\nread -p \"请输入 GitHub Token: \" github_token\nclaude mcp add github -s user -e GITHUB_TOKEN=$github_token -- npx -y @modelcontextprotocol\u002Fserver-github\n\n# 其他服务器...\n\necho \"MCP 服务器配置成功！\"\n```\n\n\u003Ch3 id=\"popular-mcp-servers\">流行的 MCP 服务器\u003C\u002Fh3>\n\n#### 开发工具\n\n```bash\n# npm install -g git-mcp-server\n\n# claude mcp add git \"git-mcp-server\"\n# claude mcp add github \"github-mcp-server --token $GITHUB_TOKEN\"\n```\n\n#### 数据库集成\n\n```bash\nnpm install -g postgres-mcp-server\nnpm install -g mysql-mcp-server\nnpm install -g sqlite-mcp-server\n\n# 设置示例可能如下：\n# export POSTGRES_URL=\"postgresql:\u002F\u002Fuser:password@localhost:5432\u002Fmydb\"\n# claude mcp add postgres \"postgres-mcp-server --url $POSTGRES_URL\"\n```\n\n#### MCP 工具权限\n\n```bash\n# 允许特定的 MCP 工具\nclaude --allowedTools \"mcp__git__commit,mcp__git__push\"\n\n# 允许来自特定服务器的所有工具\nclaude --allowedTools \"mcp__postgres__*\"\n\n# 结合内置工具\nclaude --allowedTools \"Edit,View,mcp__git__*\"\n```\n\n\u003Ch2 id=\"hooks-system\">钩子系统\u003C\u002Fh2>\n\n> 本页面提供在 Claude Code 中实现钩子的参考文档。\n\n> [!TIP]\n> 如需包含示例的快速入门指南，请参阅[开始使用 Claude Code 钩子](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fhooks-guide)。\n\n\u003Ch3 id=\"hooks-configuration\">配置\u003C\u002Fh3>\n\nClaude Code 的钩子在您的[设置文件](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fsettings)中进行配置：\n\n- `~\u002F.claude\u002Fsettings.json` - 用户设置\n- `.claude\u002Fsettings.json` - 项目设置\n- `.claude\u002Fsettings.local.json` - 本地项目设置（不提交）\n- 企业托管策略设置\n\n#### 结构\n\n钩子按匹配器组织，每个匹配器可以有多个钩子：\n\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"ToolPattern\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"your-command-here\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n#### HTTP 钩子（v2.1.63+）\n\n除了 shell 命令之外，钩子还可以将 JSON 发送到 URL 并接收 JSON 响应：\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"http\",\n            \"url\": \"https:\u002F\u002Fhooks.example.com\u002Fvalidate\",\n            \"timeout\": 10\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nHTTP 钩子会将与 `command` 钩子通过 stdin 接收的相同 JSON 负载作为 POST 请求体发送。响应 JSON 遵循相同的输出模式。这对于集中式策略执行或无需本地脚本的远程钩子执行非常有用。\n\n- **matcher**：用于匹配工具名称的模式，区分大小写（仅适用于 `PreToolUse` 和 `PostToolUse`）。\n  - 简单字符串精确匹配：`Write` 只匹配 Write 工具。\n  - 支持正则表达式：`Edit|Write` 或 `Notebook.*`。\n  - 使用 `*` 匹配所有工具。您也可以使用空字符串 (`\"\"`) 或留空 `matcher`。\n- **hooks**：当模式匹配时要执行的命令数组。\n  - `type`：`\"command\"`（shell 命令）或 `\"http\"`（POST JSON 到 URL，v2.1.63+）。\n  - `command`：要执行的 bash 命令（可使用 `$CLAUDE_PROJECT_DIR` 环境变量）。\n  - `timeout`：（可选）命令运行的时间限制，以秒为单位，超过该时间将取消该命令。\n\n对于像 `UserPromptSubmit`、`Notification`、`Stop` 和 `SubagentStop` 这样的事件，它们不使用匹配器，因此可以省略 matcher 字段：\n\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\u002Fpath\u002Fto\u002Fprompt-validator.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n#### 项目特定的钩子脚本\n\n您可以使用环境变量 `CLAUDE_PROJECT_DIR`（仅在 Claude Code 启动钩子命令时可用）来引用存储在项目中的脚本，从而确保无论 Claude 当前位于哪个目录，这些脚本都能正常工作：\n\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Write|Edit\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"$CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Fcheck-style.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n\u003Ch3 id=\"hook-events\">钩子事件\u003C\u002Fh3>\n\n#### PreToolUse\n\n在 Claude 创建工具参数之后、处理工具调用之前运行。\n\n**常见匹配器：**\n\n- `Task` - 子代理任务（参见[子代理文档](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fsub-agents)）\n- `Bash` - Shell 命令\n- `Glob` - 文件模式匹配\n- `Grep` - 内容搜索\n- `Read` - 文件读取\n- `Edit`、`MultiEdit` - 文件编辑\n- `Write` - 文件写入\n- `WebFetch`、`WebSearch` - 网络操作\n\n#### PostToolUse\n\n在工具成功完成之后立即运行。\n\n识别与 PreToolUse 相同的匹配器值。\n\n#### Notification\n\n在 Claude Code 发送通知时运行。通知会在以下情况下发送：\n\n1. Claude 需要您的许可才能使用某个工具。例如：“Claude 需要您的许可才能使用 Bash”。\n2. 提示输入已空闲至少 60 秒。“Claude 正在等待您的输入”。\n\n#### UserPromptSubmit\n\n在用户提交提示之前运行，即在 Claude 处理提示之前。这使您可以根据提示\u002F对话添加额外的上下文、验证提示或阻止某些类型的提示。\n\n#### Stop\n\n在主 Claude Code 代理完成响应后运行。如果停止是由用户中断引起的，则不会运行。\n\n#### SubagentStop\n\n在 Claude Code 子代理（Task 工具调用）完成响应后运行。\n\n#### TeammateIdle\n\n当代理队友进入空闲状态时触发（多代理工作流）。\n\n#### TaskCompleted\n\n在后台任务完成时触发（多智能体工作流）。\n\n#### ConfigChange\n\n当 Claude Code 配置文件发生变化时触发（例如设置、CLAUDE.md、`.mcp.json`）。可用于重新加载外部状态或在配置更改时触发副作用。\n\n#### WorktreeCreate\n\n当 Claude 创建一个新的 Git 工作树时触发（通过 `--worktree` \u002F `-w` 标志或代理定义中的 `isolation: worktree`）。可用于设置工作树特定的资源。\n\n#### WorktreeRemove\n\n当 Git 工作树在使用后被清理时触发。可用于销毁工作树特定的资源。\n\n#### Setup\n\n通过 `--init`、`--init-only` 或 `--maintenance` CLI 标志触发。可用于一次性项目设置任务、插件安装或维护脚本。\n\n#### PermissionRequest\n\n当 Claude 向用户显示权限提示时触发。可用于记录日志或自动化权限决策。\n\n#### PreCompact\n\n在 Claude Code 即将执行压缩操作之前运行。\n\n**匹配器：**\n\n- `manual` - 从 `\u002Fcompact` 调用\n- `auto` - 从自动压缩调用（由于上下文窗口已满）\n\n#### SessionStart\n\n当 Claude Code 开始新会话或恢复现有会话时运行（目前在后台会启动一个新会话）。可用于加载开发上下文，如现有问题或代码库的近期更改。\n\n**匹配器：**\n\n- `startup` - 从启动时调用\n- `resume` - 从 `--resume`、`--continue` 或 `\u002Fresume` 调用\n- `clear` - 从 `\u002Fclear` 调用\n\n\u003Ch3 id=\"hook-input\">钩子输入\u003C\u002Fh3>\n\n钩子通过标准输入接收包含会话信息和事件特定数据的 JSON 数据：\n\n```typescript\n{\n  \u002F\u002F 公共字段\n  session_id: string\n  transcript_path: string  \u002F\u002F 对话 JSON 的路径\n  cwd: string              \u002F\u002F 钩子调用时的当前工作目录\n\n  \u002F\u002F 事件特定字段\n  hook_event_name: string\n  ...\n}\n```\n\n#### PreToolUse 输入\n\n`tool_input` 的确切模式取决于工具。\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"PreToolUse\",\n  \"tool_name\": \"Write\",\n  \"tool_input\": {\n    \"file_path\": \"\u002Fpath\u002Fto\u002Ffile.txt\",\n    \"content\": \"file content\"\n  }\n}\n```\n\n#### PostToolUse 输入\n\n`tool_input` 和 `tool_response` 的确切模式取决于工具。\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"PostToolUse\",\n  \"tool_name\": \"Write\",\n  \"tool_input\": {\n    \"file_path\": \"\u002Fpath\u002Fto\u002Ffile.txt\",\n    \"content\": \"file content\"\n  },\n  \"tool_response\": {\n    \"filePath\": \"\u002Fpath\u002Fto\u002Ffile.txt\",\n    \"success\": true\n  }\n}\n```\n\n#### Notification 输入\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"Notification\",\n  \"message\": \"任务成功完成\"\n}\n```\n\n#### UserPromptSubmit 输入\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"\u002FUsers\u002F...\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"cwd\": \"\u002FUsers\u002F...\",\n  \"hook_event_name\": \"UserPromptSubmit\",\n  \"prompt\": \"编写一个计算阶乘的函数\"\n}\n```\n\n#### Stop 和 SubagentStop 输入\n\n`stop_hook_active` 在 Claude Code 已经因停止钩子而继续运行时为真。请检查此值或处理对话记录，以防止 Claude Code 无限运行。\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"~\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"hook_event_name\": \"Stop\",\n  \"stop_hook_active\": true,\n  \"last_assistant_message\": \"我已经完成了所有请求的更改。\"\n}\n```\n\n> `last_assistant_message` 字段（v2.1.47+）包含 Claude 在停止前生成的最终文本。可用于验证完整性或记录结果。\n\n#### PreCompact 输入\n\n对于 `manual`，`custom_instructions` 来自用户传递给 `\u002Fcompact` 的内容。对于 `auto`，`custom_instructions` 为空。\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"~\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"hook_event_name\": \"PreCompact\",\n  \"trigger\": \"manual\",\n  \"custom_instructions\": \"\"\n}\n```\n\n#### SessionStart 输入\n\n```json\n{\n  \"session_id\": \"abc123\",\n  \"transcript_path\": \"~\u002F.claude\u002Fprojects\u002F...\u002F00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl\",\n  \"hook_event_name\": \"SessionStart\",\n  \"source\": \"startup\"\n}\n```\n\n\u003Ch3 id=\"hook-output\">钩子输出\u003C\u002Fh3>\n\n钩子有两种方式可以将输出返回给 Claude Code。输出用于传达是否阻止以及应向 Claude 和用户显示的任何反馈。\n\n#### 简单：退出码\n\n钩子通过退出码、stdout 和 stderr 传达状态：\n\n- **退出码 0**：成功。`stdout` 会在转录模式下显示给用户（CTRL-R），但 `UserPromptSubmit` 和 `SessionStart` 除外，在这些情况下 `stdout` 会被添加到上下文中。\n- **退出码 2**：阻止性错误。`stderr` 会反馈给 Claude 自动处理。请参阅下方的每个钩子事件的行为。\n- **其他退出码**：非阻止性错误。`stderr` 会显示给用户，执行将继续。\n\n> [!WARNING]\n> 提醒：如果退出码为 0，Claude Code 不会看到 stdout，除了 `UserPromptSubmit` 钩子，该钩子的 stdout 会被注入为上下文。\n\n##### 退出码 2 行为\n\n| 钩子事件         | 行为                                                           |\n| ------------------ | ------------------------------------------------------------------ |\n| `PreToolUse`       | 阻止工具调用，向 Claude 显示 stderr                       |\n| `PostToolUse`      | 向 Claude 显示 stderr（工具已经运行）                          |\n| `Notification`     | 无，仅向用户显示 stderr                                     |\n| `UserPromptSubmit` | 阻止提示处理，清除提示，仅向用户显示 stderr                 |\n| `Stop`             | 阻止停止，向 Claude 显示 stderr                            |\n| `SubagentStop`     | 阻止停止，向 Claude 子代理显示 stderr                   |\n| `PreCompact`       | 无，仅向用户显示 stderr                                     |\n| `SessionStart`     | 无，仅向用户显示 stderr                                     |\n\n#### 高级：JSON 输出\n\n钩子可以在 `stdout` 中返回结构化 JSON，以实现更复杂的控制：\n\n##### 常见 JSON 字段\n\n所有类型的钩子都可以包含以下可选字段：\n\n```json\n{\n  \"continue\": true, \u002F\u002F Claude 是否应在钩子执行后继续（默认：是）\n  \"stopReason\": \"string\" \u002F\u002F 当 continue 为 false 时显示的消息\n  \"suppressOutput\": true, \u002F\u002F 隐藏转录模式下的 stdout（默认：否）\n}\n```\n\n如果 `continue` 为 false，Claude 将在钩子运行后停止处理。\n\n- 对于 `PreToolUse`，这与 `\"permissionDecision\": \"deny\"` 不同，后者仅阻止特定的工具调用，并向 Claude 提供自动反馈。\n- 对于 `PostToolUse`，这与 `\"decision\": \"block\"` 不同，后者会向 Claude 提供自动化反馈。\n- 对于 `UserPromptSubmit`，这会阻止提示被处理。\n- 对于 `Stop` 和 `SubagentStop`，这将优先于任何 `\"decision\": \"block\"` 的输出。\n- 在所有情况下，`\"continue\" = false` 都会优先于任何 `\"decision\": \"block\"` 的输出。\n\n`stopReason` 会伴随 `continue` 一起提供一个向用户展示、但不向 Claude 展示的原因。\n\n##### `PreToolUse` 决策控制\n\n`PreToolUse` 钩子可以控制工具调用是否继续。\n\n- `\"allow\"` 会绕过权限系统。`permissionDecisionReason` 会展示给用户，但不会展示给 Claude。（已弃用的 `\"approve\"` 值 + `reason` 具有相同的行为。）\n- `\"deny\"` 会阻止工具调用执行。`permissionDecisionReason` 会展示给 Claude。（`\"block\"` 值 + `reason` 具有相同的行为。）\n- `\"ask\"` 会在 UI 中请求用户确认工具调用。`permissionDecisionReason` 会展示给用户，但不会展示给 Claude。\n\n```json\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"PreToolUse\",\n    \"permissionDecision\": \"allow\" | \"deny\" | \"ask\",\n    \"permissionDecisionReason\": \"我的理由在这里（展示给用户）\"\n  },\n  \"decision\": \"approve\" | \"block\" | undefined, \u002F\u002F 已弃用，但仍支持\n  \"reason\": \"决策解释\" \u002F\u002F 已弃用，但仍支持\n}\n```\n\n##### `PostToolUse` 决策控制\n\n`PostToolUse` 钩子可以控制工具调用是否继续。\n\n- `\"block\"` 会自动向 Claude 发送 `reason`。\n- `undefined` 则不做任何操作。`reason` 会被忽略。\n\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"决策解释\"\n}\n```\n\n##### `UserPromptSubmit` 决策控制\n\n`UserPromptSubmit` 钩子可以控制用户提示是否被处理。\n\n- `\"block\"` 会阻止提示被处理。提交的提示将从上下文中清除。`reason` 会展示给用户，但不会添加到上下文中。\n- `undefined` 则允许提示正常进行。`reason` 会被忽略。\n- `\"hookSpecificOutput.additionalContext\"` 如果未被阻止，则会将字符串添加到上下文中。\n\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"决策解释\",\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"UserPromptSubmit\",\n    \"additionalContext\": \"我的附加上下文在这里\"\n  }\n}\n```\n\n##### `Stop`\u002F`SubagentStop` 决策控制\n\n`Stop` 和 `SubagentStop` 钩子可以控制 Claude 是否必须继续。\n\n- `\"block\"` 会阻止 Claude 停止。您必须填写 `reason`，以便 Claude 知道如何继续。\n- `undefined` 则允许 Claude 停止。`reason` 会被忽略。\n\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"当 Claude 被阻止停止时，必须提供此原因\"\n}\n```\n\n##### `SessionStart` 决策控制\n\n`SessionStart` 钩子允许您在会话开始时加载上下文。\n\n- `\"hookSpecificOutput.additionalContext\"` 会将字符串添加到上下文中。\n\n```json\n{\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"SessionStart\",\n    \"additionalContext\": \"我的附加上下文在这里\"\n  }\n}\n```\n\n##### 退出码示例：Bash 命令验证\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\nimport json\nimport re\nimport sys\n\n\n\n# 定义验证规则为 (正则表达式模式, 消息) 元组列表\nVALIDATION_RULES = [\n    (\n        r\"\\bgrep\\b(?!.*\\|)\",\n        \"请使用 'rg'（ripgrep）代替 'grep'，以获得更好的性能和功能\",\n    ),\n    (\n        r\"\\bfind\\s+\\S+\\s+-name\\b\",\n        \"请使用 'rg --files | rg pattern' 或 'rg --files -g pattern' 代替 'find -name'，以获得更好的性能\",\n    ),\n]\n\n\ndef validate_command(command: str) -> list[str]:\n    issues = []\n    for pattern, message in VALIDATION_RULES:\n        if re.search(pattern, command):\n            issues.append(message)\n    return issues\n\n\ntry:\n    input_data = json.load(sys.stdin)\nexcept json.JSONDecodeError as e:\n    print(f\"错误：无效的 JSON 输入：{e}\", file=sys.stderr)\n    sys.exit(1)\n\ntool_name = input_data.get(\"tool_name\", \"\")\ntool_input = input_data.get(\"tool_input\", {})\ncommand = tool_input.get(\"command\", \"\")\n\nif tool_name != \"Bash\" 或者命令为空：\n    sys.exit(1)\n\n# 验证命令\nissues = validate_command(command)\n\nif issues:\n    for message in issues:\n        print(f\"• {message}\", file=sys.stderr)\n    # 退出码 2 会阻止工具调用，并将 stderr 显示给 Claude\n    sys.exit(2)\n```\n\n##### JSON 输出示例：UserPromptSubmit 添加上下文和验证\n\n> [!注意]\n> 对于 `UserPromptSubmit` 钩子，您可以使用以下两种方法注入上下文：\n>\n> - 退出码 0 并通过 stdout：Claude 可以看到上下文（`UserPromptSubmit` 的特殊情况）\n> - JSON 输出：提供更多对行为的控制\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\nimport json\nimport sys\nimport re\nimport datetime\n\n# 从 stdin 加载输入\ntry:\n    input_data = json.load(sys.stdin)\nexcept json.JSONDecodeError as e:\n    print(f\"错误：无效的 JSON 输入：{e}\", file=sys.stderr)\n    sys.exit(1)\n\nprompt = input_data.get(\"prompt\", \"\")\n\n# 检查敏感模式\nsensitive_patterns = [\n    (r\"(?i)\\b(password|secret|key|token)\\s*[:=]\", \"提示包含潜在的机密信息\"),\n]\n\nfor pattern, message in sensitive_patterns:\n    if re.search(pattern, prompt):\n        # 使用 JSON 输出以特定理由阻止\n        output = {\n            \"decision\": \"block\",\n            \"reason\": f\"违反安全策略：{message}。请重新表述您的请求，避免包含敏感信息。\"\n        }\n        print(json.dumps(output))\n        sys.exit(0)\n\n# 将当前时间添加到上下文中\ncontext = f\"当前时间：{datetime.datetime.now()}\"\nprint(context)\n\n\"\"\"\n以下内容也是等价的：\nprint(json.dumps({\n  \"hookSpecificOutput\": {\n    \"hookEventName\": \"UserPromptSubmit\",\n    \"additionalContext\": context,\n  },\n}))\n\"\"\"\n\n# 允许提示在附加上下文的情况下继续\nsys.exit(0)\n```\n\n##### JSON 输出示例：PreToolUse 自动批准\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\nimport json\nimport sys\n\n# 从 stdin 加载输入\ntry：\n    input_data = json.load(sys.stdin)\nexcept json.JSONDecodeError as e：\n    print(f\"错误：无效的 JSON 输入：{e}\", file=sys.stderr)\n    sys.exit(1)\n\ntool_name = input_data.get(\"tool_name\", \"\")\ntool_input = input_data.get(\"tool_input\", {})\n\n# 示例：自动批准文档文件的读取操作\nif tool_name == \"Read\"：\n    file_path = tool_input.get(\"file_path\", \"\")\n    if file_path.endswith((\".md\", \".mdx\", \".txt\", \".json\"))：\n        # 使用 JSON 输出自动批准工具调用\n        output = {\n            \"decision\": \"approve\",\n            \"reason\": \"文档文件已自动批准\",\n            \"suppressOutput\": True  # 不在转录模式中显示\n        }\n        print(json.dumps(output))\n        sys.exit(0)\n\n# 对于其他情况，让正常的权限流程继续\nsys.exit(0)\n```\n\n\u003Ch3 id=\"working-with-mcp-tools\">使用 MCP 工具\u003C\u002Fh3>\n\nClaude Code 钩子可以与\n[模型上下文协议 (MCP) 工具](\u002Fen\u002Fdocs\u002Fclaude-code\u002Fmcp) 无缝协作。当 MCP 服务器提供工具时，这些工具会以一种特殊的命名模式出现，您可以在自己的钩子中匹配这种模式。\n\n#### MCP 工具命名\n\nMCP 工具遵循 `mcp__\u003Cserver>__\u003Ctool>` 的命名模式，例如：\n\n- `mcp__memory__create_entities` - 内存服务器的创建实体工具\n- `mcp__filesystem__read_file` - 文件系统服务器的读取文件工具\n- `mcp__github__search_repositories` - GitHub 服务器的搜索工具\n\n#### 为 MCP 工具配置钩子\n\n您可以针对特定的 MCP 工具或整个 MCP 服务器进行配置：\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"mcp__memory__.*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo 'Memory operation initiated' >> ~\u002Fmcp-operations.log\"\n          }\n        ]\n      },\n      {\n        \"matcher\": \"mcp__.*__write.*\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"\u002Fhome\u002Fuser\u002Fscripts\u002Fvalidate-mcp-write.py\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n\u003Ch3 id=\"hooks-examples\">示例\u003C\u002Fh3>\n\n> [!TIP]\n> 有关代码格式化、通知和文件保护等实用示例，请参阅入门指南中的“更多示例”(\u002Fen\u002Fdocs\u002Fclaude-code\u002Fhooks-guide#more-examples)。\n\n\u003Ch3 id=\"security-considerations\">安全注意事项\u003C\u002Fh3>\n\n#### 免责声明\n\n**自担风险使用**：Claude Code 钩子会在您的系统上自动执行任意的 shell 命令。通过使用钩子，您确认：\n\n- 您对所配置的命令负全部责任\n- 钩子可以修改、删除或访问您用户账户可访问的任何文件\n- 恶意或编写不当的钩子可能导致数据丢失或系统损坏\n- Anthropic 不对因使用钩子而导致的任何损害提供任何保证或承担任何责任\n- 在生产环境中使用之前，您应在安全的环境中彻底测试钩子\n\n在将任何钩子命令添加到您的配置之前，请务必仔细审查并理解这些命令。\n\n\u003Ch3 id=\"hooks-security\">钩子安全注意事项\u003C\u002Fh3>\n\n以下是一些编写更安全钩子的关键实践：\n\n1. **验证并清理输入** - 切勿盲目信任输入数据\n2. **始终引用 shell 变量** - 使用 `\"$VAR\"` 而不是 `$VAR`\n3. **阻止路径遍历** - 检查文件路径中是否存在 `..`\n4. **使用绝对路径** - 为脚本指定完整路径（使用 `$CLAUDE_PROJECT_DIR` 表示项目路径）\n5. **跳过敏感文件** - 避免 `.env`、`.git\u002F`、密钥等文件\n\n#### 配置安全性\n\n直接在设置文件中编辑钩子并不会立即生效。Claude Code：\n\n1. 在启动时捕获钩子的快照\n2. 在整个会话中使用该快照\n3. 如果钩子被外部修改，会发出警告\n4. 必须在 `\u002Fhooks` 菜单中审核后才能应用更改\n\n这可以防止恶意钩子修改影响您当前的会话。\n\n\u003Ch3 id=\"hook-execution-details\">钩子执行细节\u003C\u002Fh3>\n\n- **超时**：默认执行限制为 60 秒，每个命令均可配置。\n  - 单个命令的超时不会影响其他命令。\n- **并行化**：所有匹配的钩子会并行运行\n- **环境**：在当前目录下运行，使用 Claude Code 的环境\n  - 环境变量 `CLAUDE_PROJECT_DIR` 可用，包含项目根目录的绝对路径\n- **输入**：通过 stdin 传递 JSON\n- **输出**：\n  - PreToolUse\u002FPostToolUse\u002FStop：进度显示在对话记录中（Ctrl-R）\n  - 通知：仅记录到调试日志中（`--debug`）\n\n\u003Ch3 id=\"hooks-debugging\">调试\u003C\u002Fh3>\n\n#### 基本故障排除\n\n如果您的钩子无法正常工作：\n\n1. **检查配置** - 运行 `\u002Fhooks` 查看您的钩子是否已注册\n2. **验证语法** - 确保您的 JSON 设置有效\n3. **测试命令** - 先手动运行钩子命令\n4. **检查权限** - 确保脚本具有可执行权限\n5. **查看日志** - 使用 `claude --debug` 查看钩子执行详情\n\n常见问题：\n\n- **引号未转义** - 在 JSON 字符串中使用 `\\\"`\n- **匹配器错误** - 检查工具名称是否完全匹配（区分大小写）\n- **命令未找到** - 为脚本使用完整路径\n\n#### 高级调试\n\n对于复杂的钩子问题：\n\n1. **检查钩子执行** - 使用 `claude --debug` 查看详细的钩子执行过程\n2. **验证 JSON 模式** - 使用外部工具测试钩子的输入和输出\n3. **检查环境变量** - 验证 Claude Code 的环境是否正确\n4. **测试边界条件** - 尝试使用不寻常的文件路径或输入运行钩子\n5. **监控系统资源** - 检查钩子执行过程中是否有资源耗尽的情况\n6. **使用结构化日志记录** - 在您的钩子脚本中实现日志记录\n\n#### 调试输出示例\n\n使用 `claude --debug` 查看钩子执行详情：\n\n```\n[DEBUG] Executing hooks for PostToolUse:Write\n[DEBUG] Getting matching hook commands for PostToolUse with query: Write\n[DEBUG] Found 1 hook matchers in settings\n[DEBUG] Matched 1 hooks for query \"Write\"\n[DEBUG] Found 1 hook commands to execute\n[DEBUG] Executing hook command: \u003CYour command> with timeout 60000ms\n[DEBUG] Hook command completed with status 0: \u003CYour stdout>\n```\n\n进度消息会显示在对话记录模式（Ctrl-R）中，显示：\n\n- 正在运行哪个钩子\n- 正在执行的命令\n- 成功或失败状态\n- 输出或错误信息\n\n---\n\n\u003Ch1 id=\"security--permissions\">安全与权限\u003C\u002Fh1>\n\n#### 工具权限模式\n\n```bash\n# 允许特定工具（读取\u002F编辑文件）\nclaude --allowedTools \"Edit,Read\"\n\n# 允许工具类别，包括 Bash（但仍有限制范围）\nclaude --allowedTools \"Edit,Read,Bash\"\n\n# 限定权限范围（所有 git 命令）\nclaude --allowedTools \"Bash(git:*)\"\n\n# 多重限定范围（git + npm）\nclaude --allowedTools \"Bash(git:*),Bash(npm:*)\"\n```\n\n\u003Ch2 id=\"dangerous-mode\">危险模式\u003C\u002Fh2>\n\n> [!Warning]\n> 切勿在生产系统、共享机器或包含重要数据的系统中使用\n> 仅在隔离环境（如 Docker 容器）中使用此模式，否则可能导致数据丢失并危及您的系统！\n>\n> `claude --dangerously-skip-permissions`\n\n\u003Ch1 id=\"automation--integration\">自动化与集成\u003C\u002Fh1>\n\n\u003Ch2 id=\"automation--scripting-with-claude-code\">使用 Claude Code 进行自动化和脚本编写\u003C\u002Fh2>\n\n> GitHub Actions，您可以直接复制粘贴 :p\n\n1. 在您的组织\u002F仓库中安装 Claude GitHub 应用程序（这是 Actions 能够对 PR 或问题发表评论的必要条件）。\n2. 在您的仓库中，添加一个名为 **`ANTHROPIC_API_KEY`** 的秘密设置 → 秘密和变量 → Actions → 新建仓库秘密\n3. 将下面的工作流复制到 **`.github\u002Fworkflows\u002F`** 目录中。\n4. 打开一个 **测试 PR**（或新建一个问题），看看它们是否能正常运行。\n\n> [!TIP]\n> 当您长期采用这些工作流时，请将其固定到某个发布标签上（例如 `@v1`）。下面的代码片段为了便于阅读，使用了分支标签。\n\n\u003Ch2 id=\"auto-pr-review-inline-comments\">自动 PR 审核（内联评论）\u003C\u002Fh2>\n\n> **在 PR 打开或更新时，立即创建带有内联评论的结构化评审。**\n\n**文件：** `.github\u002Fworkflows\u002Fclaude-pr-auto-review.yml`\n\n```yaml\nname: 自动评审 PR\non:\n  pull_request:\n    types: [opened, synchronize, reopened, ready_for_review]\n\npermissions:\n  contents: read\n  pull-requests: write\n\njobs:\n  auto-review:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with:\n          fetch-depth: 1\n\n      - name: Claude PR 审核\n        uses: anthropics\u002Fclaude-code-action@main\n        with:\n          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}\n          # Claude 将获取差异并留下内联评论\n          direct_prompt: |\n            审查此拉取请求的差异，检查其正确性、可读性、测试覆盖、性能和开发体验。\n            优先提供具体且可操作的建议。在适当的地方使用内联评论。\n          # 运行期间允许使用的 GitHub 工具：\n          allowed_tools: >-\n            mcp__github__get_pull_request_diff,\n            mcp__github__create_pending_pull_request_review,\n            mcp__github__add_comment_to_pending_review,\n            mcp__github__submit_pending_pull_request_review\n```\n\n\u003Ch2 id=\"security-review-on-every-pr\">每个 PR 的安全审核\u003C\u002Fh2>\n\n> **运行专注的安全扫描，并将发现直接评论到 PR 上。**\n\n**文件：** `.github\u002Fworkflows\u002Fclaude-security-review.yml`\n\n```yaml\nname: 安全审核\non:\n  pull_request:\n\npermissions:\n  contents: read\n  pull-requests: write\n\njobs:\n  security:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with:\n          ref: ${{ github.event.pull_request.head.sha || github.sha }}\n          fetch-depth: 2\n\n      - name: Claude 代码安全审核\n        uses: anthropics\u002Fclaude-code-security-review@main\n        with:\n          claude-api-key: ${{ secrets.ANTHROPIC_API_KEY }}\n          comment-pr: true\n          # 可选：\n          # exclude-directories: \"docs,examples\"\n          # claudecode-timeout: \"20\"\n          # claude-model: \"claude-sonnet-4-6-20260217\"\n```\n\n\u003Ch2 id=\"issue-triage-suggest-labels--severity\">问题分类（建议标签与严重性）\u003C\u002Fh2>\n\n> **当新问题打开时，Claude 会提出标签\u002F严重性建议，并发布整洁的分类评论。您可以通过切换一个标志来启用“自动应用标签”功能。**\n\n**文件：** `.github\u002Fworkflows\u002Fclaude-issue-triage.yml`\n\n```yaml\nname: Claude 问题分类\non:\n  issues:\n    types: [opened, edited, reopened]\n\npermissions:\n  contents: read\n  issues: write\n\njobs:\n  triage:\n    runs-on: ubuntu-latest\n    env:\n      CLAUDE_MODEL: claude-sonnet-4-6-20260217\n    steps:\n      - name: 收集上下文及相似问题\n        id: gather\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        run: |\n          TITLE=\"${{ github.event.issue.title }}\"\n          BODY=\"${{ github.event.issue.body }}\"\n          # 基于标题关键词的简单相似搜索\n          Q=$(echo \"$TITLE\" | tr -dc '[:alnum:] ' | awk '{print $1\" \"$2\" \"$3\" \"$4}')\n          gh api -X GET search\u002Fissues -f q=\"repo:${{ github.repository }} is:issue $Q\" -f per_page=5 > similars.json\n          echo \"$TITLE\" > title.txt\n          echo \"$BODY\" > body.txt\n\n      - name: 向 Claude 请求分类 JSON\n        env:\n          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}\n        run: |\n          cat > payload.json \u003C\u003C 'JSON'\n          {\n            \"model\": \"${{ env.CLAUDE_MODEL }}\",\n            \"max_tokens\": 1500,\n            \"system\": \"你是一位务实的分类工程师。请务必具体，同时注意避免重复问题。\",\n            \"messages\": [{\n              \"role\": \"user\",\n              \"content\": [{\n                \"type\":\"text\",\n                \"text\":\"根据该问题及其相似候选，生成严格的 JSON 格式，包含以下键：labels（字符串数组）、severity（低、中、高、critical 中的一个）、duplicate_url（字符串或空）、comment_markdown（简短文本）。请勿包含任何额外的键。\"\n              },\n              {\"type\":\"text\",\"text\":\"问题标题：\\n\"},\n              {\"type\":\"text\",\"text\": (从文件中引入) },\n              {\"type\":\"text\",\"text\":\"\\n\\n问题描述：\\n\"},\n              {\"type\":\"text\",\"text\": (从文件中引入) },\n              {\"type\":\"text\",\"text\":\"\\n\\n相似问题（JSON）：\\n\"},\n              {\"type\":\"text\",\"text\": (从文件中引入) }]\n            }]\n          }\n          JSON\n          # 安全注入文件内容\n          jq --arg title \"$(cat title.txt)\" '.messages[0].content[2].text = $title' payload.json \\\n          | jq --arg body \"$(cat body.txt)\" '.messages[0].content[4].text = $body' \\\n          | jq --arg sims \"$(cat similars.json)\" '.messages[0].content[6].text = $sims' > payload.final.json\n\n          curl -s https:\u002F\u002Fapi.anthropic.com\u002Fv1\u002Fmessages \\\n            -H \"x-api-key: $ANTHROPIC_API_KEY\" \\\n            -H \"anthropic-version: 2023-06-01\" \\\n            -H \"content-type: application\u002Fjson\" \\\n            -d @payload.final.json > out.json\n          jq -r '.content[0].text' out.json > triage.json || echo '{}' > triage.json\n          # 验证 JSON 以避免发布无效数据\n          jq -e . triage.json >\u002Fdev\u002Fnull 2>&1 || echo '{\"labels\":[],\"severity\":\"low\",\"duplicate_url\":\"\",\"comment_markdown\":\"(分类解析失败)\"}' > triage.json\n\n      - name: 应用标签（可选）\n        if: ${{ false }} # 切换为 `true` 即可自动应用标签\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const triage = JSON.parse(require('fs').readFileSync('triage.json','utf8'))\n            if (triage.labels?.length) {\n              await github.rest.issues.addLabels({\n                owner: context.repo.owner,\n                repo: context.repo.repo,\n                issue_number: context.issue.number,\n                labels: triage.labels\n              })\n            }\n\n      - name: 发布分类评论\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const fs = require('fs')\n            const triage = JSON.parse(fs.readFileSync('triage.json','utf8'))\n            const md = `### 🤖 分类\n            - **建议标签：** ${triage.labels?.join(', ') || '—'}\n            - **严重性：** ${triage.severity || '—'}\n            ${triage.duplicate_url ? `- **可能重复：** ${triage.duplicate_url}\\n` : ''}\n            ---\n            ${triage.comment_markdown || ''}`\n            await github.rest.issues.createComment({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              issue_number: context.issue.number,\n              body: md\n            })\n```\n\n> [!NOTE]\n> 分类工作流默认会发布一条**建议评论**。如果希望自动应用标签，请将`Apply labels`步骤切换为`true`。\n>\n> ### 配置与自定义\n>\n> - **模型选择**：按照所示设置`CLAUDE_MODEL`（例如，`claude-sonnet-4-6-20260217`）。\n> - **密钥**：需要`ANTHROPIC_API_KEY`。内置的`GITHUB_TOKEN`足以用于发布评论和应用标签。\n> - **权限**：每个工作流都会声明其所需的最低权限（`pull-requests: write`和\u002F或`issues: write`）。仅当您的组织要求更严格的策略时才进行调整。\n> - **范围**：在触发器上使用`paths:`过滤器来限制工作流运行的时间（例如，仅针对`\u002Fsrc`目录，或排除`\u002Fdocs`目录）。\n>\n> ### 故障排除\n>\n> 首先检查**操作日志**——大多数问题都是由于缺少密钥或权限，或者YAML块缩进错误导致的。\n>\n> - **PR上没有出现评论**：请确认Claude GitHub应用已安装，并且工作流具有`pull-requests: write`权限。\n> - **应用标签时出现403错误**：确保作业或步骤具有`issues: write`权限。默认的`GITHUB_TOKEN`必须有权访问该仓库。\n> - **Anthropic API错误**：请确认`ANTHROPIC_API_KEY`已在仓库（或组织）级别设置，并且未过期。\n> - **“YAML格式不正确”**：请检查缩进——每级缩进两个空格，不要使用制表符。\n\n---\n\n\u003Ch1 id=\"help--troubleshooting\">帮助与故障排除\u003C\u002Fh1>\n\n> [!TIP]\n> **问：找不到`claude`命令，但`npx claude`可以运行？**\n>\n> > **答：您的`PATH`环境变量中缺少npm全局bin目录。请参阅关于`PATH`问题的部分，适用于[Windows](#windowspath)或[Linux](#linuxpath)。**\n>\n> **问：我需要哪个版本的Node.js？**\n>\n> > **答：Node.js 18及以上版本（理想情况下是20及以上版本）。您可以通过运行`node --version`来检查。**\n>\n> **问：我在哪里可以看到日志？**\n>\n> > **答：运行`claude doctor`和`claude --verbose`，诊断窗口会显示日志文件的位置。**\n>\n> **问：修改`PATH`后需要重启吗？**\n>\n> > **答：不需要重启，但您\u003Cmark>必须\u003C\u002Fmark>打开一个\u003Cmark>新的\u003C\u002Fmark>终端窗口。**\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"debug-quick-commands\">调试快捷命令\u003C\u002Fh2>\n\n_请查看`claude doctor`的输出，以获取日志位置和环境检查信息。_\n\n> [!Note]\n>\n> ```bash\n> claude                  # 打开Claude UI界面（如果已在PATH中）\n> claude --version        # 显示CLI版本（例如，1.0.xx）\n> claude update           # 更新CLI（如果支持）\n>\n> claude doctor           # 打开诊断\u002F调试窗口\n> npx claude \u002Fdoctor      # 打开诊断\u002F调试窗口\n>\n> claude --debug          # 以诊断模式启动Claude\n> claude --verbose        # 启用详细日志记录\n>\n> where claude            # Windows（cmd）\n> which claude            # macOS\u002FLinux（bash\u002Fzsh）\n>\n> npm bin -g              # Linux 检查您的全局bin路径\n> npm prefix -g           # Windows 检查您的全局bin路径\n> ```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"linuxpath\">临时修复PATH\u003C\u002Fh2>\n\n**您的`PATH`环境变量很可能没有包含npm全局bin目录。**\n\n> [!Note]\n>\n> #### Windows（CMD）：\n>\n> ```bash\n> set PATH=%USERPROFILE%\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;%PATH%\n> where claude\n> claude --debug\n> ```\n>\n> #### Windows（PowerShell）：\n>\n> ```powershell\n> $env:Path = \"$env:USERPROFILE\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;$env:Path\"\n> where claude\n> claude --debug\n> ```\n>\n> #### Linux\u002FMacOS（bash\u002Fzsh）：\n>\n> ```bash\n> export PATH=\"$(npm config get prefix)\u002Fbin:$HOME\u002F.local\u002Fbin:$PATH\"\n> which claude\n> claude doctor\n> ```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"windowspath\">Windows永久修复PATH\u003C\u002Fh2>\n\n**请将`\u003Cyou>`替换为您自己的Windows用户名（不要带尖括号）**\n\n- **开始 → 输入：\u003Ckbd>环境变量\u003C\u002Fkbd>**\n- **打开\u003Ckbd>编辑系统环境变量\u003C\u002Fkbd> → \u003Ckbd>环境变量\u003C\u002Fkbd>**\n- **在\u003Ckbd>用户变量\u003C\u002Fkbd>下，选择\u003Cmark>\u003Cyou>\u003C\u002Fmark>的`Path` → `编辑` → `新建`，添加以下内容：**\n\n```path\nC:\\Users\\\u003Cyou>\\AppData\\Roaming\\npm\nC:\\Program Files\\nodejs\u003C\u002Fkbd>\n```\n\n> **可选添加的位置：**\n\n```path\nC:\\Users\\\u003Cyou>\\.claude\\local\\bin\nC:\\Users\\\u003Cyou>\\.local\\bin\n```\n\n- **删除重复项、任何包含`%PATH%`的条目以及多余的引号（`\"`）。点击`确定`。**\n- **打开一个新的命令提示符或PowerShell，并验证：**\n\n```C\nwhere claude\nclaude doctor\n```\n\n> [!Tip]\n>\n> ### 可选直接运行（当PATH损坏时）\n>\n> > **Windows（PowerShell\u002Fcmd）**\n>\n> ```powershell\n> \"%USERPROFILE%\\AppData\\Roaming\\npm\\claude.cmd\" --version\n> \"%USERPROFILE%\\AppData\\Roaming\\npm\\claude.cmd\" doctor\n> ```\n>\n> > **或者通过npx：**\n>\n> ```\n> npx claude doctor\n> ```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"installation--nodejs-issues\">安装\u002FNode.js问题\u003C\u002Fh3>\n\n**必须使用Node 18及以上版本（推荐20及以上版本）**\n\n```bash\nnode --version\n```\n\n**干净卸载**\n\n```bash\nnpm uninstall -g @anthropic-ai\u002Fclaude-code\n```\n\n**全新安装**\n\n```bash\nnpm install  -g @anthropic-ai\u002Fclaude-code\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"authentication-issues\">认证问题\u003C\u002Fh3>\n> *请确认您的Anthropic API密钥对CLI可用。*\n\n**PowerShell（Windows）：**\n\n```powershell\necho $env:ANTHROPIC_API_KEY\nclaude -p \"test\" --verbose\n```\n\n**bash\u002Fzsh（macOS\u002FLinux）：**\n\n```bash\necho $ANTHROPIC_API_KEY\nclaude -p \"test\" --verbose\n```\n\n_如果该变量为空，请为您的shell或配置文件设置它，或者使用操作系统的密钥链\u002F秘密管理工具。_\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"permission--allowed-tools-issues\">权限\u002F允许工具问题\u003C\u002Fh3>\n\n**检查权限**\n\n```bash\nclaude config get allowedTools\n```\n\n**重置权限**\n\n```bash\nclaude config set allowedTools \"[]\"\n```\n\n**最小安全设置（示例）**\n\n```bash\nclaude config set allowedTools '[\"Edit\",\"View\"]'\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch3 id=\"mcp-model-context-protocol-issues\">MCP（模型上下文协议）问题\u003C\u002Fh3>\n\n> **调试MCP服务器**\n\n```bash\nclaude --debug\n```\n\n> **列出并移除MCP服务器**\n\n```bash\nclaude mcp list\nclaude mcp remove \u003Cserver-name>\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"full-clean-reinstall-windows--powershell\">完全清理并重新安装（Windows \u002F PowerShell）\u003C\u002Fh2>\n\n> [!Caution]\n> **以下步骤将移除Claude Code的二进制文件、缓存和用户目录下的配置文件**\n\n> 1. 卸载全局npm包\n\n```powershell\nnpm uninstall -g @anthropic-ai\u002Fclaude-code\n```\n\n> 2. 删除残留的桥接文件\n\n```powershell\nRemove-Item -LiteralPath \"$env:USERPROFILE\\AppData\\Roaming\\npm\\claude*\" -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\AppData\\Roaming\\npm\\node_modules\\@anthropic-ai\\claude-code\" -Recurse -Force -ErrorAction SilentlyContinue\n```\n\n> 3. 删除缓存的安装程序及原生文件\n\n```powershell\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\\downloads\\*\" -Recurse -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\\local\\bin\\claude.exe\" -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\\local\" -Recurse -Force -ErrorAction SilentlyContinue\n```\n\n> 4. 删除配置文件和项目本地文件\n\n```powershell\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude.json\" -Force -ErrorAction SilentlyContinue\nRemove-Item -LiteralPath \"$env:USERPROFILE\\.claude\" -Recurse -Force -ErrorAction SilentlyContinue\n```\n\n> 5. 重新安装\n\n```powershell\nnpm install -g @anthropic-ai\u002Fclaude-code\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"one-shot-health-check-copypaste\">一次性健康检查（复制\u002F粘贴）\u003C\u002Fh2>\n\n**Windows (PowerShell):**\n\n```powershell\nWrite-Host \"`n=== Node.js 和 npm ===\"; node --version; npm --version\nWrite-Host \"`n=== Claude 在哪里？===\"; where claude\nWrite-Host \"`n=== 尝试运行 doctor ===\"; try { claude doctor } catch { Write-Host \"Claude 没有在 PATH 中\" }\nWrite-Host \"`n=== API 密钥已设置吗？===\"; if ($env:ANTHROPIC_API_KEY) { \"是\" } else { \"否\" }\n```\n\n**macOS\u002FLinux (bash\u002Fzsh):**\n\n```bash\necho \"=== Node.js 和 npm ===\"; node --version; npm --version\necho \"=== Claude 在哪里？===\"; which claude || echo \"Claude 没有在 PATH 中\"\necho \"=== 尝试运行 doctor ===\"; claude doctor || true\necho \"=== API 密钥已设置吗？===\"; [ -n \"$ANTHROPIC_API_KEY\" ] && echo 是 || echo 否\n```\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n---\n\n\u003Ctable>\u003Ctd>\n\n\u003Ch2 id=\"appendix-useful-paths\">附录：常用路径\u003C\u002Fh2>\n\n- **Windows npm 全局 bin 目录:** `C:\\Users\\\u003Cyou>\\AppData\\Roaming\\npm`\n- **Windows Node.js 安装目录:** `C:\\Program Files\\nodejs`\n- **Claude 本地数据（Win）:** `C:\\Users\\\u003Cyou>\\.claude\\`\n- **Claude 配置文件（Win）:** `C:\\Users\\\u003Cyou>\\.claude.json`\n- **macOS\u002FLinux npm 全局 bin 目录:** `$(npm config get prefix)\u002Fbin`（通常为 `\u002Fusr\u002Flocal\u002Fbin` 或 `$HOME\u002F.npm-global\u002Fbin`）\n\n\u003C\u002Ftd>\u003C\u002Ftable>\n\n\u003Ch2 id=\"best-practices\">最佳实践\u003C\u002Fh2>\n\n> 精选指南，帮助您安全、快速且正确地使用 Claude Code CLI 和交互式 REPL。此处的所有命令和标志均与截至 **2026年2月28日** 的 Anthropic 官方文档一致。\n\n\u003Ch2 id=\"effective-prompting\">有效提示技巧\u003C\u002Fh2>\n\n```bash\n\n\n# 好的例子：具体且详细\nclaude \"审查 UserAuth.js 中的安全漏洞，重点关注 JWT 处理\"\n\n# 不好的例子：含糊不清\nclaude \"检查我的代码\"\n```\n\n提示：`claude \"query\"` 会启动预加载了您的提示的交互式 REPL；`claude -p \"query\"` 则以 **打印模式**（非交互式）运行并退出。\n\n---\n\n\u003Ch2 id=\"security-best-practices-main\">安全最佳实践\u003C\u002Fh2>\n\n1. **从最小权限开始**\n   - 优先使用显式的允许和拒绝规则，无论是在 CLI 中还是在配置文件中。\n\n   ```bash\n   # 只允许本次运行所需的权限\n   claude --allowedTools \"Read\" \"Grep\" \"LS\" \"Bash(npm run test:*)\"\n   ```\n\n   或者将项目策略写入 `.claude\u002Fsettings.json`：\n\n   ```json\n   {\n     \"permissions\": {\n       \"allow\": [\"Read\", \"Grep\", \"LS\", \"Bash(npm run test:*)\"],\n       \"deny\": [\n         \"WebFetch\",\n         \"Bash(curl:*)\",\n         \"Read(.\u002F.env)\",\n         \"Read(.\u002Fsecrets\u002F**)\"\n       ]\n     }\n   }\n   ```\n\n2. **正确处理敏感信息**\n   - 对于 SDK 或自动化流程，使用环境变量：\n\n   ```bash\n   export ANTHROPIC_API_KEY=\"your_key\"   # 用于 SDK 或打印模式\n   ```\n\n   - 在交互式 REPL 中，建议使用 `\u002Flogin` 命令登录，而不是硬编码令牌。\n   - 在配置文件中禁止访问敏感文件（取代旧的 `ignorePatterns`）：\n\n   ```json\n   {\n     \"permissions\": {\n       \"deny\": [\"Read(.\u002F.env)\", \"Read(.\u002F.env.*)\", \"Read(.\u002Fsecrets\u002F**)\"]\n     }\n   }\n   ```\n\n3. **定期审计权限**\n\n   ```bash\n   # 项目级设置\n   claude config list\n   claude config get permissions.allow\n   claude config get permissions.deny\n\n   # 全局级设置\n   claude config list -g\n   ```\n\n4. **避免在生产环境中使用绕过模式**\n   - **不要**在隔离或开发沙盒之外使用 `--dangerously-skip-permissions`。\n   - 对于无人值守的任务，应结合狭窄的 `--allowedTools` 和 `--disallowedTools` 选项，以及项目级别的配置文件。\n\n---\n\n\u003Ch2 id=\"performance-tips\">性能优化建议\u003C\u002Fh2>\n\n1. **在自动化任务中使用机器可读的输出**\n\n   ```bash\n   claude -p \"总结此错误日志\" --output-format json\n   # 支持的格式：text | json | stream-json\n   ```\n\n2. **限制非交互式任务的执行范围**\n\n   ```bash\n   claude -p \"运行类型检查并总结失败情况\" --max-turns 3\n   # 也可以限制思考时间：\n   export MAX_THINKING_TOKENS=20000\n   ```\n\n3. **保持会话整洁**\n\n   ```bash\n   # 默认保留最近 30 天的会话，可以调整为 20 天\n   claude config set -g cleanupPeriodDays 20\n   ```\n\n4. **限制上下文范围**\n\n   ```bash\n   # 只授予对相关路径的访问权限，以减少扫描和噪音\n   claude --add-dir .\u002Fservices\u002Fapi .\u002Fpackages\u002Fui\n   ```\n\n5. **选择合适的模型**\n   - CLI 别名：`--model sonnet` 或 `--model opus`（该系列最新版本）。\n   - 截至 2026 年 2 月，**Sonnet 4.6** 是默认的 Sonnet 模型——以 Sonnet 的价格提供前沿性能，并拥有 100 万标记的上下文窗口。\n   - 为了确保可重复性，在配置中固定完整的模型 ID（例如 `\"claude-sonnet-4-6-20260217\"`）。\n\n---\n\n\u003Ch2 id=\"monitoring--alerting\">监控与告警\u003C\u002Fh2>\n\n**1) 健康检查**\n使用内置的 `doctor` 命令来验证安装和环境是否正常。\n\n```bash\n# 每 15 分钟运行一次\n*\u002F15 * * * * \u002Fusr\u002Flocal\u002Fbin\u002Fclaude doctor >\u002Fdev\u002Fnull 2>&1 || \\\nmail -s \"Claude Code doctor 失败\" admin@company.com \u003C\u002Fdev\u002Fnull\n```\n\n**2) 日志分析批处理作业**\n\n```bash\n# 每天以非交互式 JSON 格式进行分析\n0 6 * * * tail -1000 \u002Fvar\u002Flog\u002Fapp.log | \\\nclaude -p \"分析错误、回归问题及可疑模式；输出 JSON 格式。\" \\\n--output-format json > \u002Ftmp\u002Fdaily-analysis.json\n```\n\n**3) 遥测（可选）**\nClaude Code 会发出 OpenTelemetry 指标和事件。您可以在配置或环境变量中设置导出器（例如 OTLP），并将数据发送到您的可观ability 平台（如 Datadog、Honeycomb、Prometheus\u002FGrafana 等）。\n\n---\n\n\u003Ch2 id=\"collaboration-best-practices\">协作最佳实践\u003C\u002Fh2>\n\n\u003Ch3 id=\"team-workflows\">团队工作流程\u003C\u002Fh2>\n\n**1) 共享版本化的配置文件**\n\n```jsonc\n\u002F\u002F .claude\u002Fsettings.json（提交到代码库）\n{\n  \"permissions\": {\n    \"allow\": [\n      \"Read\",\n      \"Grep\",\n      \"LS\",\n      \"Bash(npm run lint)\",\n      \"Bash(npm run test:*)\",\n    ],\n    \"deny\": [\n      \"WebFetch\",\n      \"Read(.\u002F.env)\",\n      \"Read(.\u002F.env.*)\",\n      \"Read(.\u002Fsecrets\u002F**)\",\n    ],\n  },\n  \u002F\u002F 如果需要可重复性，可以在这里固定完整的模型 ID：\n  \"model\": \"claude-sonnet-4-6-20260217\",\n}\n```\n\n**2) 文档自动化**\n\n```bash\n# 使用明确的任务更新文档\nclaude \"更新 README.md，反映最新的 API 端点和示例。\"\nclaude \"根据 schema.prisma 生成 TypeScript 类型定义，并写入 \u002Ftypes 目录。\"\n```\n\n**3) 代码审查标准**\n\n```bash\nclaude \"审查代码中的潜在逻辑错误，并提出改进建议。\"\nclaude \"检查代码是否符合项目的编码规范，并给出反馈。\"\nclaude \"评估代码的可维护性和扩展性，并提出优化建议。\"\n```\n\n---\n\n\u003Ch2 id=\"further-resources\">更多资源\u003C\u002Fh2>\n\n- **官方文档:** https:\u002F\u002Fdocs.anthropic.com\u002F\n- **社区论坛:** https:\u002F\u002Fcommunity.anthropic.com\u002F\n- **GitHub 仓库:** https:\u002F\u002Fgithub.com\u002Fanthropic-ai\u002Fclaude-code\n- **API 参考:** https:\u002F\u002Fapi.anthropic.com\u002F\n\n---\n\n\u003Ch2 id=\"conclusion\">结论\u003C\u002Fh2>\n\nClaude Code CLI 和交互式 REPL 为开发者提供了强大的工具，能够显著提升开发效率和代码质量。通过遵循上述最佳实践，您可以更安全、高效地利用这些工具，同时确保代码的安全性和可维护性。无论是个人开发还是团队协作，合理配置和使用 Claude Code 都能为您带来显著的价值。\n\n# 使用受限工具审查本地差异\ngit fetch origin main\ngit diff origin\u002Fmain...HEAD > \u002Ftmp\u002Fdiff.patch\nclaude --allowedTools \"Read\" \"Grep\" \"Bash(git:*)\" \\\n  \"使用团队标准审查 \u002Ftmp\u002Fdiff.patch：\n   - 安全最佳实践\n   - 性能考量\n   - 代码风格合规性\n   - 测试覆盖率是否充分\"\n```\n\n\u003Ch3 id=\"knowledge-sharing\">知识共享\u003C\u002Fh3>\n\n**1) 项目运行手册**\n\n```bash\nclaude \"为这个应用创建部署运行手册：步骤、检查项、回滚流程。\"\nclaude \"记录新开发人员的入职指南：环境搭建、常用命令、编码规范。\"\n```\n\n**2) 架构文档**\n\n```bash\nclaude \"更新架构文档以反映新的微服务架构。\"\nclaude \"为认证流程创建序列图。\"\n```\n\n> 小贴士：将持久化的上下文保存在项目根目录下的 **CLAUDE.md** 文件中。在 REPL 中，可以使用 `\u002Fmemory` 来管理上下文，并用 `@path` 将文件内容导入到提示中。\n\n---\n\n\u003Ch2 id=\"common-pitfalls-to-avoid\">需要避免的常见陷阱\u003C\u002Fh2>\n\n\u003Ch3 id=\"security-pitfalls\">安全方面\u003C\u002Fh3>\n\n**❌ 不要**\n\n- 在生产系统上使用 `--dangerously-skip-permissions`\n- 将密钥硬编码在命令或配置中\n- 授予过于宽泛的权限（例如 `Bash(*)`）\n- 无必要地以高权限运行\n\n**✅ 要做**\n\n- 将密钥存储在环境变量和凭据管理工具中\n- 从最小的 `permissions.allow` 开始，逐步扩大权限范围\n- 使用 `claude config list` 和 `claude config get` 进行审计\n- 将高风险操作隔离在容器或虚拟机中\n\n\u003Ch3 id=\"performance-pitfalls\">性能方面\u003C\u002Fh3>\n\n**❌ 不要**\n\n- 当只需要一个包时却加载整个 monorepo\n- 对简单任务也用尽思考或回合预算\n- 忽视会话清理\n\n**✅ 要做**\n\n- 使用 `--add-dir` 提供聚焦的上下文\n- 根据需求调整 `--max-turns` 和 `MAX_THINKING_TOKENS`\n- 设置 `cleanupPeriodDays` 定期清理旧会话\n\n\u003Ch3 id=\"workflow-pitfalls\">工作流方面\u003C\u002Fh3>\n\n**❌ 不要**\n\n- 跳过项目上下文（`CLAUDE.md`）\n- 使用模糊不清的提示\n- 忽视错误和日志\n- 在未测试的情况下就进行自动化\n\n**✅ 要做**\n\n- 维护并及时更新 `CLAUDE.md`\n- 在提示中保持具体性和目标导向\n- 根据需要通过日志或 OTel 监控\n- 先在安全环境中测试自动化流程\n\n---\n\n\u003Ch1 id=\"third-party-integrations\">第三方集成\u003C\u002Fh1>\n\n\u003Ch2 id=\"deepseek-integration\">DeepSeek 集成\u003C\u002Fh1>\n\n1. ###### 确保已安装 claude Code\n\n```\nnpm install -g @anthropic-ai\u002Fclaude-code\n```\n\n2. ###### 配置环境变量\n\n```bash\nexport ANTHROPIC_BASE_URL=https:\u002F\u002Fapi.deepseek.com\u002Fanthropic\nexport ANTHROPIC_AUTH_TOKEN=${YOUR_API_KEY}\nexport ANTHROPIC_MODEL=deepseek-chat\nexport ANTHROPIC_SMALL_FAST_MODEL=deepseek-chat\n```\n\n3. ###### 现在只需启动 `claude` 即可\n\n更多信息请参阅 [DeepSeek 官方文档](https:\u002F\u002Fapi-docs.deepseek.com\u002Fguides\u002Fanthropic_api)","# Claude Code 快速上手指南\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下最低要求：\n\n*   **操作系统**:\n    *   macOS 10.15+\n    *   Linux (Ubuntu 20.04+ \u002F Debian 10+)\n    *   Windows 10\u002F11 或 WSL\n*   **硬件配置**: 最低 4GB RAM，推荐 8GB 及以上。\n*   **网络环境**: 需要稳定的互联网连接以调用 Anthropic API。\n*   **依赖软件**:\n    *   **方案 A (推荐)**: 无需安装 Node.js，原生安装程序自带运行时。\n    *   **方案 B (npm)**: 如需通过 npm 安装，需预先安装 Node.js 18+。\n    *   **可选**: Git 2.23+ 及 GitHub\u002FGitLab CLI（用于 PR 工作流）。\n\n> **注意**: 请提前在 [Anthropic Console](https:\u002F\u002Fconsole.anthropic.com) 获取您的 API Key (`sk-...`)。切勿将真实密钥提交到代码仓库，建议使用环境变量或密钥管理工具存储。\n\n---\n\n## 安装步骤\n\n推荐使用**原生安装程序**（无需配置 Node.js 环境），以下是各平台的具体命令：\n\n### 1. 原生安装 (推荐 ⭐️)\n\n**macOS \u002F Linux \u002F WSL**\n```bash\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash\n```\n\n**Windows (CMD)**\n```cmd\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.cmd -o install.cmd && install.cmd && del install.cmd\n```\n\n**Windows (PowerShell)**\n```powershell\nirm https:\u002F\u002Fclaude.ai\u002Finstall.ps1 | iex\n```\n\n**Arch Linux**\n```bash\nyay -S claude-code\n```\n\n### 2. 备选安装 (基于 npm)\n*仅当您已安装 Node.js 18+ 时使用*\n\n**全局安装**\n```bash\nnpm install -g @anthropic-ai\u002Fclaude-code\n```\n\n**Docker 快速体验**\n```bash\n# macOS\u002FLinux\ndocker run -it --rm -v \"$PWD:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim bash -lc 'npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude'\n\n# Windows (CMD)\ndocker run -it --rm -v \"%cd%:\u002Fworkspace\" -e ANTHROPIC_API_KEY=\"sk-your-key\" node:20-slim bash -lc \"npm i -g @anthropic-ai\u002Fclaude-code && cd \u002Fworkspace && claude\"\n```\n\n### 3. 验证安装\n安装完成后，运行以下命令检查版本：\n```bash\nclaude --version\n```\n或者检查安装路径：\n*   Linux\u002FmacOS: `which claude`\n*   Windows: `where claude`\n\n---\n\n## 基本使用\n\n### 1. 配置 API Key\n\n在使用前，您需要设置 `ANTHROPIC_API_KEY` 环境变量。\n\n**临时设置 (当前终端会话有效)**\n\n*   **Linux \u002F macOS (Bash\u002FZsh)**\n    ```bash\n    export ANTHROPIC_API_KEY=\"sk-your-key-here\"\n    ```\n*   **Windows (CMD)**\n    ```cmd\n    set ANTHROPIC_API_KEY=sk-your-key-here\n    ```\n*   **Windows (PowerShell)**\n    ```powershell\n    $env:ANTHROPIC_API_KEY = \"sk-your-key-here\"\n    ```\n\n**永久设置**\n*   **Linux**: 将 `export ANTHROPIC_API_KEY=\"sk-your-key-here\"` 添加到 `~\u002F.bashrc` 或 `~\u002F.zshrc`。\n*   **Windows**: 使用 `setx ANTHROPIC_API_KEY \"sk-your-key-here\"` (CMD) 或通过系统属性图形界面设置。\n\n**或者使用内置登录命令**\n```bash\nclaude \u002Flogin\n# 或\nclaude auth login\n```\n\n### 2. 启动与交互\n\n进入您的项目目录，直接运行 `claude` 即可启动交互式界面：\n\n```bash\ncd \u002Fpath\u002Fto\u002Fyour\u002Fproject\nclaude\n```\n\n> **提示**: 您也可以直接使用 `npx claude` 启动（如果未全局安装）。\n\n**简单示例**:\n启动后，您可以直接输入自然语言指令，例如：\n*   \"解释一下这个项目的结构\"\n*   \"帮我修复 src\u002Fmain.py 中的 bug\"\n*   \"为当前的 API 端点编写单元测试\"\n\n### 3. 集成 VS Code \u002F Cursor\n\n若要在编辑器中获得最佳体验：\n1.  确保在 VS Code 或 Cursor 中安装了 **Claude Code extension**。\n2.  在终端中进入项目目录并打开编辑器：\n    ```bash\n    cd \u002Fpath\u002Fto\u002Fproject\n    code .\n    ```\n3.  在编辑器内调用 Claude Code 插件即可。\n\n### 4. 常用管理命令\n\n*   **配置设置**: `claude config`\n*   **管理 MCP 服务器**: `claude mcp list` (支持 add\u002Fremove)\n*   **配置子代理**: `claude \u002Fagents`\n*   **更新版本**: `claude update`\n*   **开启完成任务提示音**:\n    ```bash\n    claude config set --global preferredNotifChannel terminal_bell\n    ```","某全栈开发者需要在紧急期限内重构一个遗留的 Node.js 微服务项目，并集成新的 MCP（模型上下文协议）工具以连接内部数据库。\n\n### 没有 claude-code-guide 时\n- **配置迷茫**：面对复杂的环境变量和 `.env` 设置，开发者只能盲目试错，花费数小时排查为何 Agent 无法读取本地密钥。\n- **功能闲置**：完全不知道存在“子代理（Sub Agents）”或“思维模式（Thinking Mode）”等高级特性，仅将 AI 当作普通聊天机器人使用，处理复杂任务效率极低。\n- **协作断层**：缺乏标准化的技能（Skills）库和插件系统参考，导致团队成员各自编写重复且质量参差不齐的自动化脚本。\n- **安全隐患**：在不了解“沙盒模式”或“危险模式”边界的情况下运行代码，险些因权限过大导致本地生产数据被意外修改。\n- **排障无门**：遇到 MCP 连接失败或 CLI 报错时，找不到系统的故障排除指南，只能去分散的论坛帖子中大海捞针。\n\n### 使用 claude-code-guide 后\n- **一键就绪**：参照“快速开始”和“配置”章节，5 分钟内即可完成环境变量与配置文件的标准设置，立即启动开发流程。\n- **效能倍增**：利用指南中的“工作流”与“代理团队”策略，并行调度多个子代理分别处理单元测试、代码重构和文档更新，任务完成速度提升 3 倍。\n- **生态复用**：直接调用指南推荐的 954+ 现成技能模板和插件系统，统一了团队内部的自动化标准，无需重复造轮子。\n- **安全可控**：严格遵循“安全最佳实践”，启用沙盒模式隔离高风险操作，确保在重构过程中核心数据零风险。\n- **精准排障**：通过内置的\"MCP 问题排查”和\"CLI 速查表”，迅速定位并解决了集成过程中的协议握手错误，大幅缩短调试时间。\n\nclaude-code-guide 将开发者从繁琐的配置摸索中解放出来，使其能直接驾驭 Claude Code 的高级自动化能力，实现从新手到专家级用户的无缝跃迁。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fzebbern_claude-code-guide_f69405d9.png","zebbern",null,"https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fzebbern_84715910.png","Bug hunter with a passion for automation & AI agents ","@github Open Source Maintainer","z_r@tuta.com","https:\u002F\u002Fgithub.com\u002Fzebbern",3940,374,"2026-04-16T14:33:41","MIT","Linux, macOS, Windows","未说明","最低 4GB，推荐 8GB+",{"notes":88,"python":85,"dependencies":89},"推荐使用原生安装器（Native Installer），该方式无需预先安装 Node.js；若使用 npm 安装则需 Node.js 18+ 环境。运行需要网络连接以调用 API。API 密钥需通过环境变量 ANTHROPIC_API_KEY 配置，建议使用系统密钥存储或忽略文件管理，切勿硬编码提交。",[90,91,92,93],"Node.js 18+ (仅 npm 安装需要)","git 2.23+ (可选)","GitHub CLI (可选)","GitLab CLI (可选)",[13,14,35,15,45],[96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,65,112,113,114],"ai","ai-agent","ai-agent-tools","claude","claude-ai","claude-api","claude-code","claude-code-communication","claude-commands","claude-desktop","claude-mcp","claude-sonnet","code","mcp","mcp-agents","vscode-extension","mcp-tools","claude-code-skills","anthropic-claude","2026-03-27T02:49:30.150509","2026-04-17T08:23:25.356188",[],[]]