SpyBara
Go Premium Account
2026
23 Jan 2026, 18:02
12 May 2026, 16:02 12 May 2026, 14:59 12 May 2026, 01:59 12 May 2026, 00:01 11 May 2026, 23:00 11 May 2026, 21:57 11 May 2026, 20:02 11 May 2026, 18:59 11 May 2026, 18:00 11 May 2026, 15:00 10 May 2026, 23:03 10 May 2026, 17:00 10 May 2026, 04:02 9 May 2026, 04:57 9 May 2026, 04:01 9 May 2026, 03:01 8 May 2026, 22:00 8 May 2026, 19:00 8 May 2026, 18:00 8 May 2026, 16:57 8 May 2026, 07:02 8 May 2026, 06:02 8 May 2026, 03:01 8 May 2026, 02:03 8 May 2026, 01:02 8 May 2026, 00:02 7 May 2026, 22:59 7 May 2026, 21:57 7 May 2026, 17:08 5 May 2026, 23:00 5 May 2026, 21:00 5 May 2026, 17:00 5 May 2026, 15:59 5 May 2026, 14:57 5 May 2026, 00:02 4 May 2026, 22:58 4 May 2026, 22:01 4 May 2026, 18:58 4 May 2026, 15:35 4 May 2026, 06:55 4 May 2026, 04:18 2 May 2026, 18:14 2 May 2026, 04:05 2 May 2026, 00:19 1 May 2026, 18:19 1 May 2026, 04:22 1 May 2026, 00:20 29 Apr 2026, 21:21 29 Apr 2026, 15:36 29 Apr 2026, 09:39 29 Apr 2026, 04:11 29 Apr 2026, 00:20 28 Apr 2026, 21:21 28 Apr 2026, 18:28 28 Apr 2026, 15:45 28 Apr 2026, 06:49 27 Apr 2026, 21:20 27 Apr 2026, 18:23 26 Apr 2026, 04:08 25 Apr 2026, 21:10 24 Apr 2026, 18:11 24 Apr 2026, 06:34 24 Apr 2026, 00:17 23 Apr 2026, 18:19 23 Apr 2026, 04:04 23 Apr 2026, 00:17 22 Apr 2026, 21:15 22 Apr 2026, 04:00 22 Apr 2026, 00:13 21 Apr 2026, 21:14 21 Apr 2026, 09:30 21 Apr 2026, 04:01 20 Apr 2026, 21:14 20 Apr 2026, 18:16 18 Apr 2026, 18:09 18 Apr 2026, 00:13 17 Apr 2026, 21:13 17 Apr 2026, 18:14 17 Apr 2026, 00:15 16 Apr 2026, 21:13 16 Apr 2026, 18:21 16 Apr 2026, 15:30 16 Apr 2026, 04:02 16 Apr 2026, 00:16 15 Apr 2026, 18:20 15 Apr 2026, 15:24 15 Apr 2026, 09:29 15 Apr 2026, 04:00 14 Apr 2026, 21:14 14 Apr 2026, 18:21 14 Apr 2026, 06:32 14 Apr 2026, 04:00 14 Apr 2026, 00:16 13 Apr 2026, 21:14 13 Apr 2026, 18:21 11 Apr 2026, 00:11 10 Apr 2026, 21:09 10 Apr 2026, 18:13 10 Apr 2026, 06:32 10 Apr 2026, 00:12 9 Apr 2026, 21:14 9 Apr 2026, 18:17 9 Apr 2026, 15:29 9 Apr 2026, 03:55 9 Apr 2026, 00:09 8 Apr 2026, 21:13 8 Apr 2026, 18:21 8 Apr 2026, 15:27 8 Apr 2026, 00:12 7 Apr 2026, 21:14 4 Apr 2026, 18:05 4 Apr 2026, 03:46 4 Apr 2026, 00:09 3 Apr 2026, 21:07 3 Apr 2026, 18:08 3 Apr 2026, 03:54 3 Apr 2026, 00:11 2 Apr 2026, 21:08 2 Apr 2026, 18:12 2 Apr 2026, 09:19 2 Apr 2026, 06:21 2 Apr 2026, 03:53 1 Apr 2026, 21:12 1 Apr 2026, 18:13 1 Apr 2026, 04:00 1 Apr 2026, 00:11 31 Mar 2026, 21:09 31 Mar 2026, 06:24 31 Mar 2026, 03:56 31 Mar 2026, 00:11 30 Mar 2026, 21:13 30 Mar 2026, 18:15 28 Mar 2026, 18:04 28 Mar 2026, 15:06 27 Mar 2026, 21:09 27 Mar 2026, 18:14 27 Mar 2026, 15:15 27 Mar 2026, 06:21 27 Mar 2026, 03:56 27 Mar 2026, 00:10 26 Mar 2026, 21:07 26 Mar 2026, 18:16 26 Mar 2026, 15:25 26 Mar 2026, 06:21 26 Mar 2026, 03:55 26 Mar 2026, 00:10 25 Mar 2026, 21:08 25 Mar 2026, 18:15 25 Mar 2026, 06:18 25 Mar 2026, 03:47 25 Mar 2026, 00:08 24 Mar 2026, 18:15 24 Mar 2026, 00:07 23 Mar 2026, 21:08 23 Mar 2026, 18:13 23 Mar 2026, 00:09 22 Mar 2026, 18:04 22 Mar 2026, 00:07 21 Mar 2026, 18:03 21 Mar 2026, 00:07 20 Mar 2026, 21:05 20 Mar 2026, 18:08 20 Mar 2026, 15:13 20 Mar 2026, 03:45 20 Mar 2026, 00:08 19 Mar 2026, 06:17 19 Mar 2026, 00:08 18 Mar 2026, 18:16 18 Mar 2026, 12:11 18 Mar 2026, 09:15 18 Mar 2026, 03:50 18 Mar 2026, 00:09 17 Mar 2026, 21:10 17 Mar 2026, 18:15 17 Mar 2026, 03:46 17 Mar 2026, 00:08 16 Mar 2026, 21:10 16 Mar 2026, 18:15 14 Mar 2026, 03:44 14 Mar 2026, 00:08 13 Mar 2026, 21:07 13 Mar 2026, 18:07 13 Mar 2026, 06:12 12 Mar 2026, 21:07 12 Mar 2026, 18:12 12 Mar 2026, 00:07 11 Mar 2026, 03:43 11 Mar 2026, 00:05 10 Mar 2026, 03:43 10 Mar 2026, 00:05 9 Mar 2026, 21:06 7 Mar 2026, 03:37 7 Mar 2026, 00:07 6 Mar 2026, 06:10 6 Mar 2026, 03:44 6 Mar 2026, 00:12 5 Mar 2026, 06:12 5 Mar 2026, 03:45 5 Mar 2026, 00:07 4 Mar 2026, 21:06 4 Mar 2026, 18:09 4 Mar 2026, 09:09 1 Mar 2026, 06:10 1 Mar 2026, 03:49 28 Feb 2026, 21:01 28 Feb 2026, 00:05 27 Feb 2026, 21:05 27 Feb 2026, 18:07 27 Feb 2026, 09:11 27 Feb 2026, 06:13 27 Feb 2026, 00:08 26 Feb 2026, 21:08 26 Feb 2026, 18:12 26 Feb 2026, 09:14 26 Feb 2026, 06:17 26 Feb 2026, 00:07 25 Feb 2026, 03:47 25 Feb 2026, 00:09 24 Feb 2026, 21:08 24 Feb 2026, 18:15 23 Feb 2026, 21:13 21 Feb 2026, 18:03 21 Feb 2026, 06:08 20 Feb 2026, 21:03 20 Feb 2026, 06:14 20 Feb 2026, 00:07 19 Feb 2026, 21:06 19 Feb 2026, 03:48 19 Feb 2026, 00:08 18 Feb 2026, 03:48 17 Feb 2026, 21:08 17 Feb 2026, 00:08 16 Feb 2026, 21:05 14 Feb 2026, 03:44 13 Feb 2026, 21:09 12 Feb 2026, 00:06 11 Feb 2026, 21:10 11 Feb 2026, 00:11 10 Feb 2026, 21:13 10 Feb 2026, 03:56 10 Feb 2026, 00:11 9 Feb 2026, 15:17 9 Feb 2026, 00:08 7 Feb 2026, 21:05 7 Feb 2026, 18:03 7 Feb 2026, 03:43 6 Feb 2026, 21:06 6 Feb 2026, 00:05 5 Feb 2026, 21:06 5 Feb 2026, 18:13 5 Feb 2026, 03:46 5 Feb 2026, 00:07 4 Feb 2026, 21:07 4 Feb 2026, 18:11 4 Feb 2026, 03:45 4 Feb 2026, 00:06 3 Feb 2026, 21:08 3 Feb 2026, 18:14 3 Feb 2026, 09:10 3 Feb 2026, 03:46 1 Feb 2026, 21:03 1 Feb 2026, 18:02 31 Jan 2026, 03:42 31 Jan 2026, 00:06 30 Jan 2026, 18:07 30 Jan 2026, 00:06 29 Jan 2026, 21:03 28 Jan 2026, 15:06 28 Jan 2026, 03:30 28 Jan 2026, 00:05 27 Jan 2026, 21:01 27 Jan 2026, 18:03 27 Jan 2026, 06:02 26 Jan 2026, 21:03 25 Jan 2026, 03:34 24 Jan 2026, 03:29 23 Jan 2026, 21:01 23 Jan 2026, 18:02 23 Jan 2026, 00:05 22 Jan 2026, 21:03 22 Jan 2026, 15:05 22 Jan 2026, 03:31 22 Jan 2026, 00:05 21 Jan 2026, 21:05 21 Jan 2026, 06:02 21 Jan 2026, 03:30 21 Jan 2026, 00:05 20 Jan 2026, 21:03 20 Jan 2026, 18:03 20 Jan 2026, 15:05 20 Jan 2026, 03:30 19 Jan 2026, 21:01 19 Jan 2026, 00:05 16 Jan 2026, 21:01 16 Jan 2026, 18:02 16 Jan 2026, 15:02 16 Jan 2026, 00:05 14 Jan 2026, 06:02 14 Jan 2026, 00:05 12 Jan 2026, 21:02 12 Jan 2026, 18:02 12 Jan 2026, 00:05 11 Jan 2026, 18:02 11 Jan 2026, 03:31 11 Jan 2026, 00:06 10 Jan 2026, 21:01 10 Jan 2026, 03:29 10 Jan 2026, 00:04 9 Jan 2026, 21:01 9 Jan 2026, 00:04 8 Jan 2026, 21:02 8 Jan 2026, 06:02 8 Jan 2026, 03:29 8 Jan 2026, 00:05 7 Jan 2026, 21:01 7 Jan 2026, 18:02 7 Jan 2026, 09:05 7 Jan 2026, 06:02 7 Jan 2026, 03:30 7 Jan 2026, 00:04 6 Jan 2026, 21:01 6 Jan 2026, 03:29 6 Jan 2026, 00:05 3 Jan 2026, 18:02 27 Dec 2025, 06:02 27 Dec 2025, 03:28 23 Dec 2025, 18:02 20 Dec 2025, 00:04 19 Dec 2025, 21:01 19 Dec 2025, 18:02 19 Dec 2025, 00:05 18 Dec 2025, 21:01 18 Dec 2025, 18:02 18 Dec 2025, 15:02 17 Dec 2025, 15:02 17 Dec 2025, 03:27 16 Dec 2025, 21:01 16 Dec 2025, 18:02 16 Dec 2025, 00:05 15 Dec 2025, 21:01 15 Dec 2025, 18:02 13 Dec 2025, 06:02 12 Dec 2025, 21:01 12 Dec 2025, 00:05 11 Dec 2025, 21:02 11 Dec 2025, 18:01 11 Dec 2025, 06:02 10 Dec 2025, 09:03 9 Dec 2025, 18:01 9 Dec 2025, 06:02 9 Dec 2025, 03:25 8 Dec 2025, 21:01 8 Dec 2025, 06:02 8 Dec 2025, 00:05 6 Dec 2025, 18:02 5 Dec 2025, 00:04 4 Dec 2025, 21:02 4 Dec 2025, 18:02 4 Dec 2025, 06:02 4 Dec 2025, 03:26 3 Dec 2025, 00:04 2 Dec 2025, 21:01 2 Dec 2025, 00:04 1 Dec 2025, 03:31 27 Nov 2025, 06:02 27 Nov 2025, 03:20 26 Nov 2025, 00:04 25 Nov 2025, 03:22 24 Nov 2025, 21:01 21 Nov 2025, 00:04 20 Nov 2025, 18:02 20 Nov 2025, 06:02 20 Nov 2025, 03:20 19 Nov 2025, 03:21 19 Nov 2025, 00:05 18 Nov 2025, 18:02 18 Nov 2025, 09:02 18 Nov 2025, 03:21 17 Nov 2025, 03:24 17 Nov 2025, 00:04 16 Nov 2025, 00:04 14 Nov 2025, 21:26 6 Nov 2025, 18:02 6 Nov 2025, 15:02 6 Nov 2025, 12:02 6 Nov 2025, 06:01 6 Nov 2025, 03:22 4 Nov 2025, 18:02 4 Nov 2025, 03:19 4 Nov 2025, 00:04 3 Nov 2025, 21:01 3 Nov 2025, 12:03 3 Nov 2025, 09:02 3 Nov 2025, 06:02 3 Nov 2025, 03:24 3 Nov 2025, 00:04 2 Nov 2025, 18:01 2 Nov 2025, 12:02 2 Nov 2025, 09:01 1 Nov 2025, 21:01 31 Oct 2025, 00:04 30 Oct 2025, 18:02 29 Oct 2025, 21:02 28 Oct 2025, 18:02 27 Oct 2025, 18:02 24 Oct 2025, 21:01 23 Oct 2025, 21:02 23 Oct 2025, 09:02 23 Oct 2025, 06:02 23 Oct 2025, 00:04 21 Oct 2025, 00:04 20 Oct 2025, 21:02 20 Oct 2025, 15:12 20 Oct 2025, 00:05 17 Oct 2025, 18:01 17 Oct 2025, 12:03 16 Oct 2025, 18:02 16 Oct 2025, 00:05 15 Oct 2025, 18:02 13 Oct 2025, 21:01 12 Oct 2025, 18:01
17 Mar 2026, 00:08
12 May 2026, 16:02 12 May 2026, 14:59 12 May 2026, 01:59 12 May 2026, 00:01 11 May 2026, 23:00 11 May 2026, 21:57 11 May 2026, 20:02 11 May 2026, 18:59 11 May 2026, 18:00 11 May 2026, 15:00 10 May 2026, 23:03 10 May 2026, 17:00 10 May 2026, 04:02 9 May 2026, 04:57 9 May 2026, 04:01 9 May 2026, 03:01 8 May 2026, 22:00 8 May 2026, 19:00 8 May 2026, 18:00 8 May 2026, 16:57 8 May 2026, 07:02 8 May 2026, 06:02 8 May 2026, 03:01 8 May 2026, 02:03 8 May 2026, 01:02 8 May 2026, 00:02 7 May 2026, 22:59 7 May 2026, 21:57 7 May 2026, 17:08 5 May 2026, 23:00 5 May 2026, 21:00 5 May 2026, 17:00 5 May 2026, 15:59 5 May 2026, 14:57 5 May 2026, 00:02 4 May 2026, 22:58 4 May 2026, 22:01 4 May 2026, 18:58 4 May 2026, 15:35 4 May 2026, 06:55 4 May 2026, 04:18 2 May 2026, 18:14 2 May 2026, 04:05 2 May 2026, 00:19 1 May 2026, 18:19 1 May 2026, 04:22 1 May 2026, 00:20 29 Apr 2026, 21:21 29 Apr 2026, 15:36 29 Apr 2026, 09:39 29 Apr 2026, 04:11 29 Apr 2026, 00:20 28 Apr 2026, 21:21 28 Apr 2026, 18:28 28 Apr 2026, 15:45 28 Apr 2026, 06:49 27 Apr 2026, 21:20 27 Apr 2026, 18:23 26 Apr 2026, 04:08 25 Apr 2026, 21:10 24 Apr 2026, 18:11 24 Apr 2026, 06:34 24 Apr 2026, 00:17 23 Apr 2026, 18:19 23 Apr 2026, 04:04 23 Apr 2026, 00:17 22 Apr 2026, 21:15 22 Apr 2026, 04:00 22 Apr 2026, 00:13 21 Apr 2026, 21:14 21 Apr 2026, 09:30 21 Apr 2026, 04:01 20 Apr 2026, 21:14 20 Apr 2026, 18:16 18 Apr 2026, 18:09 18 Apr 2026, 00:13 17 Apr 2026, 21:13 17 Apr 2026, 18:14 17 Apr 2026, 00:15 16 Apr 2026, 21:13 16 Apr 2026, 18:21 16 Apr 2026, 15:30 16 Apr 2026, 04:02 16 Apr 2026, 00:16 15 Apr 2026, 18:20 15 Apr 2026, 15:24 15 Apr 2026, 09:29 15 Apr 2026, 04:00 14 Apr 2026, 21:14 14 Apr 2026, 18:21 14 Apr 2026, 06:32 14 Apr 2026, 04:00 14 Apr 2026, 00:16 13 Apr 2026, 21:14 13 Apr 2026, 18:21 11 Apr 2026, 00:11 10 Apr 2026, 21:09 10 Apr 2026, 18:13 10 Apr 2026, 06:32 10 Apr 2026, 00:12 9 Apr 2026, 21:14 9 Apr 2026, 18:17 9 Apr 2026, 15:29 9 Apr 2026, 03:55 9 Apr 2026, 00:09 8 Apr 2026, 21:13 8 Apr 2026, 18:21 8 Apr 2026, 15:27 8 Apr 2026, 00:12 7 Apr 2026, 21:14 4 Apr 2026, 18:05 4 Apr 2026, 03:46 4 Apr 2026, 00:09 3 Apr 2026, 21:07 3 Apr 2026, 18:08 3 Apr 2026, 03:54 3 Apr 2026, 00:11 2 Apr 2026, 21:08 2 Apr 2026, 18:12 2 Apr 2026, 09:19 2 Apr 2026, 06:21 2 Apr 2026, 03:53 1 Apr 2026, 21:12 1 Apr 2026, 18:13 1 Apr 2026, 04:00 1 Apr 2026, 00:11 31 Mar 2026, 21:09 31 Mar 2026, 06:24 31 Mar 2026, 03:56 31 Mar 2026, 00:11 30 Mar 2026, 21:13 30 Mar 2026, 18:15 28 Mar 2026, 18:04 28 Mar 2026, 15:06 27 Mar 2026, 21:09 27 Mar 2026, 18:14 27 Mar 2026, 15:15 27 Mar 2026, 06:21 27 Mar 2026, 03:56 27 Mar 2026, 00:10 26 Mar 2026, 21:07 26 Mar 2026, 18:16 26 Mar 2026, 15:25 26 Mar 2026, 06:21 26 Mar 2026, 03:55 26 Mar 2026, 00:10 25 Mar 2026, 21:08 25 Mar 2026, 18:15 25 Mar 2026, 06:18 25 Mar 2026, 03:47 25 Mar 2026, 00:08 24 Mar 2026, 18:15 24 Mar 2026, 00:07 23 Mar 2026, 21:08 23 Mar 2026, 18:13 23 Mar 2026, 00:09 22 Mar 2026, 18:04 22 Mar 2026, 00:07 21 Mar 2026, 18:03 21 Mar 2026, 00:07 20 Mar 2026, 21:05 20 Mar 2026, 18:08 20 Mar 2026, 15:13 20 Mar 2026, 03:45 20 Mar 2026, 00:08 19 Mar 2026, 06:17 19 Mar 2026, 00:08 18 Mar 2026, 18:16 18 Mar 2026, 12:11 18 Mar 2026, 09:15 18 Mar 2026, 03:50 18 Mar 2026, 00:09 17 Mar 2026, 21:10 17 Mar 2026, 18:15 17 Mar 2026, 03:46 17 Mar 2026, 00:08 16 Mar 2026, 21:10 16 Mar 2026, 18:15 14 Mar 2026, 03:44 14 Mar 2026, 00:08 13 Mar 2026, 21:07 13 Mar 2026, 18:07 13 Mar 2026, 06:12 12 Mar 2026, 21:07 12 Mar 2026, 18:12 12 Mar 2026, 00:07 11 Mar 2026, 03:43 11 Mar 2026, 00:05 10 Mar 2026, 03:43 10 Mar 2026, 00:05 9 Mar 2026, 21:06 7 Mar 2026, 03:37 7 Mar 2026, 00:07 6 Mar 2026, 06:10 6 Mar 2026, 03:44 6 Mar 2026, 00:12 5 Mar 2026, 06:12 5 Mar 2026, 03:45 5 Mar 2026, 00:07 4 Mar 2026, 21:06 4 Mar 2026, 18:09 4 Mar 2026, 09:09 1 Mar 2026, 06:10 1 Mar 2026, 03:49 28 Feb 2026, 21:01 28 Feb 2026, 00:05 27 Feb 2026, 21:05 27 Feb 2026, 18:07 27 Feb 2026, 09:11 27 Feb 2026, 06:13 27 Feb 2026, 00:08 26 Feb 2026, 21:08 26 Feb 2026, 18:12 26 Feb 2026, 09:14 26 Feb 2026, 06:17 26 Feb 2026, 00:07 25 Feb 2026, 03:47 25 Feb 2026, 00:09 24 Feb 2026, 21:08 24 Feb 2026, 18:15 23 Feb 2026, 21:13 21 Feb 2026, 18:03 21 Feb 2026, 06:08 20 Feb 2026, 21:03 20 Feb 2026, 06:14 20 Feb 2026, 00:07 19 Feb 2026, 21:06 19 Feb 2026, 03:48 19 Feb 2026, 00:08 18 Feb 2026, 03:48 17 Feb 2026, 21:08 17 Feb 2026, 00:08 16 Feb 2026, 21:05 14 Feb 2026, 03:44 13 Feb 2026, 21:09 12 Feb 2026, 00:06 11 Feb 2026, 21:10 11 Feb 2026, 00:11 10 Feb 2026, 21:13 10 Feb 2026, 03:56 10 Feb 2026, 00:11 9 Feb 2026, 15:17 9 Feb 2026, 00:08 7 Feb 2026, 21:05 7 Feb 2026, 18:03 7 Feb 2026, 03:43 6 Feb 2026, 21:06 6 Feb 2026, 00:05 5 Feb 2026, 21:06 5 Feb 2026, 18:13 5 Feb 2026, 03:46 5 Feb 2026, 00:07 4 Feb 2026, 21:07 4 Feb 2026, 18:11 4 Feb 2026, 03:45 4 Feb 2026, 00:06 3 Feb 2026, 21:08 3 Feb 2026, 18:14 3 Feb 2026, 09:10 3 Feb 2026, 03:46 1 Feb 2026, 21:03 1 Feb 2026, 18:02 31 Jan 2026, 03:42 31 Jan 2026, 00:06 30 Jan 2026, 18:07 30 Jan 2026, 00:06 29 Jan 2026, 21:03 28 Jan 2026, 15:06 28 Jan 2026, 03:30 28 Jan 2026, 00:05 27 Jan 2026, 21:01 27 Jan 2026, 18:03 27 Jan 2026, 06:02 26 Jan 2026, 21:03 25 Jan 2026, 03:34 24 Jan 2026, 03:29 23 Jan 2026, 21:01 23 Jan 2026, 18:02 23 Jan 2026, 00:05 22 Jan 2026, 21:03 22 Jan 2026, 15:05 22 Jan 2026, 03:31 22 Jan 2026, 00:05 21 Jan 2026, 21:05 21 Jan 2026, 06:02 21 Jan 2026, 03:30 21 Jan 2026, 00:05 20 Jan 2026, 21:03 20 Jan 2026, 18:03 20 Jan 2026, 15:05 20 Jan 2026, 03:30 19 Jan 2026, 21:01 19 Jan 2026, 00:05 16 Jan 2026, 21:01 16 Jan 2026, 18:02 16 Jan 2026, 15:02 16 Jan 2026, 00:05 14 Jan 2026, 06:02 14 Jan 2026, 00:05 12 Jan 2026, 21:02 12 Jan 2026, 18:02 12 Jan 2026, 00:05 11 Jan 2026, 18:02 11 Jan 2026, 03:31 11 Jan 2026, 00:06 10 Jan 2026, 21:01 10 Jan 2026, 03:29 10 Jan 2026, 00:04 9 Jan 2026, 21:01 9 Jan 2026, 00:04 8 Jan 2026, 21:02 8 Jan 2026, 06:02 8 Jan 2026, 03:29 8 Jan 2026, 00:05 7 Jan 2026, 21:01 7 Jan 2026, 18:02 7 Jan 2026, 09:05 7 Jan 2026, 06:02 7 Jan 2026, 03:30 7 Jan 2026, 00:04 6 Jan 2026, 21:01 6 Jan 2026, 03:29 6 Jan 2026, 00:05 3 Jan 2026, 18:02 27 Dec 2025, 06:02 27 Dec 2025, 03:28 23 Dec 2025, 18:02 20 Dec 2025, 00:04 19 Dec 2025, 21:01 19 Dec 2025, 18:02 19 Dec 2025, 00:05 18 Dec 2025, 21:01 18 Dec 2025, 18:02 18 Dec 2025, 15:02 17 Dec 2025, 15:02 17 Dec 2025, 03:27 16 Dec 2025, 21:01 16 Dec 2025, 18:02 16 Dec 2025, 00:05 15 Dec 2025, 21:01 15 Dec 2025, 18:02 13 Dec 2025, 06:02 12 Dec 2025, 21:01 12 Dec 2025, 00:05 11 Dec 2025, 21:02 11 Dec 2025, 18:01 11 Dec 2025, 06:02 10 Dec 2025, 09:03 9 Dec 2025, 18:01 9 Dec 2025, 06:02 9 Dec 2025, 03:25 8 Dec 2025, 21:01 8 Dec 2025, 06:02 8 Dec 2025, 00:05 6 Dec 2025, 18:02 5 Dec 2025, 00:04 4 Dec 2025, 21:02 4 Dec 2025, 18:02 4 Dec 2025, 06:02 4 Dec 2025, 03:26 3 Dec 2025, 00:04 2 Dec 2025, 21:01 2 Dec 2025, 00:04 1 Dec 2025, 03:31 27 Nov 2025, 06:02 27 Nov 2025, 03:20 26 Nov 2025, 00:04 25 Nov 2025, 03:22 24 Nov 2025, 21:01 21 Nov 2025, 00:04 20 Nov 2025, 18:02 20 Nov 2025, 06:02 20 Nov 2025, 03:20 19 Nov 2025, 03:21 19 Nov 2025, 00:05 18 Nov 2025, 18:02 18 Nov 2025, 09:02 18 Nov 2025, 03:21 17 Nov 2025, 03:24 17 Nov 2025, 00:04 16 Nov 2025, 00:04 14 Nov 2025, 21:26 6 Nov 2025, 18:02 6 Nov 2025, 15:02 6 Nov 2025, 12:02 6 Nov 2025, 06:01 6 Nov 2025, 03:22 4 Nov 2025, 18:02 4 Nov 2025, 03:19 4 Nov 2025, 00:04 3 Nov 2025, 21:01 3 Nov 2025, 12:03 3 Nov 2025, 09:02 3 Nov 2025, 06:02 3 Nov 2025, 03:24 3 Nov 2025, 00:04 2 Nov 2025, 18:01 2 Nov 2025, 12:02 2 Nov 2025, 09:01 1 Nov 2025, 21:01 31 Oct 2025, 00:04 30 Oct 2025, 18:02 29 Oct 2025, 21:02 28 Oct 2025, 18:02 27 Oct 2025, 18:02 24 Oct 2025, 21:01 23 Oct 2025, 21:02 23 Oct 2025, 09:02 23 Oct 2025, 06:02 23 Oct 2025, 00:04 21 Oct 2025, 00:04 20 Oct 2025, 21:02 20 Oct 2025, 15:12 20 Oct 2025, 00:05 17 Oct 2025, 18:01 17 Oct 2025, 12:03 16 Oct 2025, 18:02 16 Oct 2025, 00:05 15 Oct 2025, 18:02 13 Oct 2025, 21:01 12 Oct 2025, 18:01
Sun 1 03:49 Sun 1 06:10 Wed 4 09:09 Wed 4 18:09 Wed 4 21:06 Thu 5 00:07 Thu 5 03:45 Thu 5 06:12 Fri 6 00:12 Fri 6 03:44 Fri 6 06:10 Sat 7 00:07 Sat 7 03:37 Mon 9 21:06 Tue 10 00:05 Tue 10 03:43 Wed 11 00:05 Wed 11 03:43 Thu 12 00:07 Thu 12 18:12 Thu 12 21:07 Fri 13 06:12 Fri 13 18:07 Fri 13 21:07 Sat 14 00:08 Sat 14 03:44 Mon 16 18:15 Mon 16 21:10 Tue 17 00:08 Tue 17 03:46 Tue 17 18:15 Tue 17 21:10 Wed 18 00:09 Wed 18 03:50 Wed 18 09:15 Wed 18 12:11 Wed 18 18:16 Thu 19 00:08 Thu 19 06:17 Fri 20 00:08 Fri 20 03:45 Fri 20 15:13 Fri 20 18:08 Fri 20 21:05 Sat 21 00:07 Sat 21 18:03 Sun 22 00:07 Sun 22 18:04 Mon 23 00:09 Mon 23 18:13 Mon 23 21:08 Tue 24 00:07 Tue 24 18:15 Wed 25 00:08 Wed 25 03:47 Wed 25 06:18 Wed 25 18:15 Wed 25 21:08 Thu 26 00:10 Thu 26 03:55 Thu 26 06:21 Thu 26 15:25 Thu 26 18:16 Thu 26 21:07 Fri 27 00:10 Fri 27 03:56 Fri 27 06:21 Fri 27 15:15 Fri 27 18:14 Fri 27 21:09 Sat 28 15:06 Sat 28 18:04 Mon 30 18:15 Mon 30 21:13 Tue 31 00:11 Tue 31 03:56 Tue 31 06:24 Tue 31 21:09

agent-teams.md +403 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Orchestrate teams of Claude Code sessions

6 

7> Coordinate multiple Claude Code instances working together as a team, with shared tasks, inter-agent messaging, and centralized management.

8 

9<Warning>

10 Agent teams are experimental and disabled by default. Enable them by adding `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` to your [settings.json](/en/settings) or environment. Agent teams have [known limitations](#limitations) around session resumption, task coordination, and shutdown behavior.

11</Warning>

12 

13Agent teams let you coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other.

14 

15Unlike [subagents](/en/sub-agents), which run within a single session and can only report back to the main agent, you can also interact with individual teammates directly without going through the lead.

16 

17<Note>

18 Agent teams require Claude Code v2.1.32 or later. Check your version with `claude --version`.

19</Note>

20 

21This page covers:

22 

23* [When to use agent teams](#when-to-use-agent-teams), including best use cases and how they compare with subagents

24* [Starting a team](#start-your-first-agent-team)

25* [Controlling teammates](#control-your-agent-team), including display modes, task assignment, and delegation

26* [Best practices for parallel work](#best-practices)

27 

28## When to use agent teams

29 

30Agent teams are most effective for tasks where parallel exploration adds real value. See [use case examples](#use-case-examples) for full scenarios. The strongest use cases are:

31 

32* **Research and review**: multiple teammates can investigate different aspects of a problem simultaneously, then share and challenge each other's findings

33* **New modules or features**: teammates can each own a separate piece without stepping on each other

34* **Debugging with competing hypotheses**: teammates test different theories in parallel and converge on the answer faster

35* **Cross-layer coordination**: changes that span frontend, backend, and tests, each owned by a different teammate

36 

37Agent teams add coordination overhead and use significantly more tokens than a single session. They work best when teammates can operate independently. For sequential tasks, same-file edits, or work with many dependencies, a single session or [subagents](/en/sub-agents) are more effective.

38 

39### Compare with subagents

40 

41Both agent teams and [subagents](/en/sub-agents) let you parallelize work, but they operate differently. Choose based on whether your workers need to communicate with each other:

42 

43<Frame caption="Subagents only report results back to the main agent and never talk to each other. In agent teams, teammates share a task list, claim work, and communicate directly with each other.">

44 <img src="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=2f8db9b4f3705dd3ab931fbe2d96e42a" className="dark:hidden" alt="Diagram comparing subagent and agent team architectures. Subagents are spawned by the main agent, do work, and report results back. Agent teams coordinate through a shared task list, with teammates communicating directly with each other." width="4245" height="1615" data-path="images/subagents-vs-agent-teams-light.png" />

45 

46 <img src="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=d573a037540f2ada6a9ae7d8285b46fd" className="hidden dark:block" alt="Diagram comparing subagent and agent team architectures. Subagents are spawned by the main agent, do work, and report results back. Agent teams coordinate through a shared task list, with teammates communicating directly with each other." width="4245" height="1615" data-path="images/subagents-vs-agent-teams-dark.png" />

47</Frame>

48 

49| | Subagents | Agent teams |

50| :---------------- | :----------------------------------------------- | :-------------------------------------------------- |

51| **Context** | Own context window; results return to the caller | Own context window; fully independent |

52| **Communication** | Report results back to the main agent only | Teammates message each other directly |

53| **Coordination** | Main agent manages all work | Shared task list with self-coordination |

54| **Best for** | Focused tasks where only the result matters | Complex work requiring discussion and collaboration |

55| **Token cost** | Lower: results summarized back to main context | Higher: each teammate is a separate Claude instance |

56 

57Use subagents when you need quick, focused workers that report back. Use agent teams when teammates need to share findings, challenge each other, and coordinate on their own.

58 

59## Enable agent teams

60 

61Agent teams are disabled by default. Enable them by setting the `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` environment variable to `1`, either in your shell environment or through [settings.json](/en/settings):

62 

63```json settings.json theme={null}

64{

65 "env": {

66 "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"

67 }

68}

69```

70 

71## Start your first agent team

72 

73After enabling agent teams, tell Claude to create an agent team and describe the task and the team structure you want in natural language. Claude creates the team, spawns teammates, and coordinates work based on your prompt.

74 

75This example works well because the three roles are independent and can explore the problem without waiting on each other:

76 

77```text theme={null}

78I'm designing a CLI tool that helps developers track TODO comments across

79their codebase. Create an agent team to explore this from different angles: one

80teammate on UX, one on technical architecture, one playing devil's advocate.

81```

82 

83From there, Claude creates a team with a [shared task list](/en/interactive-mode#task-list), spawns teammates for each perspective, has them explore the problem, synthesizes findings, and attempts to [clean up the team](#clean-up-the-team) when finished.

84 

85The lead's terminal lists all teammates and what they're working on. Use Shift+Down to cycle through teammates and message them directly. After the last teammate, Shift+Down wraps back to the lead.

86 

87If you want each teammate in its own split pane, see [Choose a display mode](#choose-a-display-mode).

88 

89## Control your agent team

90 

91Tell the lead what you want in natural language. It handles team coordination, task assignment, and delegation based on your instructions.

92 

93### Choose a display mode

94 

95Agent teams support two display modes:

96 

97* **In-process**: all teammates run inside your main terminal. Use Shift+Down to cycle through teammates and type to message them directly. Works in any terminal, no extra setup required.

98* **Split panes**: each teammate gets its own pane. You can see everyone's output at once and click into a pane to interact directly. Requires tmux, or iTerm2.

99 

100<Note>

101 `tmux` has known limitations on certain operating systems and traditionally works best on macOS. Using `tmux -CC` in iTerm2 is the suggested entrypoint into `tmux`.

102</Note>

103 

104The default is `"auto"`, which uses split panes if you're already running inside a tmux session, and in-process otherwise. The `"tmux"` setting enables split-pane mode and auto-detects whether to use tmux or iTerm2 based on your terminal. To override, set `teammateMode` in your [settings.json](/en/settings):

105 

106```json theme={null}

107{

108 "teammateMode": "in-process"

109}

110```

111 

112To force in-process mode for a single session, pass it as a flag:

113 

114```bash theme={null}

115claude --teammate-mode in-process

116```

117 

118Split-pane mode requires either [tmux](https://github.com/tmux/tmux/wiki) or iTerm2 with the [`it2` CLI](https://github.com/mkusaka/it2). To install manually:

119 

120* **tmux**: install through your system's package manager. See the [tmux wiki](https://github.com/tmux/tmux/wiki/Installing) for platform-specific instructions.

121* **iTerm2**: install the [`it2` CLI](https://github.com/mkusaka/it2), then enable the Python API in **iTerm2 → Settings → General → Magic → Enable Python API**.

122 

123### Specify teammates and models

124 

125Claude decides the number of teammates to spawn based on your task, or you can specify exactly what you want:

126 

127```text theme={null}

128Create a team with 4 teammates to refactor these modules in parallel.

129Use Sonnet for each teammate.

130```

131 

132### Require plan approval for teammates

133 

134For complex or risky tasks, you can require teammates to plan before implementing. The teammate works in read-only plan mode until the lead approves their approach:

135 

136```text theme={null}

137Spawn an architect teammate to refactor the authentication module.

138Require plan approval before they make any changes.

139```

140 

141When a teammate finishes planning, it sends a plan approval request to the lead. The lead reviews the plan and either approves it or rejects it with feedback. If rejected, the teammate stays in plan mode, revises based on the feedback, and resubmits. Once approved, the teammate exits plan mode and begins implementation.

142 

143The lead makes approval decisions autonomously. To influence the lead's judgment, give it criteria in your prompt, such as "only approve plans that include test coverage" or "reject plans that modify the database schema."

144 

145### Talk to teammates directly

146 

147Each teammate is a full, independent Claude Code session. You can message any teammate directly to give additional instructions, ask follow-up questions, or redirect their approach.

148 

149* **In-process mode**: use Shift+Down to cycle through teammates, then type to send them a message. Press Enter to view a teammate's session, then Escape to interrupt their current turn. Press Ctrl+T to toggle the task list.

150* **Split-pane mode**: click into a teammate's pane to interact with their session directly. Each teammate has a full view of their own terminal.

151 

152### Assign and claim tasks

153 

154The shared task list coordinates work across the team. The lead creates tasks and teammates work through them. Tasks have three states: pending, in progress, and completed. Tasks can also depend on other tasks: a pending task with unresolved dependencies cannot be claimed until those dependencies are completed.

155 

156The lead can assign tasks explicitly, or teammates can self-claim:

157 

158* **Lead assigns**: tell the lead which task to give to which teammate

159* **Self-claim**: after finishing a task, a teammate picks up the next unassigned, unblocked task on its own

160 

161Task claiming uses file locking to prevent race conditions when multiple teammates try to claim the same task simultaneously.

162 

163### Shut down teammates

164 

165To gracefully end a teammate's session:

166 

167```text theme={null}

168Ask the researcher teammate to shut down

169```

170 

171The lead sends a shutdown request. The teammate can approve, exiting gracefully, or reject with an explanation.

172 

173### Clean up the team

174 

175When you're done, ask the lead to clean up:

176 

177```text theme={null}

178Clean up the team

179```

180 

181This removes the shared team resources. When the lead runs cleanup, it checks for active teammates and fails if any are still running, so shut them down first.

182 

183<Warning>

184 Always use the lead to clean up. Teammates should not run cleanup because their team context may not resolve correctly, potentially leaving resources in an inconsistent state.

185</Warning>

186 

187### Enforce quality gates with hooks

188 

189Use [hooks](/en/hooks) to enforce rules when teammates finish work or tasks complete:

190 

191* [`TeammateIdle`](/en/hooks#teammateidle): runs when a teammate is about to go idle. Exit with code 2 to send feedback and keep the teammate working.

192* [`TaskCompleted`](/en/hooks#taskcompleted): runs when a task is being marked complete. Exit with code 2 to prevent completion and send feedback.

193 

194## How agent teams work

195 

196This section covers the architecture and mechanics behind agent teams. If you want to start using them, see [Control your agent team](#control-your-agent-team) above.

197 

198### How Claude starts agent teams

199 

200There are two ways agent teams get started:

201 

202* **You request a team**: give Claude a task that benefits from parallel work and explicitly ask for an agent team. Claude creates one based on your instructions.

203* **Claude proposes a team**: if Claude determines your task would benefit from parallel work, it may suggest creating a team. You confirm before it proceeds.

204 

205In both cases, you stay in control. Claude won't create a team without your approval.

206 

207### Architecture

208 

209An agent team consists of:

210 

211| Component | Role |

212| :------------ | :----------------------------------------------------------------------------------------- |

213| **Team lead** | The main Claude Code session that creates the team, spawns teammates, and coordinates work |

214| **Teammates** | Separate Claude Code instances that each work on assigned tasks |

215| **Task list** | Shared list of work items that teammates claim and complete |

216| **Mailbox** | Messaging system for communication between agents |

217 

218See [Choose a display mode](#choose-a-display-mode) for display configuration options. Teammate messages arrive at the lead automatically.

219 

220The system manages task dependencies automatically. When a teammate completes a task that other tasks depend on, blocked tasks unblock without manual intervention.

221 

222Teams and tasks are stored locally:

223 

224* **Team config**: `~/.claude/teams/{team-name}/config.json`

225* **Task list**: `~/.claude/tasks/{team-name}/`

226 

227The team config contains a `members` array with each teammate's name, agent ID, and agent type. Teammates can read this file to discover other team members.

228 

229### Permissions

230 

231Teammates start with the lead's permission settings. If the lead runs with `--dangerously-skip-permissions`, all teammates do too. After spawning, you can change individual teammate modes, but you can't set per-teammate modes at spawn time.

232 

233### Context and communication

234 

235Each teammate has its own context window. When spawned, a teammate loads the same project context as a regular session: CLAUDE.md, MCP servers, and skills. It also receives the spawn prompt from the lead. The lead's conversation history does not carry over.

236 

237**How teammates share information:**

238 

239* **Automatic message delivery**: when teammates send messages, they're delivered automatically to recipients. The lead doesn't need to poll for updates.

240* **Idle notifications**: when a teammate finishes and stops, they automatically notify the lead.

241* **Shared task list**: all agents can see task status and claim available work.

242 

243**Teammate messaging:**

244 

245* **message**: send a message to one specific teammate

246* **broadcast**: send to all teammates simultaneously. Use sparingly, as costs scale with team size.

247 

248### Token usage

249 

250Agent teams use significantly more tokens than a single session. Each teammate has its own context window, and token usage scales with the number of active teammates. For research, review, and new feature work, the extra tokens are usually worthwhile. For routine tasks, a single session is more cost-effective. See [agent team token costs](/en/costs#agent-team-token-costs) for usage guidance.

251 

252## Use case examples

253 

254These examples show how agent teams handle tasks where parallel exploration adds value.

255 

256### Run a parallel code review

257 

258A single reviewer tends to gravitate toward one type of issue at a time. Splitting review criteria into independent domains means security, performance, and test coverage all get thorough attention simultaneously. The prompt assigns each teammate a distinct lens so they don't overlap:

259 

260```text theme={null}

261Create an agent team to review PR #142. Spawn three reviewers:

262- One focused on security implications

263- One checking performance impact

264- One validating test coverage

265Have them each review and report findings.

266```

267 

268Each reviewer works from the same PR but applies a different filter. The lead synthesizes findings across all three after they finish.

269 

270### Investigate with competing hypotheses

271 

272When the root cause is unclear, a single agent tends to find one plausible explanation and stop looking. The prompt fights this by making teammates explicitly adversarial: each one's job is not only to investigate its own theory but to challenge the others'.

273 

274```text theme={null}

275Users report the app exits after one message instead of staying connected.

276Spawn 5 agent teammates to investigate different hypotheses. Have them talk to

277each other to try to disprove each other's theories, like a scientific

278debate. Update the findings doc with whatever consensus emerges.

279```

280 

281The debate structure is the key mechanism here. Sequential investigation suffers from anchoring: once one theory is explored, subsequent investigation is biased toward it.

282 

283With multiple independent investigators actively trying to disprove each other, the theory that survives is much more likely to be the actual root cause.

284 

285## Best practices

286 

287### Give teammates enough context

288 

289Teammates load project context automatically, including CLAUDE.md, MCP servers, and skills, but they don't inherit the lead's conversation history. See [Context and communication](#context-and-communication) for details. Include task-specific details in the spawn prompt:

290 

291```text theme={null}

292Spawn a security reviewer teammate with the prompt: "Review the authentication module

293at src/auth/ for security vulnerabilities. Focus on token handling, session

294management, and input validation. The app uses JWT tokens stored in

295httpOnly cookies. Report any issues with severity ratings."

296```

297 

298### Choose an appropriate team size

299 

300There's no hard limit on the number of teammates, but practical constraints apply:

301 

302* **Token costs scale linearly**: each teammate has its own context window and consumes tokens independently. See [agent team token costs](/en/costs#agent-team-token-costs) for details.

303* **Coordination overhead increases**: more teammates means more communication, task coordination, and potential for conflicts

304* **Diminishing returns**: beyond a certain point, additional teammates don't speed up work proportionally

305 

306Start with 3-5 teammates for most workflows. This balances parallel work with manageable coordination. The examples in this guide use 3-5 teammates because that range works well across different task types.

307 

308Having 5-6 [tasks](/en/agent-teams#architecture) per teammate keeps everyone productive without excessive context switching. If you have 15 independent tasks, 3 teammates is a good starting point.

309 

310Scale up only when the work genuinely benefits from having teammates work simultaneously. Three focused teammates often outperform five scattered ones.

311 

312### Size tasks appropriately

313 

314* **Too small**: coordination overhead exceeds the benefit

315* **Too large**: teammates work too long without check-ins, increasing risk of wasted effort

316* **Just right**: self-contained units that produce a clear deliverable, such as a function, a test file, or a review

317 

318<Tip>

319 The lead breaks work into tasks and assigns them to teammates automatically. If it isn't creating enough tasks, ask it to split the work into smaller pieces. Having 5-6 tasks per teammate keeps everyone productive and lets the lead reassign work if someone gets stuck.

320</Tip>

321 

322### Wait for teammates to finish

323 

324Sometimes the lead starts implementing tasks itself instead of waiting for teammates. If you notice this:

325 

326```text theme={null}

327Wait for your teammates to complete their tasks before proceeding

328```

329 

330### Start with research and review

331 

332If you're new to agent teams, start with tasks that have clear boundaries and don't require writing code: reviewing a PR, researching a library, or investigating a bug. These tasks show the value of parallel exploration without the coordination challenges that come with parallel implementation.

333 

334### Avoid file conflicts

335 

336Two teammates editing the same file leads to overwrites. Break the work so each teammate owns a different set of files.

337 

338### Monitor and steer

339 

340Check in on teammates' progress, redirect approaches that aren't working, and synthesize findings as they come in. Letting a team run unattended for too long increases the risk of wasted effort.

341 

342## Troubleshooting

343 

344### Teammates not appearing

345 

346If teammates aren't appearing after you ask Claude to create a team:

347 

348* In in-process mode, teammates may already be running but not visible. Press Shift+Down to cycle through active teammates.

349* Check that the task you gave Claude was complex enough to warrant a team. Claude decides whether to spawn teammates based on the task.

350* If you explicitly requested split panes, ensure tmux is installed and available in your PATH:

351 ```bash theme={null}

352 which tmux

353 ```

354* For iTerm2, verify the `it2` CLI is installed and the Python API is enabled in iTerm2 preferences.

355 

356### Too many permission prompts

357 

358Teammate permission requests bubble up to the lead, which can create friction. Pre-approve common operations in your [permission settings](/en/permissions) before spawning teammates to reduce interruptions.

359 

360### Teammates stopping on errors

361 

362Teammates may stop after encountering errors instead of recovering. Check their output using Shift+Down in in-process mode or by clicking the pane in split mode, then either:

363 

364* Give them additional instructions directly

365* Spawn a replacement teammate to continue the work

366 

367### Lead shuts down before work is done

368 

369The lead may decide the team is finished before all tasks are actually complete. If this happens, tell it to keep going. You can also tell the lead to wait for teammates to finish before proceeding if it starts doing work instead of delegating.

370 

371### Orphaned tmux sessions

372 

373If a tmux session persists after the team ends, it may not have been fully cleaned up. List sessions and kill the one created by the team:

374 

375```bash theme={null}

376tmux ls

377tmux kill-session -t <session-name>

378```

379 

380## Limitations

381 

382Agent teams are experimental. Current limitations to be aware of:

383 

384* **No session resumption with in-process teammates**: `/resume` and `/rewind` do not restore in-process teammates. After resuming a session, the lead may attempt to message teammates that no longer exist. If this happens, tell the lead to spawn new teammates.

385* **Task status can lag**: teammates sometimes fail to mark tasks as completed, which blocks dependent tasks. If a task appears stuck, check whether the work is actually done and update the task status manually or tell the lead to nudge the teammate.

386* **Shutdown can be slow**: teammates finish their current request or tool call before shutting down, which can take time.

387* **One team per session**: a lead can only manage one team at a time. Clean up the current team before starting a new one.

388* **No nested teams**: teammates cannot spawn their own teams or teammates. Only the lead can manage the team.

389* **Lead is fixed**: the session that creates the team is the lead for its lifetime. You can't promote a teammate to lead or transfer leadership.

390* **Permissions set at spawn**: all teammates start with the lead's permission mode. You can change individual teammate modes after spawning, but you can't set per-teammate modes at spawn time.

391* **Split panes require tmux or iTerm2**: the default in-process mode works in any terminal. Split-pane mode isn't supported in VS Code's integrated terminal, Windows Terminal, or Ghostty.

392 

393<Tip>

394 **`CLAUDE.md` works normally**: teammates read `CLAUDE.md` files from their working directory. Use this to provide project-specific guidance to all teammates.

395</Tip>

396 

397## Next steps

398 

399Explore related approaches for parallel work and delegation:

400 

401* **Lightweight delegation**: [subagents](/en/sub-agents) spawn helper agents for research or verification within your session, better for tasks that don't need inter-agent coordination

402* **Manual parallel sessions**: [Git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) let you run multiple Claude Code sessions yourself without automated team coordination

403* **Compare approaches**: see the [subagent vs agent team](/en/features-overview#compare-similar-features) comparison for a side-by-side breakdown

amazon-bedrock.md +44 −28

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code on Amazon Bedrock5# Claude Code on Amazon Bedrock

2 6 

3> Learn about configuring Claude Code through Amazon Bedrock, including setup, IAM configuration, and troubleshooting.7> Learn about configuring Claude Code through Amazon Bedrock, including setup, IAM configuration, and troubleshooting.


7Before configuring Claude Code with Bedrock, ensure you have:11Before configuring Claude Code with Bedrock, ensure you have:

8 12 

9* An AWS account with Bedrock access enabled13* An AWS account with Bedrock access enabled

10* Access to desired Claude models (for example, Claude Sonnet 4.5) in Bedrock14* Access to desired Claude models (for example, Claude Sonnet 4.6) in Bedrock

11* AWS CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials)15* AWS CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials)

12* Appropriate IAM permissions16* Appropriate IAM permissions

13 17 

18<Note>

19 If you are deploying Claude Code to multiple users, [pin your model versions](#4-pin-model-versions) to prevent breakage when Anthropic releases new models.

20</Note>

21 

14## Setup22## Setup

15 23 

16### 1. Submit use case details24### 1. Submit use case details


116* When using Bedrock, the `/login` and `/logout` commands are disabled since authentication is handled through AWS credentials.124* When using Bedrock, the `/login` and `/logout` commands are disabled since authentication is handled through AWS credentials.

117* You can use settings files for environment variables like `AWS_PROFILE` that you don't want to leak to other processes. See [Settings](/en/settings) for more information.125* You can use settings files for environment variables like `AWS_PROFILE` that you don't want to leak to other processes. See [Settings](/en/settings) for more information.

118 126 

119### 4. Model configuration127### 4. Pin model versions

128 

129<Warning>

130 Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn't available in your Bedrock account, breaking existing users when Anthropic releases updates.

131</Warning>

132 

133Set these environment variables to specific Bedrock model IDs:

120 134 

121Claude Code uses these default models for Bedrock:135```bash theme={null}

136export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'

137export ANTHROPIC_DEFAULT_SONNET_MODEL='us.anthropic.claude-sonnet-4-6'

138export ANTHROPIC_DEFAULT_HAIKU_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'

139```

140 

141These variables use cross-region inference profile IDs (with the `us.` prefix). If you use a different region prefix or application inference profiles, adjust accordingly. For current and legacy model IDs, see [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables.

142 

143Claude Code uses these default models when no pinning variables are set:

122 144 

123| Model type | Default value |145| Model type | Default value |

124| :--------------- | :------------------------------------------------- |146| :--------------- | :-------------------------------------------- |

125| Primary model | `global.anthropic.claude-sonnet-4-5-20250929-v1:0` |147| Primary model | `global.anthropic.claude-sonnet-4-6` |

126| Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` |148| Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` |

127 149 

128<Note>150To customize models further, use one of these methods:

129 For Bedrock users, Claude Code won't automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `us.anthropic.claude-haiku-4-5-20251001-v1:0`).

130</Note>

131 

132To customize models, use one of these methods:

133 151 

134```bash theme={null}152```bash theme={null}

135# Using inference profile ID153# Using inference profile ID

136export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-5-20250929-v1:0'154export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-6'

137export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'155export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'

138 156 

139# Using application inference profile ARN157# Using application inference profile ARN


143export DISABLE_PROMPT_CACHING=1161export DISABLE_PROMPT_CACHING=1

144```162```

145 163 

146<Note>[Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) may not be available in all regions.</Note>164<Note>[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) may not be available in all regions.</Note>

147 

148### 5. Output token configuration

149 165 

150These are the recommended token settings for Claude Code with Amazon Bedrock:166#### Map each model version to an inference profile

151 167 

152```bash theme={null}168The `ANTHROPIC_DEFAULT_*_MODEL` environment variables configure one inference profile per model family. If your organization needs to expose several versions of the same family in the `/model` picker, each routed to its own application inference profile ARN, use the `modelOverrides` setting in your [settings file](/en/settings#settings-files) instead.

153# Recommended output token settings for Bedrock

154export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096

155export MAX_THINKING_TOKENS=1024

156```

157 169 

158**Why these values:**170This example maps three Opus versions to distinct ARNs so users can switch between them without bypassing your organization's inference profiles:

159 171 

160* **`CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096`**: Bedrock's burndown throttling logic sets a minimum of 4096 tokens as the `max_token` penalty. Setting this lower won't reduce costs but may cut off long tool uses, causing the Claude Code agent loop to fail persistently. Claude Code typically uses less than 4096 output tokens without extended thinking, but may need this headroom for tasks involving significant file creation or Write tool usage.172```json theme={null}

173{

174 "modelOverrides": {

175 "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-46-prod",

176 "claude-opus-4-5-20251101": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-45-prod",

177 "claude-opus-4-1-20250805": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-41-prod"

178 }

179}

180```

161 181 

162* **`MAX_THINKING_TOKENS=1024`**: This provides space for extended thinking without cutting off tool use responses, while still maintaining focused reasoning chains. This balance helps prevent trajectory changes that aren't always helpful for coding tasks specifically.182When a user selects one of these versions in `/model`, Claude Code calls Bedrock with the mapped ARN. Versions without an override fall back to the built-in Bedrock model ID or any matching inference profile discovered at startup. See [Override model IDs per version](/en/model-config#override-model-ids-per-version) for details on how overrides interact with `availableModels` and other model settings.

163 183 

164## IAM configuration184## IAM configuration

165 185 


206For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).226For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).

207 227 

208<Note>228<Note>

209 We recommend creating a dedicated AWS account for Claude Code to simplify cost tracking and access control.229 Create a dedicated AWS account for Claude Code to simplify cost tracking and access control.

210</Note>230</Note>

211 231 

212## AWS Guardrails232## AWS Guardrails


243* [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)263* [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)

244* [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)264* [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)

245* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)- [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)265* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)- [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)

246 

247 

248 

249> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

analytics.md +180 −47

Details

1# Analytics1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> View detailed usage insights and productivity metrics for your organization's Claude Code deployment.5# Track team usage with analytics

4 6 

5Claude Code provides an analytics dashboard that helps organizations understand developer usage patterns, track productivity metrics, and optimize their Claude Code adoption.7> View Claude Code usage metrics, track adoption, and measure engineering velocity in the analytics dashboard.

8 

9Claude Code provides analytics dashboards to help organizations understand developer usage patterns, track contribution metrics, and measure how Claude Code impacts engineering velocity. Access the dashboard for your plan:

10 

11| Plan | Dashboard URL | Includes | Read more |

12| ----------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------- |

13| Claude for Teams / Enterprise | [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code) | Usage metrics, contribution metrics with GitHub integration, leaderboard, data export | [Details](#access-analytics-for-teams-and-enterprise) |

14| API (Claude Console) | [platform.claude.com/claude-code](https://platform.claude.com/claude-code) | Usage metrics, spend tracking, team insights | [Details](#access-analytics-for-api-customers) |

15 

16## Access analytics for Teams and Enterprise

17 

18Navigate to [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code). Admins and Owners can view the dashboard.

19 

20The Teams and Enterprise dashboard includes:

21 

22* **Usage metrics**: lines of code accepted, suggestion accept rate, daily active users and sessions

23* **Contribution metrics**: PRs and lines of code shipped with Claude Code assistance, with [GitHub integration](#enable-contribution-metrics)

24* **Leaderboard**: top contributors ranked by Claude Code usage

25* **Data export**: download contribution data as CSV for custom reporting

26 

27### Enable contribution metrics

6 28 

7<Note>29<Note>

8 Analytics are currently available only for organizations using Claude Code with the Claude API through the Claude Console.30 Contribution metrics are in public beta and available on Claude for Teams and Claude for Enterprise plans. These metrics only cover users within your claude.ai organization. Usage through the Claude Console API or third-party integrations is not included.

9</Note>31</Note>

10 32 

11## Access analytics33Usage and adoption data is available for all Claude for Teams and Claude for Enterprise accounts. Contribution metrics require additional setup to connect your GitHub organization.

34 

35You need the Owner role to configure analytics settings. A GitHub admin must install the GitHub app.

36 

37<Warning>

38 Contribution metrics are not available for organizations with [Zero Data Retention](/en/zero-data-retention) enabled. The analytics dashboard will show usage metrics only.

39</Warning>

40 

41<Steps>

42 <Step title="Install the GitHub app">

43 A GitHub admin installs the Claude GitHub app on your organization's GitHub account at [github.com/apps/claude](https://github.com/apps/claude).

44 </Step>

45 

46 <Step title="Enable Claude Code analytics">

47 A Claude Owner navigates to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and enables the Claude Code analytics feature.

48 </Step>

49 

50 <Step title="Enable GitHub analytics">

51 On the same page, enable the "GitHub analytics" toggle.

52 </Step>

53 

54 <Step title="Authenticate with GitHub">

55 Complete the GitHub authentication flow and select which GitHub organizations to include in the analysis.

56 </Step>

57</Steps>

12 58 

13Navigate to the analytics dashboard at [console.anthropic.com/claude-code](https://console.anthropic.com/claude-code).59Data typically appears within 24 hours after enabling, with daily updates. If no data appears, you may see one of these messages:

14 60 

15### Required roles61* **"GitHub app required"**: install the GitHub app to view contribution metrics

62* **"Data processing in progress"**: check back in a few days and confirm the GitHub app is installed if data doesn't appear

16 63 

17* **Primary Owner**64Contribution metrics support GitHub Cloud and GitHub Enterprise Server.

18* **Owner**65 

19* **Billing**66### Review summary metrics

20* **Admin**

21* **Developer**

22 67 

23<Note>68<Note>

24 Users with **User**, **Claude Code User** or **Membership Admin** roles cannot access analytics.69 These metrics are deliberately conservative and represent an underestimate of Claude Code's actual impact. Only lines and PRs where there is high confidence in Claude Code's involvement are counted.

25</Note>70</Note>

26 71 

27## Available metrics72The dashboard displays these summary metrics at the top:

73 

74* **PRs with CC**: total count of merged pull requests that contain at least one line of code written with Claude Code

75* **Lines of code with CC**: total lines of code across all merged PRs that were written with Claude Code assistance. Only "effective lines" are counted: lines with more than 3 characters after normalization, excluding empty lines and lines with only brackets or trivial punctuation.

76* **PRs with Claude Code (%)**: percentage of all merged PRs that contain Claude Code-assisted code

77* **Suggestion accept rate**: percentage of times users accept Claude Code's code editing suggestions, including Edit, Write, and NotebookEdit tool usage

78* **Lines of code accepted**: total lines of code written by Claude Code that users have accepted in their sessions. This excludes rejected suggestions and does not track subsequent deletions.

79 

80### Explore the charts

81 

82The dashboard includes several charts to visualize trends over time.

83 

84#### Track adoption

85 

86The Adoption chart shows daily usage trends:

87 

88* **users**: daily active users

89* **sessions**: number of active Claude Code sessions per day

90 

91#### Measure PRs per user

92 

93This chart displays individual developer activity over time:

94 

95* **PRs per user**: total number of PRs merged per day divided by daily active users

96* **users**: daily active users

97 

98Use this to understand how individual productivity changes as Claude Code adoption increases.

99 

100#### View pull requests breakdown

28 101 

29### Lines of code accepted102The Pull requests chart shows a daily breakdown of merged PRs:

30 103 

31Total lines of code written by Claude Code that users have accepted in their sessions.104* **PRs with CC**: pull requests containing Claude Code-assisted code

105* **PRs without CC**: pull requests without Claude Code-assisted code

32 106 

33* Excludes rejected code suggestions107Toggle to **Lines of code** view to see the same breakdown by lines of code rather than PR count.

34* Doesn't track subsequent deletions

35 108 

36### Suggestion accept rate109#### Find top contributors

37 110 

38Percentage of times users accept code editing tool usage, including:111The Leaderboard shows the top 10 users ranked by contribution volume. Toggle between:

39 112 

40* Edit113* **Pull requests**: shows PRs with Claude Code vs All PRs for each user

41* Write114* **Lines of code**: shows lines with Claude Code vs All lines for each user

42* NotebookEdit

43 115 

44### Activity116Click **Export all users** to download complete contribution data for all users as a CSV file. The export includes all users, not just the top 10 displayed.

45 117 

46**users**: Number of active users in a given day (number on left Y-axis)118### PR attribution

47 119 

48**sessions**: Number of active sessions in a given day (number on right Y-axis)120When contribution metrics are enabled, Claude Code analyzes merged pull requests to determine which code was written with Claude Code assistance. This is done by matching Claude Code session activity against the code in each PR.

49 121 

50### Spend122#### Tagging criteria

51 123 

52**users**: Number of active users in a given day (number on left Y-axis)124PRs are tagged as "with Claude Code" if they contain at least one line of code written during a Claude Code session. The system uses conservative matching: only code where there is high confidence in Claude Code's involvement is counted as assisted.

53 125 

54**spend**: Total dollars spent in a given day (number on right Y-axis)126#### Attribution process

55 127 

56### Team insights128When a pull request is merged:

57 129 

58**Members**: All users who have authenticated to Claude Code1301. Added lines are extracted from the PR diff

1312. Claude Code sessions that edited matching files within a time window are identified

1323. PR lines are matched against Claude Code output using multiple strategies

1334. Metrics are calculated for AI-assisted lines and total lines

59 134 

60* API key users are displayed by **API key identifier**135Before comparison, lines are normalized: whitespace is trimmed, multiple spaces are collapsed, quotes are standardized, and text is converted to lowercase.

61* OAuth users are displayed by **email address**

62 136 

63**Spend this month:** Per-user total spend for the current month.137Merged pull requests containing Claude Code-assisted lines are labeled as `claude-code-assisted` in GitHub.

64 138 

65**Lines this month:** Per-user total of accepted code lines for the current month.139#### Time window

66 140 

67## Using analytics effectively141Sessions from 21 days before to 2 days after the PR merge date are considered for attribution matching.

68 142 

69### Monitor adoption143#### Excluded files

70 144 

71Track team member status to identify:145Certain files are automatically excluded from analysis because they are auto-generated:

146 

147* Lock files: package-lock.json, yarn.lock, Cargo.lock, and similar

148* Generated code: Protobuf outputs, build artifacts, minified files

149* Build directories: dist/, build/, node\_modules/, target/

150* Test fixtures: snapshots, cassettes, mock data

151* Lines over 1,000 characters, which are likely minified or generated

152 

153#### Attribution notes

154 

155Keep these additional details in mind when interpreting attribution data:

156 

157* Code substantially rewritten by developers, with more than 20% difference, is not attributed to Claude Code

158* Sessions outside the 21-day window are not considered

159* The algorithm does not consider the PR source or destination branch when performing attribution

160 

161### Get the most from analytics

162 

163Use contribution metrics to demonstrate ROI, identify adoption patterns, and find team members who can help others get started.

164 

165#### Monitor adoption

166 

167Track the Adoption chart and user counts to identify:

72 168 

73* Active users who can share best practices169* Active users who can share best practices

74* Overall adoption trends across your organization170* Overall adoption trends across your organization

171* Dips in usage that may indicate friction or issues

75 172 

76### Measure productivity173#### Measure ROI

77 174 

78Tool acceptance rates and code metrics help you:175Contribution metrics help answer "Is this tool worth the investment?" with data from your own codebase:

79 176 

80* Understand developer satisfaction with Claude Code suggestions177* Track changes in PRs per user over time as adoption increases

81* Track code generation effectiveness178* Compare PRs and lines of code shipped with vs. without Claude Code

82* Identify opportunities for training or process improvements179* Use alongside [DORA metrics](https://dora.dev/), sprint velocity, or other engineering KPIs to understand changes from adopting Claude Code

83 180 

84## Related resources181#### Identify power users

182 

183The Leaderboard helps you find team members with high Claude Code adoption who can:

184 

185* Share prompting techniques and workflows with the team

186* Provide feedback on what's working well

187* Help onboard new users

188 

189#### Access data programmatically

190 

191To query this data through GitHub, search for PRs labeled with `claude-code-assisted`.

85 192 

86* [Monitoring usage with OpenTelemetry](/en/monitoring-usage) for custom metrics and alerting193## Access analytics for API customers

87* [Identity and access management](/en/iam) for role configuration

88 194 

195API customers using the Claude Console can access analytics at [platform.claude.com/claude-code](https://platform.claude.com/claude-code). You need the UsageView permission to access the dashboard, which is granted to Developer, Billing, Admin, Owner, and Primary Owner roles.

89 196 

197<Note>

198 Contribution metrics with GitHub integration are not currently available for API customers. The Console dashboard shows usage and spend metrics only.

199</Note>

200 

201The Console dashboard displays:

202 

203* **Lines of code accepted**: total lines of code written by Claude Code that users have accepted in their sessions. This excludes rejected suggestions and does not track subsequent deletions.

204* **Suggestion accept rate**: percentage of times users accept code editing tool usage, including Edit, Write, and NotebookEdit tools.

205* **Activity**: daily active users and sessions shown on a chart.

206* **Spend**: daily API costs in dollars alongside user count.

207 

208### View team insights

209 

210The team insights table shows per-user metrics:

211 

212* **Members**: all users who have authenticated to Claude Code. API key users display by key identifier, OAuth users display by email address.

213* **Spend this month**: per-user total API costs for the current month.

214* **Lines this month**: per-user total of accepted code lines for the current month.

215 

216<Note>

217 Spend figures in the Console dashboard are estimates for analytics purposes. For actual costs, refer to your billing page.

218</Note>

219 

220## Related resources

90 221 

91> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt222* [Monitoring with OpenTelemetry](/en/monitoring-usage): export real-time metrics and events to your observability stack

223* [Manage costs effectively](/en/costs): set spend limits and optimize token usage

224* [Permissions](/en/permissions): configure roles and permissions

authentication.md +117 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Authentication

6 

7> Log in to Claude Code and configure authentication for individuals, teams, and organizations.

8 

9Claude Code supports multiple authentication methods depending on your setup. Individual users can log in with a Claude.ai account, while teams can use Claude for Teams or Enterprise, the Claude Console, or a cloud provider like Amazon Bedrock, Google Vertex AI, or Microsoft Foundry.

10 

11## Log in to Claude Code

12 

13After [installing Claude Code](/en/setup#install-claude-code), run `claude` in your terminal. On first launch, Claude Code opens a browser window for you to log in.

14 

15If the browser doesn't open automatically, press `c` to copy the login URL to your clipboard, then paste it into your browser.

16 

17You can authenticate with any of these account types:

18 

19* **Claude Pro or Max subscription**: log in with your Claude.ai account. Subscribe at [claude.com/pricing](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_pro_max).

20* **Claude for Teams or Enterprise**: log in with the Claude.ai account your team admin invited you to.

21* **Claude Console**: log in with your Console credentials. Your admin must have [invited you](#claude-console-authentication) first.

22* **Cloud providers**: if your organization uses [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry), set the required environment variables before running `claude`. No browser login is needed.

23 

24To log out and re-authenticate, type `/logout` at the Claude Code prompt.

25 

26If you're having trouble logging in, see [authentication troubleshooting](/en/troubleshooting#authentication-issues).

27 

28## Set up team authentication

29 

30For teams and organizations, you can configure Claude Code access in one of these ways:

31 

32* [Claude for Teams or Enterprise](#claude-for-teams-or-enterprise), recommended for most teams

33* [Claude Console](#claude-console-authentication)

34* [Amazon Bedrock](/en/amazon-bedrock)

35* [Google Vertex AI](/en/google-vertex-ai)

36* [Microsoft Foundry](/en/microsoft-foundry)

37 

38### Claude for Teams or Enterprise

39 

40[Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_teams#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_enterprise) provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management.

41 

42* **Claude for Teams**: self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams.

43* **Claude for Enterprise**: adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.

44 

45<Steps>

46 <Step title="Subscribe">

47 Subscribe to [Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_teams_step#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=authentication_enterprise_step).

48 </Step>

49 

50 <Step title="Invite team members">

51 Invite team members from the admin dashboard.

52 </Step>

53 

54 <Step title="Install and log in">

55 Team members install Claude Code and log in with their Claude.ai accounts.

56 </Step>

57</Steps>

58 

59### Claude Console authentication

60 

61For organizations that prefer API-based billing, you can set up access through the Claude Console.

62 

63<Steps>

64 <Step title="Create or use a Console account">

65 Use your existing Claude Console account or create a new one.

66 </Step>

67 

68 <Step title="Add users">

69 You can add users through either method:

70 

71 * Bulk invite users from within the Console: Settings -> Members -> Invite

72 * [Set up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso)

73 </Step>

74 

75 <Step title="Assign roles">

76 When inviting users, assign one of:

77 

78 * **Claude Code** role: users can only create Claude Code API keys

79 * **Developer** role: users can create any kind of API key

80 </Step>

81 

82 <Step title="Users complete setup">

83 Each invited user needs to:

84 

85 * Accept the Console invite

86 * [Check system requirements](/en/setup#system-requirements)

87 * [Install Claude Code](/en/setup#install-claude-code)

88 * Log in with Console account credentials

89 </Step>

90</Steps>

91 

92### Cloud provider authentication

93 

94For teams using Amazon Bedrock, Google Vertex AI, or Microsoft Foundry:

95 

96<Steps>

97 <Step title="Follow provider setup">

98 Follow the [Bedrock docs](/en/amazon-bedrock), [Vertex docs](/en/google-vertex-ai), or [Microsoft Foundry docs](/en/microsoft-foundry).

99 </Step>

100 

101 <Step title="Distribute configuration">

102 Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/en/settings).

103 </Step>

104 

105 <Step title="Install Claude Code">

106 Users can [install Claude Code](/en/setup#install-claude-code).

107 </Step>

108</Steps>

109 

110## Credential management

111 

112Claude Code securely manages your authentication credentials:

113 

114* **Storage location**: on macOS, credentials are stored in the encrypted macOS Keychain.

115* **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.

116* **Custom credential scripts**: the [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.

117* **Refresh intervals**: by default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.

best-practices.md +39 −57

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Best Practices for Claude Code5# Best Practices for Claude Code

2 6 

3> Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.7> Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.


16 20 

17Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.21Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.

18 22 

19This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. For detailed strategies on reducing token usage, see [Reduce token usage](/en/costs#reduce-token-usage).23This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. Track context usage continuously with a [custom status line](/en/statusline), and see [Reduce token usage](/en/costs#reduce-token-usage) for strategies on reducing token usage.

20 24 

21***25***

22 26 


36| **Verify UI changes visually** | *"make the dashboard look better"* | *"\[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them"* |40| **Verify UI changes visually** | *"make the dashboard look better"* | *"\[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them"* |

37| **Address root causes, not symptoms** | *"the build is failing"* | *"the build fails with this error: \[paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error"* |41| **Address root causes, not symptoms** | *"the build is failing"* | *"the build fails with this error: \[paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error"* |

38 42 

39UI changes can be verified using the [Claude in Chrome extension](/en/chrome). It opens a browser, tests the UI, and iterates until the code works.43UI changes can be verified using the [Claude in Chrome extension](/en/chrome). It opens new tabs in your browser, tests the UI, and iterates until the code works.

40 44 

41Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.45Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.

42 46 


69 I want to add Google OAuth. What files need to change?73 I want to add Google OAuth. What files need to change?

70 What's the session flow? Create a plan.74 What's the session flow? Create a plan.

71 ```75 ```

76 

77 Press `Ctrl+G` to open the plan in your text editor for direct editing before Claude proceeds.

72 </Step>78 </Step>

73 79 

74 <Step title="Implement">80 <Step title="Implement">


142 Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time.148 Run `/init` to generate a starter CLAUDE.md file based on your current project structure, then refine over time.

143</Tip>149</Tip>

144 150 

145CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context **it can't infer from code alone**.151CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can't infer from code alone.

146 152 

147The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.153The `/init` command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.

148 154 


188 194 

189You can place CLAUDE.md files in several locations:195You can place CLAUDE.md files in several locations:

190 196 

191* **Home folder (`~/.claude/CLAUDE.md`)**: Applies to all Claude sessions197* **Home folder (`~/.claude/CLAUDE.md`)**: applies to all Claude sessions

192* **Project root (`./CLAUDE.md`)**: Check into git to share with your team, or name it `CLAUDE.local.md` and `.gitignore` it198* **Project root (`./CLAUDE.md`)**: check into git to share with your team

193* **Parent directories**: Useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically199* **Parent directories**: useful for monorepos where both `root/CLAUDE.md` and `root/foo/CLAUDE.md` are pulled in automatically

194* **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories200* **Child directories**: Claude pulls in child CLAUDE.md files on demand when working with files in those directories

195 201 

196### Configure permissions202### Configure permissions


201 207 

202By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are two ways to reduce these interruptions:208By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are two ways to reduce these interruptions:

203 209 

204* **Permission allowlists**: Permit specific tools you know are safe (like `npm run lint` or `git commit`)210* **Permission allowlists**: permit specific tools you know are safe (like `npm run lint` or `git commit`)

205* **Sandboxing**: Enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries211* **Sandboxing**: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries

206 212 

207Alternatively, use `--dangerously-skip-permissions` to bypass all permission checks for contained workflows like fixing lint errors or generating boilerplate.213Alternatively, use `--dangerously-skip-permissions` to bypass all permission checks for contained workflows like fixing lint errors or generating boilerplate.

208 214 


210 Letting Claude run arbitrary commands can result in data loss, system corruption, or data exfiltration via prompt injection. Only use `--dangerously-skip-permissions` in a sandbox without internet access.216 Letting Claude run arbitrary commands can result in data loss, system corruption, or data exfiltration via prompt injection. Only use `--dangerously-skip-permissions` in a sandbox without internet access.

211</Warning>217</Warning>

212 218 

213Read more about [configuring permissions](/en/settings) and [enabling sandboxing](/en/sandboxing#sandboxing).219Read more about [configuring permissions](/en/permissions) and [enabling sandboxing](/en/sandboxing).

214 220 

215### Use CLI tools221### Use CLI tools

216 222 


238 244 

239[Hooks](/en/hooks-guide) run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.245[Hooks](/en/hooks-guide) run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.

240 246 

241Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Run `/hooks` for interactive configuration, or edit `.claude/settings.json` directly.247Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Edit `.claude/settings.json` directly to configure hooks by hand, and run `/hooks` to browse what's configured.

242 248 

243### Create skills249### Create skills

244 250 


350 356 

351Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.357Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.

352 358 

353```359```text theme={null}

354I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.360I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.

355 361 

356Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.362Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.


374 380 

375The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.381The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.

376 382 

377* **`Esc`**: Stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect.383* **`Esc`**: stop Claude mid-action with the `Esc` key. Context is preserved, so you can redirect.

378* **`Esc + Esc` or `/rewind`**: Press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state.384* **`Esc + Esc` or `/rewind`**: press `Esc` twice or run `/rewind` to open the rewind menu and restore previous conversation and code state, or summarize from a selected message.

379* **`"Undo that"`**: Have Claude revert its changes.385* **`"Undo that"`**: have Claude revert its changes.

380* **`/clear`**: Reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.386* **`/clear`**: reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.

381 387 

382If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run `/clear` and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.388If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run `/clear` and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.

383 389 


394* Use `/clear` frequently between tasks to reset the context window entirely400* Use `/clear` frequently between tasks to reset the context window entirely

395* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions401* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions

396* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`402* For more control, run `/compact <instructions>`, like `/compact Focus on the API changes`

403* To compact only part of the conversation, use `Esc + Esc` or `/rewind`, select a message checkpoint, and choose **Summarize from here**. This condenses messages from that point forward while keeping earlier context intact.

397* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization404* Customize compaction behavior in CLAUDE.md with instructions like `"When compacting, always preserve the full list of modified files and any test commands"` to ensure critical context survives summarization

405* For quick questions that don't need to stay in context, use [`/btw`](/en/interactive-mode#side-questions-with-btw). The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.

398 406 

399### Use subagents for investigation407### Use subagents for investigation

400 408 


404 412 

405Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:413Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:

406 414 

407```415```text theme={null}

408Use subagents to investigate how our authentication system handles token416Use subagents to investigate how our authentication system handles token

409refresh, and whether we have any existing OAuth utilities I should reuse.417refresh, and whether we have any existing OAuth utilities I should reuse.

410```418```


413 421 

414You can also use subagents for verification after Claude implements something:422You can also use subagents for verification after Claude implements something:

415 423 

416```424```text theme={null}

417use a subagent to review this code for edge cases425use a subagent to review this code for edge cases

418```426```

419 427 


423 Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.431 Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.

424</Tip>432</Tip>

425 433 

426Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the checkpoint menu. You can restore conversation only (keep code changes), restore code only (keep conversation), or restore both.434Claude automatically checkpoints before changes. Double-tap `Escape` or run `/rewind` to open the rewind menu. You can restore conversation only, restore code only, restore both, or summarize from a selected message. See [Checkpointing](/en/checkpointing) for details.

427 435 

428Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.436Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.

429 437 


437 Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions.445 Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions.

438</Tip>446</Tip>

439 447 

440Claude Code saves conversations locally. When a task spans multiple sessions (you start a feature, get interrupted, come back the next day) you don't have to re-explain the context:448Claude Code saves conversations locally. When a task spans multiple sessions, you don't have to re-explain the context:

441 449 

442```bash theme={null}450```bash theme={null}

443claude --continue # Resume the most recent conversation451claude --continue # Resume the most recent conversation

444claude --resume # Select from recent conversations452claude --resume # Select from recent conversations

445```453```

446 454 

447Use `/rename` to give sessions descriptive names (`"oauth-migration"`, `"debugging-memory-leak"`) so you can find them later. Treat sessions like branches. Different workstreams can have separate, persistent contexts.455Use `/rename` to give sessions descriptive names like `"oauth-migration"` or `"debugging-memory-leak"` so you can find them later. Treat sessions like branches: different workstreams can have separate, persistent contexts.

448 456 

449***457***

450 458 

451## Automate and scale459## Automate and scale

452 460 

453Once you're effective with one Claude, multiply your output with parallel sessions, headless mode, and fan-out patterns.461Once you're effective with one Claude, multiply your output with parallel sessions, non-interactive mode, and fan-out patterns.

454 462 

455Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.463Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.

456 464 

457### Run headless mode465### Run non-interactive mode

458 466 

459<Tip>467<Tip>

460 Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.468 Use `claude -p "prompt"` in CI, pre-commit hooks, or scripts. Add `--output-format stream-json` for streaming JSON output.

461</Tip>469</Tip>

462 470 

463With `claude -p "your prompt"`, you can run Claude headlessly, without an interactive session. Headless mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats (plain text, JSON, streaming JSON) let you parse results programmatically.471With `claude -p "your prompt"`, you can run Claude non-interactively, without a session. Non-interactive mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats let you parse results programmatically: plain text, JSON, or streaming JSON.

464 472 

465```bash theme={null}473```bash theme={null}

466# One-off queries474# One-off queries


479 Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.487 Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.

480</Tip>488</Tip>

481 489 

482There are two main ways to run parallel sessions:490There are three main ways to run parallel sessions:

483 491 

484* [Claude Desktop](/en/desktop): Manage multiple local sessions visually. Each session gets its own isolated worktree.492* [Claude Code desktop app](/en/desktop#work-in-parallel-with-sessions): Manage multiple local sessions visually. Each session gets its own isolated worktree.

485* [Claude Code on the web](/en/claude-code-on-the-web): Run on Anthropic's secure cloud infrastructure in isolated VMs.493* [Claude Code on the web](/en/claude-code-on-the-web): Run on Anthropic's secure cloud infrastructure in isolated VMs.

494* [Agent teams](/en/agent-teams): Automated coordination of multiple sessions with shared tasks, messaging, and a team lead.

486 495 

487Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.496Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.

488 497 


513 ```bash theme={null}522 ```bash theme={null}

514 for file in $(cat files.txt); do523 for file in $(cat files.txt); do

515 claude -p "Migrate $file from React to Vue. Return OK or FAIL." \524 claude -p "Migrate $file from React to Vue. Return OK or FAIL." \

516 --allowedTools "Edit,Bash(git commit:*)"525 --allowedTools "Edit,Bash(git commit *)"

517 done526 done

518 ```527 ```

519 </Step>528 </Step>


531 540 

532Use `--verbose` for debugging during development, and turn it off in production.541Use `--verbose` for debugging during development, and turn it off in production.

533 542 

534### Safe Autonomous Mode

535 

536Use `claude --dangerously-skip-permissions` to bypass all permission checks and let Claude work uninterrupted. This works well for workflows like fixing lint errors or generating boilerplate code.

537 

538<Warning>

539 Letting Claude run arbitrary commands is risky and can result in data loss, system corruption, or data exfiltration (e.g., via prompt injection attacks). To minimize these risks, use `--dangerously-skip-permissions` in a container without internet access.

540 

541 With sandboxing enabled (`/sandbox`), you get similar autonomy with better security. Sandbox defines upfront boundaries rather than bypassing all checks.

542</Warning>

543 

544***543***

545 544 

546## Avoid common failure patterns545## Avoid common failure patterns


572 571 

573## Related resources572## Related resources

574 573 

575<CardGroup cols={2}>574* [How Claude Code works](/en/how-claude-code-works): the agentic loop, tools, and context management

576 <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">575* [Extend Claude Code](/en/features-overview): skills, hooks, MCP, subagents, and plugins

577 Understand the agentic loop, tools, and context management576* [Common workflows](/en/common-workflows): step-by-step recipes for debugging, testing, PRs, and more

578 </Card>577* [CLAUDE.md](/en/memory): store project conventions and persistent context

579 

580 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">

581 Choose between skills, hooks, MCP, subagents, and plugins

582 </Card>

583 

584 <Card title="Common workflows" icon="list-check" href="/en/common-workflows">

585 Step-by-step recipes for debugging, testing, PRs, and more

586 </Card>

587 

588 <Card title="CLAUDE.md" icon="file-lines" href="/en/memory">

589 Store project conventions and persistent context

590 </Card>

591</CardGroup>

592 

593 

594 

595> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

checkpointing.md +34 −14

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Checkpointing5# Checkpointing

2 6 

3> Automatically track and rewind Claude's edits to quickly recover from unwanted changes.7> Track, rewind, and summarize Claude's edits and conversation to manage session state.

4 8 

5Claude Code automatically tracks Claude's file edits as you work, allowing you to quickly undo changes and rewind to previous states if anything gets off track.9Claude Code automatically tracks Claude's file edits as you work, allowing you to quickly undo changes and rewind to previous states if anything gets off track.

6 10 


16* Checkpoints persist across sessions, so you can access them in resumed conversations20* Checkpoints persist across sessions, so you can access them in resumed conversations

17* Automatically cleaned up along with sessions after 30 days (configurable)21* Automatically cleaned up along with sessions after 30 days (configurable)

18 22 

19### Rewinding changes23### Rewind and summarize

24 

25Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open the rewind menu. A scrollable list shows each of your prompts from the session. Select the point you want to act on, then choose an action:

26 

27* **Restore code and conversation**: revert both code and conversation to that point

28* **Restore conversation**: rewind to that message while keeping current code

29* **Restore code**: revert file changes while keeping the conversation

30* **Summarize from here**: compress the conversation from this point forward into a summary, freeing context window space

31* **Never mind**: return to the message list without making changes

32 

33After restoring the conversation or summarizing, the original prompt from the selected message is restored into the input field so you can re-send or edit it.

34 

35#### Restore vs. summarize

20 36 

21Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open up the rewind menu. You can choose to restore:37The three restore options revert state: they undo code changes, conversation history, or both. "Summarize from here" works differently:

22 38 

23* **Conversation only**: Rewind to a user message while keeping code changes39* Messages before the selected message stay intact

24* **Code only**: Revert file changes while keeping the conversation40* The selected message and all subsequent messages get replaced with a compact AI-generated summary

25* **Both code and conversation**: Restore both to a prior point in the session41* No files on disk are changed

42* The original messages are preserved in the session transcript, so Claude can reference the details if needed

43 

44This is similar to `/compact`, but targeted: instead of summarizing the entire conversation, you keep early context in full detail and only compress the parts that are using up space. You can type optional instructions to guide what the summary focuses on.

45 

46<Note>

47 Summarize keeps you in the same session and compresses context. If you want to branch off and try a different approach while preserving the original session intact, use [fork](/en/how-claude-code-works#resume-or-fork-sessions) instead (`claude --continue --fork-session`).

48</Note>

26 49 

27## Common use cases50## Common use cases

28 51 

29Checkpoints are particularly useful when:52Checkpoints are particularly useful when:

30 53 

31* **Exploring alternatives**: Try different implementation approaches without losing your starting point54* **Exploring alternatives**: try different implementation approaches without losing your starting point

32* **Recovering from mistakes**: Quickly undo changes that introduced bugs or broke functionality55* **Recovering from mistakes**: quickly undo changes that introduced bugs or broke functionality

33* **Iterating on features**: Experiment with variations knowing you can revert to working states56* **Iterating on features**: experiment with variations knowing you can revert to working states

57* **Freeing context space**: summarize a verbose debugging session from the midpoint forward, keeping your initial instructions intact

34 58 

35## Limitations59## Limitations

36 60 


61## See also85## See also

62 86 

63* [Interactive mode](/en/interactive-mode) - Keyboard shortcuts and session controls87* [Interactive mode](/en/interactive-mode) - Keyboard shortcuts and session controls

64* [Built-in commands](/en/interactive-mode#built-in-commands) - Accessing checkpoints using `/rewind`88* [Built-in commands](/en/commands) - Accessing checkpoints using `/rewind`

65* [CLI reference](/en/cli-reference) - Command-line options89* [CLI reference](/en/cli-reference) - Command-line options

66 

67 

68 

69> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

chrome.md +101 −89

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Use Claude Code with Chrome (beta)5# Use Claude Code with Chrome (beta)

2 6 

3> Connect Claude Code to your browser to test web apps, debug with console logs, and automate browser tasks.7> Connect Claude Code to your Chrome browser to test web apps, debug with console logs, automate form filling, and extract data from web pages.

4 8 

5<Note>9Claude Code integrates with the Claude in Chrome browser extension to give you browser automation capabilities from the CLI or the [VS Code extension](/en/vs-code#automate-browser-tasks-with-chrome). Build your code, then test and debug in the browser without switching contexts.

6 Chrome integration is in beta and currently works with Google Chrome only. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported.

7</Note>

8 10 

9Claude Code integrates with the Claude in Chrome browser extension to give you browser automation capabilities directly from your terminal. Build in your terminal, then test and debug in your browser without switching contexts.11Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into. Browser actions run in a visible Chrome window in real time. When Claude encounters a login page or CAPTCHA, it pauses and asks you to handle it manually.

10 12 

11## What the integration enables13<Note>

14 Chrome integration is in beta and currently works with Google Chrome and Microsoft Edge. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported.

15</Note>

12 16 

13With Chrome connected, you can chain browser actions with terminal commands in a single workflow. For example: scrape documentation from a website, analyze it, generate code based on what you learned, and commit the result.17## Capabilities

14 18 

15Key capabilities include:19With Chrome connected, you can chain browser actions with coding tasks in a single workflow:

16 20 

17* **Live debugging**: Claude reads console errors and DOM state directly, then fixes the code that caused them21* **Live debugging**: read console errors and DOM state directly, then fix the code that caused them

18* **Design verification**: Build a UI from a Figma mock, then have Claude open it in the browser and verify it matches22* **Design verification**: build a UI from a Figma mock, then open it in the browser to verify it matches

19* **Web app testing**: Test form validation, check for visual regressions, or verify user flows work correctly23* **Web app testing**: test form validation, check for visual regressions, or verify user flows

20* **Authenticated web apps**: Interact with Google Docs, Gmail, Notion, or any app you're logged into without needing API connectors24* **Authenticated web apps**: interact with Google Docs, Gmail, Notion, or any app you're logged into without API connectors

21* **Data extraction**: Pull structured information from web pages and save it locally25* **Data extraction**: pull structured information from web pages and save it locally

22* **Task automation**: Automate repetitive browser tasks like data entry, form filling, or multi-site workflows26* **Task automation**: automate repetitive browser tasks like data entry, form filling, or multi-site workflows

23* **Session recording**: Record browser interactions as GIFs to document or share what happened27* **Session recording**: record browser interactions as GIFs to document or share what happened

24 28 

25## Prerequisites29## Prerequisites

26 30 

27Before using Claude Code with Chrome, you need:31Before using Claude Code with Chrome, you need:

28 32 

29* [Google Chrome](https://www.google.com/chrome/) browser33* [Google Chrome](https://www.google.com/chrome/) or [Microsoft Edge](https://www.microsoft.com/edge) browser

30* [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher34* [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher, available in the Chrome Web Store for both browsers

31* [Claude Code CLI](/en/quickstart#step-1-install-claude-code) version 2.0.73 or higher35* [Claude Code](/en/quickstart#step-1-install-claude-code) version 2.0.73 or higher

32* A paid Claude plan (Pro, Team, or Enterprise)36* A direct Anthropic plan (Pro, Max, Teams, or Enterprise)

33 

34## How the integration works

35 

36Claude Code communicates with Chrome through the Claude in Chrome browser extension. The extension uses Chrome's [Native Messaging API](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging) to receive commands from Claude Code and execute them in your browser. This architecture lets Claude Code control browser tabs, read page content, and perform actions while you continue working in your terminal.

37 

38When Claude encounters a login page, CAPTCHA, or other blocker, it pauses and asks you to handle it. You can provide credentials for Claude to enter, or log in manually in the browser. Once you're past the blocker, tell Claude to continue and it picks up where it left off.

39 

40Claude opens new tabs for browser tasks rather than taking over existing ones. However, it shares your browser's login state, so if you're already signed into a site in Chrome, Claude can access it without re-authenticating.

41 37 

42<Note>38<Note>

43 The Chrome integration requires a visible browser window. When Claude performs browser actions, you'll see Chrome open and navigate in real time. There's no headless mode since the integration relies on your actual browser session with its login state.39 Chrome integration is not available through third-party providers like Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature.

44</Note>40</Note>

45 41 

46## Set up the integration42## Get started in the CLI

47 43 

48<Steps>44<Steps>

49 <Step title="Update Claude Code">45 <Step title="Launch Claude Code with Chrome">

50 Chrome integration requires a recent version of Claude Code. If you installed using the [native installer](/en/quickstart#step-1-install-claude-code), updates happen automatically. Otherwise, run:46 Start Claude Code with the `--chrome` flag:

51 47 

52 ```bash theme={null}48 ```bash theme={null}

53 claude update49 claude --chrome

54 ```50 ```

51 

52 You can also enable Chrome from within an existing session by running `/chrome`.

55 </Step>53 </Step>

56 54 

57 <Step title="Start Claude Code with Chrome enabled">55 <Step title="Ask Claude to use the browser">

58 Launch Claude Code with the `--chrome` flag:56 This example navigates to a page, interacts with it, and reports what it finds, all from your terminal or editor:

59 57 

60 ```bash theme={null}58 ```text theme={null}

61 claude --chrome59 Go to code.claude.com/docs, click on the search box,

60 type "hooks", and tell me what results appear

62 ```61 ```

63 </Step>62 </Step>

64 

65 <Step title="Verify the connection">

66 Run `/chrome` to check the connection status and manage settings. If the extension isn't detected, you'll see a warning with a link to install it.

67 </Step>

68</Steps>63</Steps>

69 64 

70You can also enable Chrome integration from within an existing session using the `/chrome` command.65Run `/chrome` at any time to check the connection status, manage permissions, or reconnect the extension.

71 66 

72## Try it out67For VS Code, see [browser automation in VS Code](/en/vs-code#automate-browser-tasks-with-chrome).

73 68 

74Once connected, type this into Claude to see the integration in action:69### Enable Chrome by default

75 70 

76```71To avoid passing `--chrome` each session, run `/chrome` and select "Enabled by default".

77Go to code.claude.com/docs, click on the search box,

78type "hooks", and tell me what results appear

79```

80 72 

81Claude opens the page, clicks into the search field, types the query, and reports the autocomplete results. This shows navigation, clicking, and typing in a single workflow.73In the [VS Code extension](/en/vs-code#automate-browser-tasks-with-chrome), Chrome is available whenever the Chrome extension is installed. No additional flag is needed.

82 74 

83## Example workflows75<Note>

76 Enabling Chrome by default in the CLI increases context usage since browser tools are always loaded. If you notice increased context consumption, disable this setting and use `--chrome` only when needed.

77</Note>

78 

79### Manage site permissions

80 

81Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on.

84 82 

85Claude can navigate pages, click and type, fill forms, scroll, read console logs and network requests, manage tabs, resize windows, and record GIFs. Run `/mcp` and click into `claude-in-chrome` to see the full list of available tools.83## Example workflows

86 84 

87The following examples show common patterns for browser automation.85These examples show common ways to combine browser actions with coding tasks. Run `/mcp` and select `claude-in-chrome` to see the full list of available browser tools.

88 86 

89### Test a local web application87### Test a local web application

90 88 

91When developing a web app, ask Claude to verify your changes work correctly:89When developing a web app, ask Claude to verify your changes work correctly:

92 90 

93```91```text theme={null}

94I just updated the login form validation. Can you open localhost:3000,92I just updated the login form validation. Can you open localhost:3000,

95try submitting the form with invalid data, and check if the error93try submitting the form with invalid data, and check if the error

96messages appear correctly?94messages appear correctly?


100 98 

101### Debug with console logs99### Debug with console logs

102 100 

103If your app has issues, Claude can read console output to help diagnose problems:101Claude can read console output to help diagnose problems. Tell Claude what patterns to look for rather than asking for all console output, since logs can be verbose:

104 102 

105```103```text theme={null}

106Open the dashboard page and check the console for any errors when104Open the dashboard page and check the console for any errors when

107the page loads.105the page loads.

108```106```


113 111 

114Speed up repetitive data entry tasks:112Speed up repetitive data entry tasks:

115 113 

116```114```text theme={null}

117I have a spreadsheet of customer contacts in contacts.csv. For each row,115I have a spreadsheet of customer contacts in contacts.csv. For each row,

118go to our CRM at crm.example.com, click "Add Contact", and fill in the116go to the CRM at crm.example.com, click "Add Contact", and fill in the

119name, email, and phone fields.117name, email, and phone fields.

120```118```

121 119 


125 123 

126Use Claude to write directly in your documents without API setup:124Use Claude to write directly in your documents without API setup:

127 125 

128```126```text theme={null}

129Draft a project update based on our recent commits and add it to my127Draft a project update based on the recent commits and add it to my

130Google Doc at docs.google.com/document/d/abc123128Google Doc at docs.google.com/document/d/abc123

131```129```

132 130 


136 134 

137Pull structured information from websites:135Pull structured information from websites:

138 136 

139```137```text theme={null}

140Go to the product listings page and extract the name, price, and138Go to the product listings page and extract the name, price, and

141availability for each item. Save the results as a CSV file.139availability for each item. Save the results as a CSV file.

142```140```


147 145 

148Coordinate tasks across multiple websites:146Coordinate tasks across multiple websites:

149 147 

150```148```text theme={null}

151Check my calendar for meetings tomorrow, then for each meeting with149Check my calendar for meetings tomorrow, then for each meeting with

152an external attendee, look up their company on LinkedIn and add a150an external attendee, look up their company website and add a note

153note about what they do.151about what they do.

154```152```

155 153 

156Claude works across tabs to gather information and complete the workflow.154Claude works across tabs to gather information and complete the workflow.


159 157 

160Create shareable recordings of browser interactions:158Create shareable recordings of browser interactions:

161 159 

162```160```text theme={null}

163Record a GIF showing how to complete the checkout flow, from adding161Record a GIF showing how to complete the checkout flow, from adding

164an item to the cart through to the confirmation page.162an item to the cart through to the confirmation page.

165```163```

166 164 

167Claude records the interaction sequence and saves it as a GIF file.165Claude records the interaction sequence and saves it as a GIF file.

168 166 

169## Best practices

170 

171When using browser automation, keep these guidelines in mind:

172 

173* **Modal dialogs can interrupt the flow**: JavaScript alerts, confirms, and prompts block browser events and prevent Claude from receiving commands. If a dialog appears, dismiss it manually and tell Claude to continue.

174* **Use fresh tabs**: Claude creates new tabs for each session. If a tab becomes unresponsive, ask Claude to create a new one.

175* **Filter console output**: Console logs can be verbose. When debugging, tell Claude what patterns to look for rather than asking for all console output.

176 

177## Troubleshooting167## Troubleshooting

178 168 

179### Extension not detected169### Extension not detected

180 170 

181If Claude Code shows "Chrome extension not detected":171If Claude Code shows "Chrome extension not detected":

182 172 

1831. Verify the Chrome extension (version 1.0.36 or higher) is installed1731. Verify the Chrome extension is installed and enabled in `chrome://extensions`

1842. Verify Claude Code is version 2.0.73 or higher by running `claude --version`1742. Verify Claude Code is up to date by running `claude --version`

1853. Check that Chrome is running1753. Check that Chrome is running

1864. Run `/chrome` and select "Reconnect extension" to re-establish the connection1764. Run `/chrome` and select "Reconnect extension" to re-establish the connection

1875. If the issue persists, restart both Claude Code and Chrome1775. If the issue persists, restart both Claude Code and Chrome

188 178 

179The first time you enable Chrome integration, Claude Code installs a native messaging host configuration file. Chrome reads this file on startup, so if the extension isn't detected on your first attempt, restart Chrome to pick up the new configuration.

180 

181If the connection still fails, verify the host configuration file exists at:

182 

183For Chrome:

184 

185* **macOS**: `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

186* **Linux**: `~/.config/google-chrome/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

187* **Windows**: check `HKCU\Software\Google\Chrome\NativeMessagingHosts\` in the Windows Registry

188 

189For Edge:

190 

191* **macOS**: `~/Library/Application Support/Microsoft Edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

192* **Linux**: `~/.config/microsoft-edge/NativeMessagingHosts/com.anthropic.claude_code_browser_extension.json`

193* **Windows**: check `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\` in the Windows Registry

194 

189### Browser not responding195### Browser not responding

190 196 

191If Claude's browser commands stop working:197If Claude's browser commands stop working:

192 198 

1931. Check if a modal dialog (alert, confirm, prompt) is blocking the page1991. Check if a modal dialog (alert, confirm, prompt) is blocking the page. JavaScript dialogs block browser events and prevent Claude from receiving commands. Dismiss the dialog manually, then tell Claude to continue.

1942. Ask Claude to create a new tab and try again2002. Ask Claude to create a new tab and try again

1953. Restart the Chrome extension by disabling and re-enabling it2013. Restart the Chrome extension by disabling and re-enabling it in `chrome://extensions`

196 202 

197### First-time setup203### Connection drops during long sessions

198 204 

199The first time you use the integration, Claude Code installs a native messaging host that allows communication between the CLI and Chrome. If you encounter permission errors, you may need to restart Chrome for the installation to take effect.205The Chrome extension's service worker can go idle during extended sessions, which breaks the connection. If browser tools stop working after a period of inactivity, run `/chrome` and select "Reconnect extension".

200 206 

201## Enable by default207### Windows-specific issues

202 208 

203Chrome integration requires the `--chrome` flag each time you start Claude Code. To enable it by default, run `/chrome` and select "Enabled by default".209On Windows, you may encounter:

204 210 

205<Note>211* **Named pipe conflicts (EADDRINUSE)**: if another process is using the same named pipe, restart Claude Code. Close any other Claude Code sessions that might be using Chrome.

206 Enabling Chrome by default increases context usage since browser tools are always loaded. If you notice increased context consumption, disable this setting and use `--chrome` only when needed.212* **Native messaging host errors**: if the native messaging host crashes on startup, try reinstalling Claude Code to regenerate the host configuration.

207</Note>

208 213 

209Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on. Run `/chrome` to see current permission settings.214### Common error messages

210 215 

211## See also216These are the most frequently encountered errors and how to resolve them:

212 217 

213* [CLI reference](/en/cli-reference) - Command-line flags including `--chrome`218| Error | Cause | Fix |

214* [Common workflows](/en/common-workflows) - More ways to use Claude Code219| ------------------------------------ | ------------------------------------------------ | --------------------------------------------------------------- |

215* [Getting started with Claude for Chrome](https://support.anthropic.com/en/articles/12012173-getting-started-with-claude-for-chrome) - Full documentation for the Chrome extension, including shortcuts, scheduling, and permissions220| "Browser extension is not connected" | Native messaging host cannot reach the extension | Restart Chrome and Claude Code, then run `/chrome` to reconnect |

221| "Extension not detected" | Chrome extension is not installed or is disabled | Install or enable the extension in `chrome://extensions` |

222| "No tab available" | Claude tried to act before a tab was ready | Ask Claude to create a new tab and retry |

223| "Receiving end does not exist" | Extension service worker went idle | Run `/chrome` and select "Reconnect extension" |

216 224 

225## See also

217 226 

218 227* [Use Claude Code in VS Code](/en/vs-code#automate-browser-tasks-with-chrome): browser automation in the VS Code extension

219> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt228* [CLI reference](/en/cli-reference): command-line flags including `--chrome`

229* [Common workflows](/en/common-workflows): more ways to use Claude Code

230* [Data and privacy](/en/data-usage): how Claude Code handles your data

231* [Getting started with Claude in Chrome](https://support.claude.com/en/articles/12012173-getting-started-with-claude-in-chrome): full documentation for the Chrome extension, including shortcuts, scheduling, and permissions

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code on the web5# Claude Code on the web

2 6 

3> Run Claude Code tasks asynchronously on secure cloud infrastructure7> Run Claude Code tasks asynchronously on secure cloud infrastructure


16* **Repositories not on your local machine**: Work on code you don't have checked out locally20* **Repositories not on your local machine**: Work on code you don't have checked out locally

17* **Backend changes**: Where Claude Code can write tests and then write code to pass those tests21* **Backend changes**: Where Claude Code can write tests and then write code to pass those tests

18 22 

19Claude Code is also available on the Claude iOS app for kicking off tasks on the go and monitoring work in progress.23Claude Code is also available on the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) for kicking off tasks on the go and monitoring work in progress.

20 24 

21You can move between local and remote development: [send tasks from your terminal to run on the web](#from-terminal-to-web) with the `&` prefix, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally.25You can [kick off new tasks on the web from your terminal](#from-terminal-to-web) with `--remote`, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally. To use the web interface while running Claude Code on your own machine instead of cloud infrastructure, see [Remote Control](/en/remote-control).

22 26 

23## Who can use Claude Code on the web?27## Who can use Claude Code on the web?

24 28 


26 30 

27* **Pro users**31* **Pro users**

28* **Max users**32* **Max users**

29* **Team premium seat users**33* **Team users**

30* **Enterprise premium seat users**34* **Enterprise users** with premium seats or Chat + Claude Code seats

31 35 

32## Getting started36## Getting started

33 37 


43When you start a task on Claude Code on the web:47When you start a task on Claude Code on the web:

44 48 

451. **Repository cloning**: Your repository is cloned to an Anthropic-managed virtual machine491. **Repository cloning**: Your repository is cloned to an Anthropic-managed virtual machine

462. **Environment setup**: Claude prepares a secure cloud environment with your code502. **Environment setup**: Claude prepares a secure cloud environment with your code, then runs your [setup script](#setup-scripts) if configured

473. **Network configuration**: Internet access is configured based on your settings513. **Network configuration**: Internet access is configured based on your settings

484. **Task execution**: Claude analyzes code, makes changes, runs tests, and checks its work524. **Task execution**: Claude analyzes code, makes changes, runs tests, and checks its work

495. **Completion**: You're notified when finished and can create a PR with the changes535. **Completion**: You're notified when finished and can create a PR with the changes


65 69 

66## Moving tasks between web and terminal70## Moving tasks between web and terminal

67 71 

68You can start tasks on the web and continue them in your terminal, or send tasks from your terminal to run on the web. Web sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude iOS app.72You can start new tasks on the web from your terminal, or pull web sessions into your terminal to continue locally. Web sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude mobile app.

69 73 

70<Note>74<Note>

71 Session handoff is one-way: you can pull web sessions into your terminal, but you can't push an existing terminal session to the web. The [`&` prefix](#from-terminal-to-web) creates a *new* web session with your current conversation context.75 Session handoff is one-way: you can pull web sessions into your terminal, but you can't push an existing terminal session to the web. The `--remote` flag creates a *new* web session for your current repository.

72</Note>76</Note>

73 77 

74### From terminal to web78### From terminal to web

75 79 

76Start a message with `&` inside Claude Code to send a task to run on the web:80Start a web session from the command line with the `--remote` flag:

77 

78```

79& Fix the authentication bug in src/auth/login.ts

80```

81 

82This creates a new web session on claude.ai with your current conversation context. The task runs in the cloud while you continue working locally. Use `/tasks` to check progress, or open the session on claude.ai or the Claude iOS app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.

83 

84You can also start a web session directly from the command line:

85 81 

86```bash theme={null}82```bash theme={null}

87claude --remote "Fix the authentication bug in src/auth/login.ts"83claude --remote "Fix the authentication bug in src/auth/login.ts"

88```84```

89 85 

90#### Tips for background tasks86This creates a new web session on claude.ai. The task runs in the cloud while you continue working locally. Use `/tasks` to check progress, or open the session on claude.ai or the Claude mobile app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.

87 

88#### Tips for remote tasks

91 89 

92**Plan locally, execute remotely**: For complex tasks, start Claude in plan mode to collaborate on the approach before sending work to the web:90**Plan locally, execute remotely**: For complex tasks, start Claude in plan mode to collaborate on the approach, then send work to the web:

93 91 

94```bash theme={null}92```bash theme={null}

95claude --permission-mode plan93claude --permission-mode plan

96```94```

97 95 

98In plan mode, Claude can only read files and explore the codebase. Once you're satisfied with the plan, send it to the web for autonomous execution:96In plan mode, Claude can only read files and explore the codebase. Once you're satisfied with the plan, start a remote session for autonomous execution:

99 97 

100```98```bash theme={null}

101& Execute the migration plan we discussed99claude --remote "Execute the migration plan in docs/migration-plan.md"

102```100```

103 101 

104This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud.102This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud.

105 103 

106**Run tasks in parallel**: Each `&` command creates its own web session that runs independently. You can kick off multiple tasks and they'll all run simultaneously in separate sessions:104**Run tasks in parallel**: Each `--remote` command creates its own web session that runs independently. You can kick off multiple tasks and they'll all run simultaneously in separate sessions:

107 105 

108```106```bash theme={null}

109& Fix the flaky test in auth.spec.ts107claude --remote "Fix the flaky test in auth.spec.ts"

110& Update the API documentation108claude --remote "Update the API documentation"

111& Refactor the logger to use structured output109claude --remote "Refactor the logger to use structured output"

112```110```

113 111 

114Monitor all sessions with `/tasks`. When a session completes, you can create a PR from the web interface or [teleport](#from-web-to-terminal) the session to your terminal to continue working.112Monitor all sessions with `/tasks`. When a session completes, you can create a PR from the web interface or [teleport](#from-web-to-terminal) the session to your terminal to continue working.


135| Branch available | The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out. |133| Branch available | The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out. |

136| Same account | You must be authenticated to the same Claude.ai account used in the web session. |134| Same account | You must be authenticated to the same Claude.ai account used in the web session. |

137 135 

136### Sharing sessions

137 

138To share a session, toggle its visibility according to the account

139types below. After that, share the session link as-is. Recipients who open your

140shared session will see the latest state of the session upon load, but the

141recipient's page will not update in real time.

142 

143#### Sharing from an Enterprise or Teams account

144 

145For Enterprise and Teams accounts, the two visibility options are **Private**

146and **Team**. Team visibility makes the session visible to other members of your

147Claude.ai organization. Repository access verification is enabled by default,

148based on the GitHub account connected to the recipient's account. Your account's

149display name is visible to all recipients with access. [Claude in Slack](/en/slack)

150sessions are automatically shared with Team visibility.

151 

152#### Sharing from a Max or Pro account

153 

154For Max and Pro accounts, the two visibility options are **Private**

155and **Public**. Public visibility makes the session visible to any user logged

156into claude.ai.

157 

158Check your session for sensitive content before sharing. Sessions may contain

159code and credentials from private GitHub repositories. Repository access

160verification is not enabled by default.

161 

162Enable repository access verification and/or withhold your name from your shared

163sessions by going to Settings > Claude Code > Sharing settings.

164 

165## Managing sessions

166 

167### Archiving sessions

168 

169You can archive sessions to keep your session list organized. Archived sessions are hidden from the default session list but can be viewed by filtering for archived sessions.

170 

171To archive a session, hover over the session in the sidebar and click the archive icon.

172 

173### Deleting sessions

174 

175Deleting a session permanently removes the session and its data. This action cannot be undone. You can delete a session in two ways:

176 

177* **From the sidebar**: Filter for archived sessions, then hover over the session you want to delete and click the delete icon

178* **From the session menu**: Open a session, click the dropdown next to the session title, and select **Delete**

179 

180You will be asked to confirm before a session is deleted.

181 

138## Cloud environment182## Cloud environment

139 183 

140### Default image184### Default image


183 227 

184When you start a session in Claude Code on the web, here's what happens under the hood:228When you start a session in Claude Code on the web, here's what happens under the hood:

185 229 

1861. **Environment preparation**: We clone your repository and run any configured Claude hooks for initialization. The repo will be cloned with the default branch on your GitHub repo. If you would like to check out a specific branch, you can specify that in the prompt.2301. **Environment preparation**: We clone your repository and run any configured [setup script](#setup-scripts). The repo will be cloned with the default branch on your GitHub repo. If you would like to check out a specific branch, you can specify that in the prompt.

187 231 

1882. **Network configuration**: We configure internet access for the agent. Internet access is limited by default, but you can configure the environment to have no internet or full internet access based on your needs.2322. **Network configuration**: We configure internet access for the agent. Internet access is limited by default, but you can configure the environment to have no internet or full internet access based on your needs.

189 233 


195 Claude operates entirely through the terminal and CLI tools available in the environment. It uses the pre-installed tools in the universal image and any additional tools you install through hooks or dependency management.239 Claude operates entirely through the terminal and CLI tools available in the environment. It uses the pre-installed tools in the universal image and any additional tools you install through hooks or dependency management.

196</Note>240</Note>

197 241 

198**To add a new environment:** Select the current environment to open the environment selector, and then select "Add environment". This will open a dialog where you can specify the environment name, network access level, and any environment variables you want to set.242**To add a new environment:** Select the current environment to open the environment selector, and then select "Add environment". This will open a dialog where you can specify the environment name, network access level, environment variables, and a [setup script](#setup-scripts).

199 243 

200**To update an existing environment:** Select the current environment, to the right of the environment name, and select the settings button. This will open a dialog where you can update the environment name, network access, and environment variables.244**To update an existing environment:** Select the current environment, to the right of the environment name, and select the settings button. This will open a dialog where you can update the environment name, network access, environment variables, and setup script.

201 245 

202**To select your default environment from the terminal:** If you have multiple environments configured, run `/remote-env` to choose which one to use when starting web sessions from your terminal with `&` or `--remote`. With a single environment, this command shows your current configuration.246**To select your default environment from the terminal:** If you have multiple environments configured, run `/remote-env` to choose which one to use when starting web sessions from your terminal with `--remote`. With a single environment, this command shows your current configuration.

203 247 

204<Note>248<Note>

205 Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:249 Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:

206 250 

207 ```251 ```text theme={null}

208 API_KEY=your_api_key252 API_KEY=your_api_key

209 DEBUG=true253 DEBUG=true

210 ```254 ```

211</Note>255</Note>

212 256 

257### Setup scripts

258 

259A setup script is a Bash script that runs when a new cloud session starts, before Claude Code launches. Use setup scripts to install dependencies, configure tools, or prepare anything the cloud environment needs that isn't in the [default image](#default-image).

260 

261Scripts run as root on Ubuntu 24.04, so `apt install` and most language package managers work.

262 

263<Tip>

264 To check what's already installed before adding it to your script, ask Claude to run `check-tools` in a cloud session.

265</Tip>

266 

267To add a setup script, open the environment settings dialog and enter your script in the **Setup script** field.

268 

269This example installs the `gh` CLI, which isn't in the default image:

270 

271```bash theme={null}

272#!/bin/bash

273apt update && apt install -y gh

274```

275 

276Setup scripts run only when creating a new session. They are skipped when resuming an existing session.

277 

278If the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands to avoid blocking the session on a flaky install.

279 

280<Note>

281 Setup scripts that install packages need network access to reach registries. The default network access allows connections to [common package registries](#default-allowed-domains) including npm, PyPI, RubyGems, and crates.io. Scripts will fail to install packages if your environment has network access disabled.

282</Note>

283 

284#### Setup scripts vs. SessionStart hooks

285 

286Use a setup script to install things the cloud needs but your laptop already has, like a language runtime or CLI tool. Use a [SessionStart hook](/en/hooks#sessionstart) for project setup that should run everywhere, cloud and local, like `npm install`.

287 

288Both run at the start of a session, but they belong to different places:

289 

290| | Setup scripts | SessionStart hooks |

291| ------------- | ------------------------------------------------- | -------------------------------------------------------------- |

292| Attached to | The cloud environment | Your repository |

293| Configured in | Cloud environment UI | `.claude/settings.json` in your repo |

294| Runs | Before Claude Code launches, on new sessions only | After Claude Code launches, on every session including resumed |

295| Scope | Cloud environments only | Both local and cloud |

296 

297SessionStart hooks can also be defined in your user-level `~/.claude/settings.json` locally, but user-level settings don't carry over to cloud sessions. In the cloud, only hooks committed to the repo run.

298 

213### Dependency management299### Dependency management

214 300 

215Configure automatic dependency installation using [SessionStart hooks](/en/hooks#sessionstart). This can be configured in your repository's `.claude/settings.json` file:301Custom environment images and snapshots are not yet supported. Use [setup scripts](#setup-scripts) to install packages when a session starts, or [SessionStart hooks](/en/hooks#sessionstart) for dependency installation that should also run in local environments. SessionStart hooks have [known limitations](#dependency-management-limitations).

302 

303To configure automatic dependency installation with a setup script, open your environment settings and add a script:

304 

305```bash theme={null}

306#!/bin/bash

307npm install

308pip install -r requirements.txt

309```

310 

311Alternatively, you can use SessionStart hooks in your repository's `.claude/settings.json` file for dependency installation that should also run in local environments:

216 312 

217```json theme={null}313```json theme={null}

218{314{


234 330 

235Create the corresponding script at `scripts/install_pkgs.sh`:331Create the corresponding script at `scripts/install_pkgs.sh`:

236 332 

237```bash theme={null}

238#!/bin/bash

239npm install

240pip install -r requirements.txt

241exit 0

242```

243 

244Make it executable: `chmod +x scripts/install_pkgs.sh`

245 

246#### Local vs remote execution

247 

248By default, all hooks execute both locally and in remote (web) environments. To run a hook only in one environment, check the `CLAUDE_CODE_REMOTE` environment variable in your hook script.

249 

250```bash theme={null}333```bash theme={null}

251#!/bin/bash334#!/bin/bash

252 335 

253# Example: Only run in remote environments336# Only run in remote environments

254if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then337if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then

255 exit 0338 exit 0

256fi339fi

257 340 

258npm install341npm install

259pip install -r requirements.txt342pip install -r requirements.txt

343exit 0

260```344```

261 345 

262#### Persisting environment variables346Make it executable: `chmod +x scripts/install_pkgs.sh`

347 

348#### Persist environment variables

349 

350SessionStart hooks can persist environment variables for subsequent Bash commands by writing to the file specified in the `CLAUDE_ENV_FILE` environment variable. For details, see [SessionStart hooks](/en/hooks#sessionstart) in the hooks reference.

263 351 

264SessionStart hooks can persist environment variables for subsequent bash commands by writing to the file specified in the `CLAUDE_ENV_FILE` environment variable. For details, see [SessionStart hooks](/en/hooks#sessionstart) in the hooks reference.352#### Dependency management limitations

353 

354* **Hooks fire for all sessions**: SessionStart hooks run in both local and remote environments. There is no hook configuration to scope a hook to remote sessions only. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable in your script as shown above.

355* **Requires network access**: Install commands need network access to reach package registries. If your environment is configured with "No internet" access, these hooks will fail. Use "Limited" (the default) or "Full" network access. The [default allowlist](#default-allowed-domains) includes common registries like npm, PyPI, RubyGems, and crates.io.

356* **Proxy compatibility**: All outbound traffic in remote environments passes through a [security proxy](#security-proxy). Some package managers do not work correctly with this proxy. Bun is a known example.

357* **Runs on every session start**: Hooks run each time a session starts or resumes, adding startup latency. Keep install scripts fast by checking whether dependencies are already present before reinstalling.

265 358 

266## Network access and security359## Network access and security

267 360 


297 390 

298* api.anthropic.com391* api.anthropic.com

299* statsig.anthropic.com392* statsig.anthropic.com

300* docs.claude.com393* platform.claude.com

301* code.claude.com394* code.claude.com

302* claude.ai395* claude.ai

303 396 


433* gradle.org526* gradle.org

434* [www.gradle.org](http://www.gradle.org)527* [www.gradle.org](http://www.gradle.org)

435* services.gradle.org528* services.gradle.org

529* plugins.gradle.org

530* kotlin.org

531* [www.kotlin.org](http://www.kotlin.org)

436* spring.io532* spring.io

437* repo.spring.io533* repo.spring.io

438 534 


565 661 

566## Best practices662## Best practices

567 663 

5681. **Use Claude Code hooks**: Configure [SessionStart hooks](/en/hooks#sessionstart) to automate environment setup and dependency installation.6641. **Automate environment setup**: Use [setup scripts](#setup-scripts) to install dependencies and configure tools before Claude Code launches. For more advanced scenarios, configure [SessionStart hooks](/en/hooks#sessionstart).

5692. **Document requirements**: Clearly specify dependencies and commands in your `CLAUDE.md` file. If you have an `AGENTS.md` file, you can source it in your `CLAUDE.md` using `@AGENTS.md` to maintain a single source of truth.6652. **Document requirements**: Clearly specify dependencies and commands in your `CLAUDE.md` file. If you have an `AGENTS.md` file, you can source it in your `CLAUDE.md` using `@AGENTS.md` to maintain a single source of truth.

570 666 

571## Related resources667## Related resources


574* [Settings reference](/en/settings)670* [Settings reference](/en/settings)

575* [Security](/en/security)671* [Security](/en/security)

576* [Data usage](/en/data-usage)672* [Data usage](/en/data-usage)

577 

578 

579 

580> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

cli-reference.md +49 −93

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# CLI reference5# CLI reference

2 6 

3> Complete reference for Claude Code command-line interface, including commands and flags.7> Complete reference for Claude Code command-line interface, including commands and flags.

4 8 

5## CLI commands9## CLI commands

6 10 

11You can start sessions, pipe content, resume conversations, and manage updates with these commands:

12 

7| Command | Description | Example |13| Command | Description | Example |

8| :------------------------------ | :----------------------------------------------------- | :------------------------------------------------ |14| :------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |

9| `claude` | Start interactive REPL | `claude` |15| `claude` | Start interactive session | `claude` |

10| `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` |16| `claude "query"` | Start interactive session with initial prompt | `claude "explain this project"` |

11| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |17| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |

12| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |18| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |

13| `claude -c` | Continue most recent conversation in current directory | `claude -c` |19| `claude -c` | Continue most recent conversation in current directory | `claude -c` |

14| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |20| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |

15| `claude -r "<session>" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` |21| `claude -r "<session>" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` |

16| `claude update` | Update to latest version | `claude update` |22| `claude update` | Update to latest version | `claude update` |

23| `claude auth login` | Sign in to your Anthropic account. Use `--email` to pre-fill your email address and `--sso` to force SSO authentication | `claude auth login --email user@example.com --sso` |

24| `claude auth logout` | Log out from your Anthropic account | `claude auth logout` |

25| `claude auth status` | Show authentication status as JSON. Use `--text` for human-readable output. Exits with code 0 if logged in, 1 if not | `claude auth status` |

26| `claude agents` | List all configured [subagents](/en/sub-agents), grouped by source | `claude agents` |

17| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](/en/mcp). |27| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](/en/mcp). |

28| `claude remote-control` | Start a [Remote Control](/en/remote-control) server to control Claude Code from Claude.ai or the Claude app. Runs in server mode (no local interactive session). See [Server mode flags](/en/remote-control#server-mode) | `claude remote-control --name "My Project"` |

18 29 

19## CLI flags30## CLI flags

20 31 

21Customize Claude Code's behavior with these command-line flags:32Customize Claude Code's behavior with these command-line flags:

22 33 

23| Flag | Description | Example |34| Flag | Description | Example |

24| :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |35| :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |

25| `--add-dir` | Add additional working directories for Claude to access (validates each path exists as a directory) | `claude --add-dir ../apps ../lib` |36| `--add-dir` | Add additional working directories for Claude to access (validates each path exists as a directory) | `claude --add-dir ../apps ../lib` |

26| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |37| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |

27| `--agents` | Define custom [subagents](/en/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |38| `--agents` | Define custom subagents dynamically via JSON. Uses the same field names as subagent [frontmatter](/en/sub-agents#supported-frontmatter-fields), plus a `prompt` field for the agent's instructions | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |

28| `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |39| `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |

29| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log:*)" "Bash(git diff:*)" "Read"` |40| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"` |

30| `--append-system-prompt` | Append custom text to the end of the default system prompt (works in both interactive and print modes) | `claude --append-system-prompt "Always use TypeScript"` |41| `--append-system-prompt` | Append custom text to the end of the default system prompt | `claude --append-system-prompt "Always use TypeScript"` |

31| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt (print mode only) | `claude -p --append-system-prompt-file ./extra-rules.txt "query"` |42| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt | `claude --append-system-prompt-file ./extra-rules.txt` |

32| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |43| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |

33| `--chrome` | Enable [Chrome browser integration](/en/chrome) for web automation and testing | `claude --chrome` |44| `--chrome` | Enable [Chrome browser integration](/en/chrome) for web automation and testing | `claude --chrome` |

34| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` |45| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` |

35| `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` |46| `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` |

36| `--debug` | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`) | `claude --debug "api,mcp"` |47| `--debug` | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`) | `claude --debug "api,mcp"` |

37| `--disable-slash-commands` | Disable all skills and slash commands for this session | `claude --disable-slash-commands` |48| `--disable-slash-commands` | Disable all skills and commands for this session | `claude --disable-slash-commands` |

38| `--disallowedTools` | Tools that are removed from the model's context and cannot be used | `"Bash(git log:*)" "Bash(git diff:*)" "Edit"` |49| `--disallowedTools` | Tools that are removed from the model's context and cannot be used | `"Bash(git log *)" "Bash(git diff *)" "Edit"` |

50| `--effort` | Set the [effort level](/en/model-config#adjust-effort-level) for the current session. Options: `low`, `medium`, `high`, `max` (Opus 4.6 only). Session-scoped and does not persist to settings | `claude --effort high` |

39| `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` |51| `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` |

40| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |52| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |

53| `--from-pr` | Resume sessions linked to a specific GitHub PR. Accepts a PR number or URL. Sessions are automatically linked when created via `gh pr create` | `claude --from-pr 123` |

41| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` |54| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` |

42| `--init` | Run [Setup hooks](/en/hooks#setup) and start interactive mode | `claude --init` |55| `--init` | Run initialization hooks and start interactive mode | `claude --init` |

43| `--init-only` | Run [Setup hooks](/en/hooks#setup) and exit (no interactive session) | `claude --init-only` |56| `--init-only` | Run initialization hooks and exit (no interactive session) | `claude --init-only` |

44| `--include-partial-messages` | Include partial streaming events in output (requires `--print` and `--output-format=stream-json`) | `claude -p --output-format stream-json --include-partial-messages "query"` |57| `--include-partial-messages` | Include partial streaming events in output (requires `--print` and `--output-format=stream-json`) | `claude -p --output-format stream-json --include-partial-messages "query"` |

45| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |58| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |

46| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [Agent SDK Structured Outputs](https://docs.claude.com/en/docs/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |59| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](https://platform.claude.com/docs/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |

47| `--maintenance` | Run [Setup hooks](/en/hooks#setup) with maintenance trigger and exit | `claude --maintenance` |60| `--maintenance` | Run maintenance hooks and exit | `claude --maintenance` |

48| `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` |61| `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` |

49| `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default | `claude -p --max-turns 3 "query"` |62| `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default | `claude -p --max-turns 3 "query"` |

50| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` |63| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` |

51| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name | `claude --model claude-sonnet-4-5-20250929` |64| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name | `claude --model claude-sonnet-4-6` |

65| `--name`, `-n` | Set a display name for the session, shown in `/resume` and the terminal title. You can resume a named session with `claude --resume <name>`. <br /><br />[`/rename`](/en/commands) changes the name mid-session and also shows it on the prompt bar | `claude -n "my-feature-work"` |

52| `--no-chrome` | Disable [Chrome browser integration](/en/chrome) for this session | `claude --no-chrome` |66| `--no-chrome` | Disable [Chrome browser integration](/en/chrome) for this session | `claude --no-chrome` |

53| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only) | `claude -p --no-session-persistence "query"` |67| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only) | `claude -p --no-session-persistence "query"` |

54| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |68| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |

55| `--permission-mode` | Begin in a specified [permission mode](/en/iam#permission-modes) | `claude --permission-mode plan` |69| `--permission-mode` | Begin in a specified [permission mode](/en/permissions#permission-modes) | `claude --permission-mode plan` |

56| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |70| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |

57| `--plugin-dir` | Load plugins from directories for this session only (repeatable) | `claude --plugin-dir ./my-plugins` |71| `--plugin-dir` | Load plugins from a directory for this session only. Each flag takes one path. Repeat the flag for multiple directories: `--plugin-dir A --plugin-dir B` | `claude --plugin-dir ./my-plugins` |

58| `--print`, `-p` | Print response without interactive mode (see [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) for programmatic usage details) | `claude -p "query"` |72| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |

59| `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |73| `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |

74| `--remote-control`, `--rc` | Start an interactive session with [Remote Control](/en/remote-control#interactive-session) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session | `claude --remote-control "My Project"` |

60| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` |75| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` |

61| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |76| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |

62| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` |77| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` |

63| `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.json` |78| `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.json` |

64| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` |79| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` |

65| `--system-prompt` | Replace the entire system prompt with custom text (works in both interactive and print modes) | `claude --system-prompt "You are a Python expert"` |80| `--system-prompt` | Replace the entire system prompt with custom text | `claude --system-prompt "You are a Python expert"` |

66| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt (print mode only) | `claude -p --system-prompt-file ./custom-prompt.txt "query"` |81| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt | `claude --system-prompt-file ./custom-prompt.txt` |

67| `--teleport` | Resume a [web session](/en/claude-code-on-the-web) in your local terminal | `claude --teleport` |82| `--teleport` | Resume a [web session](/en/claude-code-on-the-web) in your local terminal | `claude --teleport` |

68| `--tools` | Restrict which built-in tools Claude can use (works in both interactive and print modes). Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |83| `--teammate-mode` | Set how [agent team](/en/agent-teams) teammates display: `auto` (default), `in-process`, or `tmux`. See [set up agent teams](/en/agent-teams#set-up-agent-teams) | `claude --teammate-mode in-process` |

69| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |84| `--tools` | Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |

85| `--verbose` | Enable verbose logging, shows full turn-by-turn output | `claude --verbose` |

70| `--version`, `-v` | Output the version number | `claude -v` |86| `--version`, `-v` | Output the version number | `claude -v` |

71 87| `--worktree`, `-w` | Start Claude in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) at `<repo>/.claude/worktrees/<name>`. If no name is given, one is auto-generated | `claude -w feature-auth` |

72<Tip>

73 The `--output-format json` flag is particularly useful for scripting and

74 automation, allowing you to parse Claude's responses programmatically.

75</Tip>

76 

77### Agents flag format

78 

79The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields:

80 

81| Field | Required | Description |

82| :------------ | :------- | :---------------------------------------------------------------------------------------------------------------------------------- |

83| `description` | Yes | Natural language description of when the subagent should be invoked |

84| `prompt` | Yes | The system prompt that guides the subagent's behavior |

85| `tools` | No | Array of specific tools the subagent can use (for example, `["Read", "Edit", "Bash"]`). If omitted, inherits all tools |

86| `model` | No | Model alias to use: `sonnet`, `opus`, `haiku`, or `inherit`. If omitted, defaults to `inherit` (uses the main conversation's model) |

87 

88Example:

89 

90```bash theme={null}

91claude --agents '{

92 "code-reviewer": {

93 "description": "Expert code reviewer. Use proactively after code changes.",

94 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",

95 "tools": ["Read", "Grep", "Glob", "Bash"],

96 "model": "sonnet"

97 },

98 "debugger": {

99 "description": "Debugging specialist for errors and test failures.",

100 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."

101 }

102}'

103```

104 

105For more details on creating and using subagents, see the [subagents documentation](/en/sub-agents).

106 88 

107### System prompt flags89### System prompt flags

108 90 

109Claude Code provides four flags for customizing the system prompt, each serving a different purpose:91Claude Code provides four flags for customizing the system prompt. All four work in both interactive and non-interactive modes.

110 92 

111| Flag | Behavior | Modes | Use Case |93| Flag | Behavior | Example |

112| :---------------------------- | :------------------------------------------ | :------------------ | :------------------------------------------------------------------- |94| :---------------------------- | :------------------------------------------ | :------------------------------------------------------ |

113| `--system-prompt` | **Replaces** entire default prompt | Interactive + Print | Complete control over Claude's behavior and instructions |95| `--system-prompt` | Replaces the entire default prompt | `claude --system-prompt "You are a Python expert"` |

114| `--system-prompt-file` | **Replaces** with file contents | Print only | Load prompts from files for reproducibility and version control |96| `--system-prompt-file` | Replaces with file contents | `claude --system-prompt-file ./prompts/review.txt` |

115| `--append-system-prompt` | **Appends** to default prompt | Interactive + Print | Add specific instructions while keeping default Claude Code behavior |97| `--append-system-prompt` | Appends to the default prompt | `claude --append-system-prompt "Always use TypeScript"` |

116| `--append-system-prompt-file` | **Appends** file contents to default prompt | Print only | Load additional instructions from files while keeping defaults |98| `--append-system-prompt-file` | Appends file contents to the default prompt | `claude --append-system-prompt-file ./style-rules.txt` |

117 99 

118**When to use each:**100`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be combined with either replacement flag.

119 101 

120* **`--system-prompt`**: Use when you need complete control over Claude's system prompt. This removes all default Claude Code instructions, giving you a blank slate.102For most use cases, use an append flag. Appending preserves Claude Code's built-in capabilities while adding your requirements. Use a replacement flag only when you need complete control over the system prompt.

121 ```bash theme={null}

122 claude --system-prompt "You are a Python expert who only writes type-annotated code"

123 ```

124 

125* **`--system-prompt-file`**: Use when you want to load a custom prompt from a file, useful for team consistency or version-controlled prompt templates.

126 ```bash theme={null}

127 claude -p --system-prompt-file ./prompts/code-review.txt "Review this PR"

128 ```

129 

130* **`--append-system-prompt`**: Use when you want to add specific instructions while keeping Claude Code's default capabilities intact. This is the safest option for most use cases.

131 ```bash theme={null}

132 claude --append-system-prompt "Always use TypeScript and include JSDoc comments"

133 ```

134 

135* **`--append-system-prompt-file`**: Use when you want to append instructions from a file while keeping Claude Code's defaults. Useful for version-controlled additions.

136 ```bash theme={null}

137 claude -p --append-system-prompt-file ./prompts/style-rules.txt "Review this PR"

138 ```

139 

140`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag.

141 

142For most use cases, `--append-system-prompt` or `--append-system-prompt-file` is recommended as they preserve Claude Code's built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt.

143 103 

144## See also104## See also

145 105 


148* [Quickstart guide](/en/quickstart) - Getting started with Claude Code108* [Quickstart guide](/en/quickstart) - Getting started with Claude Code

149* [Common workflows](/en/common-workflows) - Advanced workflows and patterns109* [Common workflows](/en/common-workflows) - Advanced workflows and patterns

150* [Settings](/en/settings) - Configuration options110* [Settings](/en/settings) - Configuration options

151* [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) - Programmatic usage and integrations111* [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) - Programmatic usage and integrations

152 

153 

154 

155> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

code-review.md +187 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Code Review

6 

7> Set up automated PR reviews that catch logic errors, security vulnerabilities, and regressions using multi-agent analysis of your full codebase

8 

9<Note>

10 Code Review is in research preview, available for [Teams and Enterprise](https://claude.ai/admin-settings/claude-code) subscriptions. It is not available for organizations with [Zero Data Retention](/en/zero-data-retention) enabled.

11</Note>

12 

13Code Review analyzes your GitHub pull requests and posts findings as inline comments on the lines of code where it found issues. A fleet of specialized agents examine the code changes in the context of your full codebase, looking for logic errors, security vulnerabilities, broken edge cases, and subtle regressions.

14 

15Findings are tagged by severity and don't approve or block your PR, so existing review workflows stay intact. You can tune what Claude flags by adding a `CLAUDE.md` or `REVIEW.md` file to your repository.

16 

17To run Claude in your own CI infrastructure instead of this managed service, see [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd).

18 

19This page covers:

20 

21* [How reviews work](#how-reviews-work)

22* [Setup](#set-up-code-review)

23* [Customizing reviews](#customize-reviews) with `CLAUDE.md` and `REVIEW.md`

24* [Pricing](#pricing)

25 

26## How reviews work

27 

28Once an admin [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting `@claude review` [starts reviews on a PR](#manually-trigger-reviews) in any mode.

29 

30When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found. If no issues are found, Claude posts a short confirmation comment on the PR.

31 

32Reviews scale in cost with PR size and complexity, completing in 20 minutes on average. Admins can monitor review activity and spend via the [analytics dashboard](#view-usage).

33 

34### Severity levels

35 

36Each finding is tagged with a severity level:

37 

38| Marker | Severity | Meaning |

39| :----- | :----------- | :------------------------------------------------------------------ |

40| 🔴 | Normal | A bug that should be fixed before merging |

41| 🟡 | Nit | A minor issue, worth fixing but not blocking |

42| 🟣 | Pre-existing | A bug that exists in the codebase but was not introduced by this PR |

43 

44Findings include a collapsible extended reasoning section you can expand to understand why Claude flagged the issue and how it verified the problem.

45 

46### What Code Review checks

47 

48By default, Code Review focuses on correctness: bugs that would break production, not formatting preferences or missing test coverage. You can expand what it checks by [adding guidance files](#customize-reviews) to your repository.

49 

50## Set up Code Review

51 

52An admin enables Code Review once for the organization and selects which repositories to include.

53 

54<Steps>

55 <Step title="Open Claude Code admin settings">

56 Go to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and find the Code Review section. You need admin access to your Claude organization and permission to install GitHub Apps in your GitHub organization.

57 </Step>

58 

59 <Step title="Start setup">

60 Click **Setup**. This begins the GitHub App installation flow.

61 </Step>

62 

63 <Step title="Install the Claude GitHub App">

64 Follow the prompts to install the Claude GitHub App to your GitHub organization. The app requests these repository permissions:

65 

66 * **Contents**: read and write

67 * **Issues**: read and write

68 * **Pull requests**: read and write

69 

70 Code Review uses read access to contents and write access to pull requests. The broader permission set also supports [GitHub Actions](/en/github-actions) if you enable that later.

71 </Step>

72 

73 <Step title="Select repositories">

74 Choose which repositories to enable for Code Review. If you don't see a repository, make sure you gave the Claude GitHub App access to it during installation. You can add more repositories later.

75 </Step>

76 

77 <Step title="Set review triggers per repo">

78 After setup completes, the Code Review section shows your repositories in a table. For each repository, use the **Review Behavior** dropdown to choose when reviews run:

79 

80 * **Once after PR creation**: review runs once when a PR is opened or marked ready for review

81 * **After every push**: review runs on every push to the PR branch, catching new issues as the PR evolves and auto-resolving threads when you fix flagged issues

82 * **Manual**: reviews start only when someone [comments `@claude review` on a PR](#manually-trigger-reviews); subsequent pushes to that PR are then reviewed automatically

83 

84 Reviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they're ready.

85 </Step>

86</Steps>

87 

88The repositories table also shows the average cost per review for each repo based on recent activity. Use the row actions menu to turn Code Review on or off per repository, or to remove a repository entirely.

89 

90To verify setup, open a test PR. If you chose an automatic trigger, a check run named **Claude Code Review** appears within a few minutes. If you chose Manual, comment `@claude review` on the PR to start the first review. If no check run appears, confirm the repository is listed in your admin settings and the Claude GitHub App has access to it.

91 

92## Manually trigger reviews

93 

94Comment `@claude review` on a pull request to start a review and opt that PR into push-triggered reviews going forward. This works regardless of the repository's configured trigger: use it to opt specific PRs into review in Manual mode, or to get an immediate re-review in other modes. Either way, pushes to that PR trigger reviews from then on.

95 

96For the comment to trigger a review:

97 

98* Post it as a top-level PR comment, not an inline comment on a diff line

99* Put `@claude review` at the start of the comment

100* You must have owner, member, or collaborator access to the repository

101* The PR must be open and not a draft

102 

103If a review is already running on that PR, the request is queued until the in-progress review completes. You can monitor progress via the check run on the PR.

104 

105## Customize reviews

106 

107Code Review reads two files from your repository to guide what it flags. Both are additive on top of the default correctness checks:

108 

109* **`CLAUDE.md`**: shared project instructions that Claude Code uses for all tasks, not just reviews. Use it when guidance also applies to interactive Claude Code sessions.

110* **`REVIEW.md`**: review-only guidance, read exclusively during code reviews. Use it for rules that are strictly about what to flag or skip during review and would clutter your general `CLAUDE.md`.

111 

112### CLAUDE.md

113 

114Code Review reads your repository's `CLAUDE.md` files and treats newly-introduced violations as nit-level findings. This works bidirectionally: if your PR changes code in a way that makes a `CLAUDE.md` statement outdated, Claude flags that the docs need updating too.

115 

116Claude reads `CLAUDE.md` files at every level of your directory hierarchy, so rules in a subdirectory's `CLAUDE.md` apply only to files under that path. See the [memory documentation](/en/memory) for more on how `CLAUDE.md` works.

117 

118For review-specific guidance that you don't want applied to general Claude Code sessions, use [`REVIEW.md`](#review-md) instead.

119 

120### REVIEW\.md

121 

122Add a `REVIEW.md` file to your repository root for review-specific rules. Use it to encode:

123 

124* Company or team style guidelines: "prefer early returns over nested conditionals"

125* Language- or framework-specific conventions not covered by linters

126* Things Claude should always flag: "any new API route must have an integration test"

127* Things Claude should skip: "don't comment on formatting in generated code under `/gen/`"

128 

129Example `REVIEW.md`:

130 

131```markdown theme={null}

132# Code Review Guidelines

133 

134## Always check

135- New API endpoints have corresponding integration tests

136- Database migrations are backward-compatible

137- Error messages don't leak internal details to users

138 

139## Style

140- Prefer `match` statements over chained `isinstance` checks

141- Use structured logging, not f-string interpolation in log calls

142 

143## Skip

144- Generated files under `src/gen/`

145- Formatting-only changes in `*.lock` files

146```

147 

148Claude auto-discovers `REVIEW.md` at the repository root. No configuration needed.

149 

150## View usage

151 

152Go to [claude.ai/analytics/code-review](https://claude.ai/analytics/code-review) to see Code Review activity across your organization. The dashboard shows:

153 

154| Section | What it shows |

155| :------------------- | :--------------------------------------------------------------------------------------- |

156| PRs reviewed | Daily count of pull requests reviewed over the selected time range |

157| Cost weekly | Weekly spend on Code Review |

158| Feedback | Count of review comments that were auto-resolved because a developer addressed the issue |

159| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved |

160 

161The repositories table in admin settings also shows average cost per review for each repo.

162 

163## Pricing

164 

165Code Review is billed based on token usage. Reviews average \$15-25, scaling with PR size, codebase complexity, and how many issues require verification. Code Review usage is billed separately through [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) and does not count against your plan's included usage.

166 

167The review trigger you choose affects total cost:

168 

169* **Once after PR creation**: runs once per PR

170* **After every push**: runs on each push, multiplying cost by the number of pushes

171* **Manual**: no reviews until someone comments `@claude review` on a PR

172 

173In any mode, commenting `@claude review` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment.

174 

175Costs appear on your Anthropic bill regardless of whether your organization uses AWS Bedrock or Google Vertex AI for other Claude Code features. To set a monthly spend cap for Code Review, go to [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) and configure the limit for the Claude Code Review service.

176 

177Monitor spend via the weekly cost chart in [analytics](#view-usage) or the per-repo average cost column in admin settings.

178 

179## Related resources

180 

181Code Review is designed to work alongside the rest of Claude Code. If you want to run reviews locally before opening a PR, need a self-hosted setup, or want to go deeper on how `CLAUDE.md` shapes Claude's behavior across tools, these pages are good next stops:

182 

183* [Plugins](/en/discover-plugins): browse the plugin marketplace, including a `code-review` plugin for running on-demand reviews locally before pushing

184* [GitHub Actions](/en/github-actions): run Claude in your own GitHub Actions workflows for custom automation beyond code review

185* [GitLab CI/CD](/en/gitlab-ci-cd): self-hosted Claude integration for GitLab pipelines

186* [Memory](/en/memory): how `CLAUDE.md` files work across Claude Code

187* [Analytics](/en/analytics): track Claude Code usage beyond code review

commands.md +88 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Built-in commands

6 

7> Complete reference for built-in commands available in Claude Code.

8 

9Type `/` in Claude Code to see all available commands, or type `/` followed by any letters to filter. Not all commands are visible to every user. Some depend on your platform, plan, or environment. For example, `/desktop` only appears on macOS and Windows, `/upgrade` and `/privacy-settings` are only available on Pro and Max plans, and `/terminal-setup` is hidden when your terminal natively supports its keybindings.

10 

11Claude Code also includes [bundled skills](/en/skills#bundled-skills) like `/simplify`, `/batch`, and `/debug` that appear alongside built-in commands when you type `/`. To create your own commands, see [skills](/en/skills).

12 

13In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

14 

15| Command | Purpose |

16| :--------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

17| `/add-dir <path>` | Add a new working directory to the current session |

18| `/agents` | Manage [agent](/en/sub-agents) configurations |

19| `/btw <question>` | Ask a quick [side question](/en/interactive-mode#side-questions-with-btw) without adding to the conversation |

20| `/chrome` | Configure [Claude in Chrome](/en/chrome) settings |

21| `/clear` | Clear conversation history and free up context. Aliases: `/reset`, `/new` |

22| `/color [color\|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset |

23| `/compact [instructions]` | Compact conversation with optional focus instructions |

24| `/config` | Open the [Settings](/en/settings) interface to adjust theme, model, [output style](/en/output-styles), and other preferences. Alias: `/settings` |

25| `/context` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings |

26| `/copy` | Copy the last assistant response to clipboard. When code blocks are present, shows an interactive picker to select individual blocks or the full response |

27| `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details |

28| `/desktop` | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app` |

29| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files |

30| `/doctor` | Diagnose and verify your Claude Code installation and settings |

31| `/effort [low\|medium\|high\|max\|auto]` | Set the model [effort level](/en/model-config#adjust-effort-level). `low`, `medium`, and `high` persist across sessions. `max` applies to the current session only and requires Opus 4.6. `auto` resets to the model default. Without an argument, shows the current level. Takes effect immediately without waiting for the current response to finish |

32| `/exit` | Exit the CLI. Alias: `/quit` |

33| `/export [filename]` | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file |

34| `/extra-usage` | Configure extra usage to keep working when rate limits are hit |

35| `/fast [on\|off]` | Toggle [fast mode](/en/fast-mode) on or off |

36| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |

37| `/fork [name]` | Create a fork of the current conversation at this point |

38| `/help` | Show help and available commands |

39| `/hooks` | View [hook](/en/hooks) configurations for tool events |

40| `/ide` | Manage IDE integrations and show status |

41| `/init` | Initialize project with `CLAUDE.md` guide |

42| `/insights` | Generate a report analyzing your Claude Code sessions, including project areas, interaction patterns, and friction points |

43| `/install-github-app` | Set up the [Claude GitHub Actions](/en/github-actions) app for a repository. Walks you through selecting a repo and configuring the integration |

44| `/install-slack-app` | Install the Claude Slack app. Opens a browser to complete the OAuth flow |

45| `/keybindings` | Open or create your keybindings configuration file |

46| `/login` | Sign in to your Anthropic account |

47| `/logout` | Sign out from your Anthropic account |

48| `/mcp` | Manage MCP server connections and OAuth authentication |

49| `/memory` | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/en/memory#auto-memory), and view auto-memory entries |

50| `/mobile` | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` |

51| `/model [model]` | Select or change the AI model. For models that support it, use left/right arrows to [adjust effort level](/en/model-config#adjust-effort-level). The change takes effect immediately without waiting for the current response to finish |

52| `/passes` | Share a free week of Claude Code with friends. Only visible if your account is eligible |

53| `/permissions` | View or update [permissions](/en/permissions#manage-permissions). Alias: `/allowed-tools` |

54| `/plan` | Enter plan mode directly from the prompt |

55| `/plugin` | Manage Claude Code [plugins](/en/plugins) |

56| `/pr-comments [PR]` | Fetch and display comments from a GitHub pull request. Automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI |

57| `/privacy-settings` | View and update your privacy settings. Only available for Pro and Max plan subscribers |

58| `/release-notes` | View the full changelog, with the most recent version closest to your prompt |

59| `/reload-plugins` | Reload all active [plugins](/en/plugins) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors |

60| `/remote-control` | Make this session available for [remote control](/en/remote-control) from claude.ai. Alias: `/rc` |

61| `/remote-env` | Configure the default remote environment for [web sessions started with `--remote`](/en/claude-code-on-the-web#environment-configuration) |

62| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history |

63| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. Alias: `/continue` |

64| `/review` | Deprecated. Install the [`code-review` plugin](https://github.com/anthropics/claude-code-marketplace/blob/main/code-review/README.md) instead: `claude plugin install code-review@claude-code-marketplace` |

65| `/rewind` | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](/en/checkpointing). Alias: `/checkpoint` |

66| `/sandbox` | Toggle [sandbox mode](/en/sandboxing). Available on supported platforms only |

67| `/security-review` | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure |

68| `/skills` | List available [skills](/en/skills) |

69| `/stats` | Visualize daily usage, session history, streaks, and model preferences |

70| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |

71| `/statusline` | Configure Claude Code's [status line](/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |

72| `/stickers` | Order Claude Code stickers |

73| `/tasks` | List and manage background tasks |

74| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Alacritty, or Warp |

75| `/theme` | Change the color theme. Includes light and dark variants, colorblind-accessible (daltonized) themes, and ANSI themes that use your terminal's color palette |

76| `/upgrade` | Open the upgrade page to switch to a higher plan tier |

77| `/usage` | Show plan usage limits and rate limit status |

78| `/vim` | Toggle between Vim and Normal editing modes |

79 

80## MCP prompts

81 

82MCP servers can expose prompts that appear as commands. These use the format `/mcp__<server>__<prompt>` and are dynamically discovered from connected servers. See [MCP prompts](/en/mcp#use-mcp-prompts-as-commands) for details.

83 

84## See also

85 

86* [Skills](/en/skills): create your own commands

87* [Interactive mode](/en/interactive-mode): keyboard shortcuts, Vim mode, and command history

88* [CLI reference](/en/cli-reference): launch-time flags

common-workflows.md +291 −194

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Common workflows5# Common workflows

2 6 

3> Step-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code.7> Step-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code.


24 </Step>28 </Step>

25 29 

26 <Step title="Ask for a high-level overview">30 <Step title="Ask for a high-level overview">

27 ```31 ```text theme={null}

28 > give me an overview of this codebase 32 give me an overview of this codebase

29 ```33 ```

30 </Step>34 </Step>

31 35 

32 <Step title="Dive deeper into specific components">36 <Step title="Dive deeper into specific components">

33 ```37 ```text theme={null}

34 > explain the main architecture patterns used here 38 explain the main architecture patterns used here

35 ```39 ```

36 40 

37 ```41 ```text theme={null}

38 > what are the key data models?42 what are the key data models?

39 ```43 ```

40 44 

41 ```45 ```text theme={null}

42 > how is authentication handled?46 how is authentication handled?

43 ```47 ```

44 </Step>48 </Step>

45</Steps>49</Steps>


58 62 

59<Steps>63<Steps>

60 <Step title="Ask Claude to find relevant files">64 <Step title="Ask Claude to find relevant files">

61 ```65 ```text theme={null}

62 > find the files that handle user authentication 66 find the files that handle user authentication

63 ```67 ```

64 </Step>68 </Step>

65 69 

66 <Step title="Get context on how components interact">70 <Step title="Get context on how components interact">

67 ```71 ```text theme={null}

68 > how do these authentication files work together? 72 how do these authentication files work together?

69 ```73 ```

70 </Step>74 </Step>

71 75 

72 <Step title="Understand the execution flow">76 <Step title="Understand the execution flow">

73 ```77 ```text theme={null}

74 > trace the login process from front-end to database 78 trace the login process from front-end to database

75 ```79 ```

76 </Step>80 </Step>

77</Steps>81</Steps>


92 96 

93<Steps>97<Steps>

94 <Step title="Share the error with Claude">98 <Step title="Share the error with Claude">

95 ```99 ```text theme={null}

96 > I'm seeing an error when I run npm test 100 I'm seeing an error when I run npm test

97 ```101 ```

98 </Step>102 </Step>

99 103 

100 <Step title="Ask for fix recommendations">104 <Step title="Ask for fix recommendations">

101 ```105 ```text theme={null}

102 > suggest a few ways to fix the @ts-ignore in user.ts 106 suggest a few ways to fix the @ts-ignore in user.ts

103 ```107 ```

104 </Step>108 </Step>

105 109 

106 <Step title="Apply the fix">110 <Step title="Apply the fix">

107 ```111 ```text theme={null}

108 > update user.ts to add the null check you suggested 112 update user.ts to add the null check you suggested

109 ```113 ```

110 </Step>114 </Step>

111</Steps>115</Steps>


126 130 

127<Steps>131<Steps>

128 <Step title="Identify legacy code for refactoring">132 <Step title="Identify legacy code for refactoring">

129 ```133 ```text theme={null}

130 > find deprecated API usage in our codebase 134 find deprecated API usage in our codebase

131 ```135 ```

132 </Step>136 </Step>

133 137 

134 <Step title="Get refactoring recommendations">138 <Step title="Get refactoring recommendations">

135 ```139 ```text theme={null}

136 > suggest how to refactor utils.js to use modern JavaScript features 140 suggest how to refactor utils.js to use modern JavaScript features

137 ```141 ```

138 </Step>142 </Step>

139 143 

140 <Step title="Apply the changes safely">144 <Step title="Apply the changes safely">

141 ```145 ```text theme={null}

142 > refactor utils.js to use ES2024 features while maintaining the same behavior 146 refactor utils.js to use ES2024 features while maintaining the same behavior

143 ```147 ```

144 </Step>148 </Step>

145 149 

146 <Step title="Verify the refactoring">150 <Step title="Verify the refactoring">

147 ```151 ```text theme={null}

148 > run tests for the refactored code 152 run tests for the refactored code

149 ```153 ```

150 </Step>154 </Step>

151</Steps>155</Steps>


166 170 

167<Steps>171<Steps>

168 <Step title="View available subagents">172 <Step title="View available subagents">

169 ```173 ```text theme={null}

170 > /agents174 /agents

171 ```175 ```

172 176 

173 This shows all available subagents and lets you create new ones.177 This shows all available subagents and lets you create new ones.


176 <Step title="Use subagents automatically">180 <Step title="Use subagents automatically">

177 Claude Code automatically delegates appropriate tasks to specialized subagents:181 Claude Code automatically delegates appropriate tasks to specialized subagents:

178 182 

179 ```183 ```text theme={null}

180 > review my recent code changes for security issues184 review my recent code changes for security issues

181 ```185 ```

182 186 

183 ```187 ```text theme={null}

184 > run all tests and fix any failures188 run all tests and fix any failures

185 ```189 ```

186 </Step>190 </Step>

187 191 

188 <Step title="Explicitly request specific subagents">192 <Step title="Explicitly request specific subagents">

189 ```193 ```text theme={null}

190 > use the code-reviewer subagent to check the auth module194 use the code-reviewer subagent to check the auth module

191 ```195 ```

192 196 

193 ```197 ```text theme={null}

194 > have the debugger subagent investigate why users can't log in198 have the debugger subagent investigate why users can't log in

195 ```199 ```

196 </Step>200 </Step>

197 201 

198 <Step title="Create custom subagents for your workflow">202 <Step title="Create custom subagents for your workflow">

199 ```203 ```text theme={null}

200 > /agents204 /agents

201 ```205 ```

202 206 

203 Then select "Create New subagent" and follow the prompts to define:207 Then select "Create New subagent" and follow the prompts to define:


222 226 

223## Use Plan Mode for safe code analysis227## Use Plan Mode for safe code analysis

224 228 

225Plan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely. In Plan Mode, Claude uses [`AskUserQuestion`](/en/settings#tools-available-to-claude) to gather requirements and clarify your goals before proposing a plan.229Plan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely. In Plan Mode, Claude uses [`AskUserQuestion`](/en/tools-reference) to gather requirements and clarify your goals before proposing a plan.

226 230 

227### When to use Plan Mode231### When to use Plan Mode

228 232 


260claude --permission-mode plan264claude --permission-mode plan

261```265```

262 266 

263```267```text theme={null}

264> I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.268I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.

265```269```

266 270 

267Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:271Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:

268 272 

273```text theme={null}

274What about backward compatibility?

269```275```

270> What about backward compatibility?276 

271> How should we handle database migration?277```text theme={null}

278How should we handle database migration?

272```279```

273 280 

281<Tip>Press `Ctrl+G` to open the plan in your default text editor, where you can edit it directly before Claude proceeds.</Tip>

282 

274### Configure Plan Mode as default283### Configure Plan Mode as default

275 284 

276```json theme={null}285```json theme={null}


292 301 

293<Steps>302<Steps>

294 <Step title="Identify untested code">303 <Step title="Identify untested code">

295 ```304 ```text theme={null}

296 > find functions in NotificationsService.swift that are not covered by tests 305 find functions in NotificationsService.swift that are not covered by tests

297 ```306 ```

298 </Step>307 </Step>

299 308 

300 <Step title="Generate test scaffolding">309 <Step title="Generate test scaffolding">

301 ```310 ```text theme={null}

302 > add tests for the notification service 311 add tests for the notification service

303 ```312 ```

304 </Step>313 </Step>

305 314 

306 <Step title="Add meaningful test cases">315 <Step title="Add meaningful test cases">

307 ```316 ```text theme={null}

308 > add test cases for edge conditions in the notification service 317 add test cases for edge conditions in the notification service

309 ```318 ```

310 </Step>319 </Step>

311 320 

312 <Step title="Run and verify tests">321 <Step title="Run and verify tests">

313 ```322 ```text theme={null}

314 > run the new tests and fix any failures 323 run the new tests and fix any failures

315 ```324 ```

316 </Step>325 </Step>

317</Steps>326</Steps>


324 333 

325## Create pull requests334## Create pull requests

326 335 

327Suppose you need to create a well-documented pull request for your changes.336You can create pull requests by asking Claude directly ("create a pr for my changes"), or guide Claude through it step-by-step:

328 337 

329<Steps>338<Steps>

330 <Step title="Summarize your changes">339 <Step title="Summarize your changes">

331 ```340 ```text theme={null}

332 > summarize the changes I've made to the authentication module 341 summarize the changes I've made to the authentication module

333 ```342 ```

334 </Step>343 </Step>

335 344 

336 <Step title="Generate a pull request with Claude">345 <Step title="Generate a pull request">

337 ```346 ```text theme={null}

338 > create a pr 347 create a pr

339 ```348 ```

340 </Step>349 </Step>

341 350 

342 <Step title="Review and refine">351 <Step title="Review and refine">

343 ```352 ```text theme={null}

344 > enhance the PR description with more context about the security improvements 353 enhance the PR description with more context about the security improvements

345 ```

346 </Step>

347 

348 <Step title="Add testing details">

349 ```

350 > add information about how these changes were tested

351 ```354 ```

352 </Step>355 </Step>

353</Steps>356</Steps>

354 357 

355<Tip>358When you create a PR using `gh pr create`, the session is automatically linked to that PR. You can resume it later with `claude --from-pr <number>`.

356 Tips:

357 359 

358 * Ask Claude directly to make a PR for you360<Tip>

359 * Review Claude's generated PR before submitting361 Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations.

360 * Ask Claude to highlight potential risks or considerations

361</Tip>362</Tip>

362 363 

363## Handle documentation364## Handle documentation


366 367 

367<Steps>368<Steps>

368 <Step title="Identify undocumented code">369 <Step title="Identify undocumented code">

369 ```370 ```text theme={null}

370 > find functions without proper JSDoc comments in the auth module 371 find functions without proper JSDoc comments in the auth module

371 ```372 ```

372 </Step>373 </Step>

373 374 

374 <Step title="Generate documentation">375 <Step title="Generate documentation">

375 ```376 ```text theme={null}

376 > add JSDoc comments to the undocumented functions in auth.js 377 add JSDoc comments to the undocumented functions in auth.js

377 ```378 ```

378 </Step>379 </Step>

379 380 

380 <Step title="Review and enhance">381 <Step title="Review and enhance">

381 ```382 ```text theme={null}

382 > improve the generated documentation with more context and examples 383 improve the generated documentation with more context and examples

383 ```384 ```

384 </Step>385 </Step>

385 386 

386 <Step title="Verify documentation">387 <Step title="Verify documentation">

387 ```388 ```text theme={null}

388 > check if the documentation follows our project standards 389 check if the documentation follows our project standards

389 ```390 ```

390 </Step>391 </Step>

391</Steps>392</Steps>


414 </Step>415 </Step>

415 416 

416 <Step title="Ask Claude to analyze the image">417 <Step title="Ask Claude to analyze the image">

417 ```418 ```text theme={null}

418 > What does this image show?419 What does this image show?

419 ```420 ```

420 421 

421 ```422 ```text theme={null}

422 > Describe the UI elements in this screenshot423 Describe the UI elements in this screenshot

423 ```424 ```

424 425 

425 ```426 ```text theme={null}

426 > Are there any problematic elements in this diagram?427 Are there any problematic elements in this diagram?

427 ```428 ```

428 </Step>429 </Step>

429 430 

430 <Step title="Use images for context">431 <Step title="Use images for context">

431 ```432 ```text theme={null}

432 > Here's a screenshot of the error. What's causing it?433 Here's a screenshot of the error. What's causing it?

433 ```434 ```

434 435 

435 ```436 ```text theme={null}

436 > This is our current database schema. How should we modify it for the new feature?437 This is our current database schema. How should we modify it for the new feature?

437 ```438 ```

438 </Step>439 </Step>

439 440 

440 <Step title="Get code suggestions from visual content">441 <Step title="Get code suggestions from visual content">

441 ```442 ```text theme={null}

442 > Generate CSS to match this design mockup443 Generate CSS to match this design mockup

443 ```444 ```

444 445 

445 ```446 ```text theme={null}

446 > What HTML structure would recreate this component?447 What HTML structure would recreate this component?

447 ```448 ```

448 </Step>449 </Step>

449</Steps>450</Steps>


466 467 

467<Steps>468<Steps>

468 <Step title="Reference a single file">469 <Step title="Reference a single file">

469 ```470 ```text theme={null}

470 > Explain the logic in @src/utils/auth.js471 Explain the logic in @src/utils/auth.js

471 ```472 ```

472 473 

473 This includes the full content of the file in the conversation.474 This includes the full content of the file in the conversation.

474 </Step>475 </Step>

475 476 

476 <Step title="Reference a directory">477 <Step title="Reference a directory">

477 ```478 ```text theme={null}

478 > What's the structure of @src/components?479 What's the structure of @src/components?

479 ```480 ```

480 481 

481 This provides a directory listing with file information.482 This provides a directory listing with file information.

482 </Step>483 </Step>

483 484 

484 <Step title="Reference MCP resources">485 <Step title="Reference MCP resources">

485 ```486 ```text theme={null}

486 > Show me the data from @github:repos/owner/repo/issues487 Show me the data from @github:repos/owner/repo/issues

487 ```488 ```

488 489 

489 This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/mcp#use-mcp-resources) for details.490 This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/mcp#use-mcp-resources) for details.


503 504 

504## Use extended thinking (thinking mode)505## Use extended thinking (thinking mode)

505 506 

506[Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is enabled by default, reserving a portion of the output token budget (up to 31,999 tokens) for Claude to reason through complex problems step-by-step. This reasoning is visible in verbose mode, which you can toggle on with `Ctrl+O`.507[Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) is enabled by default, giving Claude space to reason through complex problems step-by-step before responding. This reasoning is visible in verbose mode, which you can toggle on with `Ctrl+O`.

507 508 

508Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches. It provides more space for exploring multiple solutions, analyzing edge cases, and self-correcting mistakes.509Additionally, Opus 4.6 and Sonnet 4.6 support adaptive reasoning: instead of a fixed thinking token budget, the model dynamically allocates thinking based on your [effort level](/en/model-config#adjust-effort-level) setting. Extended thinking and adaptive reasoning work together to give you control over how deeply Claude reasons before responding.

510 

511Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches.

509 512 

510<Note>513<Note>

511 Phrases like "think", "think hard", "ultrathink", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.514 Phrases like "think", "think hard", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.

512</Note>515</Note>

513 516 

514### Configure thinking mode517### Configure thinking mode


516Thinking is enabled by default, but you can adjust or disable it.519Thinking is enabled by default, but you can adjust or disable it.

517 520 

518| Scope | How to configure | Details |521| Scope | How to configure | Details |

519| ---------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |522| ------------------------ | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |

520| **Toggle shortcut** | Press `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle thinking on/off for the current session. May require [terminal configuration](/en/terminal-config) to enable Option key shortcuts |523| **Effort level** | Run `/effort`, adjust in `/model`, or set [`CLAUDE_CODE_EFFORT_LEVEL`](/en/env-vars) | Control thinking depth for Opus 4.6 and Sonnet 4.6. See [Adjust effort level](/en/model-config#adjust-effort-level) |

521| **Global default** | Use `/config` to toggle thinking mode | Sets your default across all projects.<br />Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` |524| **`ultrathink` keyword** | Include "ultrathink" anywhere in your prompt | Sets effort to high for that turn on Opus 4.6 and Sonnet 4.6. Useful for one-off tasks requiring deep reasoning without permanently changing your effort setting |

522| **Limit token budget** | Set [`MAX_THINKING_TOKENS`](/en/settings#environment-variables) environment variable | Limit the thinking budget to a specific number of tokens. Example: `export MAX_THINKING_TOKENS=10000` |525| **Toggle shortcut** | Press `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle thinking on/off for the current session (all models). May require [terminal configuration](/en/terminal-config) to enable Option key shortcuts |

526| **Global default** | Use `/config` to toggle thinking mode | Sets your default across all projects (all models).<br />Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` |

527| **Limit token budget** | Set [`MAX_THINKING_TOKENS`](/en/env-vars) environment variable | Limit the thinking budget to a specific number of tokens (ignored on Opus 4.6 and Sonnet 4.6 unless set to 0). Example: `export MAX_THINKING_TOKENS=10000` |

523 528 

524To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.529To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.

525 530 

526### How extended thinking token budgets work531### How extended thinking works

527 

528Extended thinking uses a **token budget** that controls how much internal reasoning Claude can perform before responding.

529 

530A larger thinking token budget provides:

531 532 

532* More space to explore multiple solution approaches step-by-step533Extended thinking controls how much internal reasoning Claude performs before responding. More thinking provides more space to explore solutions, analyze edge cases, and self-correct mistakes.

533* Room to analyze edge cases and evaluate tradeoffs thoroughly

534* Ability to revise reasoning and self-correct mistakes

535 534 

536Token budgets for thinking mode:535**With Opus 4.6 and Sonnet 4.6**, thinking uses adaptive reasoning: the model dynamically allocates thinking tokens based on the [effort level](/en/model-config#adjust-effort-level) you select. This is the recommended way to tune the tradeoff between speed and reasoning depth.

537 536 

538* When thinking is **enabled**, Claude can use up to **31,999 tokens** from your output budget for internal reasoning537**With older models**, thinking uses a fixed budget of up to 31,999 tokens from your output budget. You can limit this with the [`MAX_THINKING_TOKENS`](/en/env-vars) environment variable, or disable thinking entirely via `/config` or the `Option+T`/`Alt+T` toggle.

539* When thinking is **disabled** (via toggle or `/config`), Claude uses **0 tokens** for thinking

540 538 

541**Limit the thinking budget:**539`MAX_THINKING_TOKENS` is ignored on Opus 4.6 and Sonnet 4.6, since adaptive reasoning controls thinking depth instead. The one exception: setting `MAX_THINKING_TOKENS=0` still disables thinking entirely on any model. To disable adaptive thinking and revert to the fixed thinking budget, set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1`. See [environment variables](/en/env-vars).

542 

543* Use the [`MAX_THINKING_TOKENS` environment variable](/en/settings#environment-variables) to cap the thinking budget

544* When set, this value limits the maximum tokens Claude can use for thinking

545* See the [extended thinking documentation](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for valid token ranges

546 540 

547<Warning>541<Warning>

548 You're charged for all thinking tokens used, even though Claude 4 models show summarized thinking542 You're charged for all thinking tokens used, even though Claude 4 models show summarized thinking


556 550 

557* `claude --continue` continues the most recent conversation in the current directory551* `claude --continue` continues the most recent conversation in the current directory

558* `claude --resume` opens a conversation picker or resumes by name552* `claude --resume` opens a conversation picker or resumes by name

553* `claude --from-pr 123` resumes sessions linked to a specific pull request

559 554 

560From inside an active session, use `/resume` to switch to a different conversation.555From inside an active session, use `/resume` to switch to a different conversation.

561 556 


566Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features.561Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features.

567 562 

568<Steps>563<Steps>

569 <Step title="Name the current session">564 <Step title="Name the session">

570 Use `/rename` during a session to give it a memorable name:565 Name a session at startup with `-n`:

571 566 

567 ```bash theme={null}

568 claude -n auth-refactor

572 ```569 ```

573 > /rename auth-refactor570 

571 Or use `/rename` during a session, which also shows the name on the prompt bar:

572 

573 ```text theme={null}

574 /rename auth-refactor

574 ```575 ```

575 576 

576 You can also rename any session from the picker: run `/resume`, navigate to a session, and press `R`.577 You can also rename any session from the picker: run `/resume`, navigate to a session, and press `R`.


585 586 

586 Or from inside an active session:587 Or from inside an active session:

587 588 

588 ```589 ```text theme={null}

589 > /resume auth-refactor590 /resume auth-refactor

590 ```591 ```

591 </Step>592 </Step>

592</Steps>593</Steps>


643 644 

644## Run parallel Claude Code sessions with Git worktrees645## Run parallel Claude Code sessions with Git worktrees

645 646 

646Suppose you need to work on multiple tasks simultaneously with complete code isolation between Claude Code instances.647When working on multiple tasks at once, you need each Claude session to have its own copy of the codebase so changes don't collide. Git worktrees solve this by creating separate working directories that each have their own files and branch, while sharing the same repository history and remote connections. This means you can have Claude working on a feature in one worktree while fixing a bug in another, without either session interfering with the other.

647 648 

648<Steps>649Use the `--worktree` (`-w`) flag to create an isolated worktree and start Claude in it. The value you pass becomes the worktree directory name and branch name:

649 <Step title="Understand Git worktrees">

650 Git worktrees allow you to check out multiple branches from the same

651 repository into separate directories. Each worktree has its own working

652 directory with isolated files, while sharing the same Git history. Learn

653 more in the [official Git worktree

654 documentation](https://git-scm.com/docs/git-worktree).

655 </Step>

656 650 

657 <Step title="Create a new worktree">651```bash theme={null}

658 ```bash theme={null}652# Start Claude in a worktree named "feature-auth"

659 # Create a new worktree with a new branch 653# Creates .claude/worktrees/feature-auth/ with a new branch

660 git worktree add ../project-feature-a -b feature-a654claude --worktree feature-auth

661 655 

662 # Or create a worktree with an existing branch656# Start another session in a separate worktree

663 git worktree add ../project-bugfix bugfix-123657claude --worktree bugfix-123

664 ```658```

665 659 

666 This creates a new directory with a separate working copy of your repository.660If you omit the name, Claude generates a random one automatically:

667 </Step>

668 661 

669 <Step title="Run Claude Code in each worktree">662```bash theme={null}

670 ```bash theme={null}663# Auto-generates a name like "bright-running-fox"

671 # Navigate to your worktree 664claude --worktree

672 cd ../project-feature-a665```

673 666 

674 # Run Claude Code in this isolated environment667Worktrees are created at `<repo>/.claude/worktrees/<name>` and branch from the default remote branch. The worktree branch is named `worktree-<name>`.

675 claude

676 ```

677 </Step>

678 668 

679 <Step title="Run Claude in another worktree">669You can also ask Claude to "work in a worktree" or "start a worktree" during a session, and it will create one automatically.

680 ```bash theme={null}670 

681 cd ../project-bugfix671### Subagent worktrees

682 claude672 

673Subagents can also use worktree isolation to work in parallel without conflicts. Ask Claude to "use worktrees for your agents" or configure it in a [custom subagent](/en/sub-agents#supported-frontmatter-fields) by adding `isolation: worktree` to the agent's frontmatter. Each subagent gets its own worktree that is automatically cleaned up when the subagent finishes without changes.

674 

675### Worktree cleanup

676 

677When you exit a worktree session, Claude handles cleanup based on whether you made changes:

678 

679* **No changes**: the worktree and its branch are removed automatically

680* **Changes or commits exist**: Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding all uncommitted changes and commits

681 

682To clean up worktrees outside of a Claude session, use [manual worktree management](#manage-worktrees-manually).

683 

684<Tip>

685 Add `.claude/worktrees/` to your `.gitignore` to prevent worktree contents from appearing as untracked files in your main repository.

686</Tip>

687 

688### Manage worktrees manually

689 

690For more control over worktree location and branch configuration, create worktrees with Git directly. This is useful when you need to check out a specific existing branch or place the worktree outside the repository.

691 

692```bash theme={null}

693# Create a worktree with a new branch

694git worktree add ../project-feature-a -b feature-a

695 

696# Create a worktree with an existing branch

697git worktree add ../project-bugfix bugfix-123

698 

699# Start Claude in the worktree

700cd ../project-feature-a && claude

701 

702# Clean up when done

703git worktree list

704git worktree remove ../project-feature-a

705```

706 

707Learn more in the [official Git worktree documentation](https://git-scm.com/docs/git-worktree).

708 

709<Tip>

710 Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include running dependency installation (`npm install`, `yarn`), setting up virtual environments, or following your project's standard setup process.

711</Tip>

712 

713### Non-git version control

714 

715Worktree isolation works with git by default. For other version control systems like SVN, Perforce, or Mercurial, configure [WorktreeCreate and WorktreeRemove hooks](/en/hooks#worktreecreate) to provide custom worktree creation and cleanup logic. When configured, these hooks replace the default git behavior when you use `--worktree`.

716 

717For automated coordination of parallel sessions with shared tasks and messaging, see [agent teams](/en/agent-teams).

718 

719***

720 

721## Get notified when Claude needs your attention

722 

723When you kick off a long-running task and switch to another window, you can set up desktop notifications so you know when Claude finishes or needs your input. This uses the `Notification` [hook event](/en/hooks-guide#get-notified-when-claude-needs-input), which fires whenever Claude is waiting for permission, idle and ready for a new prompt, or completing authentication.

724 

725<Steps>

726 <Step title="Add the hook to your settings">

727 Open `~/.claude/settings.json` and add a `Notification` hook that calls your platform's native notification command:

728 

729 <Tabs>

730 <Tab title="macOS">

731 ```json theme={null}

732 {

733 "hooks": {

734 "Notification": [

735 {

736 "matcher": "",

737 "hooks": [

738 {

739 "type": "command",

740 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

741 }

742 ]

743 }

744 ]

745 }

746 }

683 ```747 ```

748 </Tab>

749 

750 <Tab title="Linux">

751 ```json theme={null}

752 {

753 "hooks": {

754 "Notification": [

755 {

756 "matcher": "",

757 "hooks": [

758 {

759 "type": "command",

760 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

761 }

762 ]

763 }

764 ]

765 }

766 }

767 ```

768 </Tab>

769 

770 <Tab title="Windows">

771 ```json theme={null}

772 {

773 "hooks": {

774 "Notification": [

775 {

776 "matcher": "",

777 "hooks": [

778 {

779 "type": "command",

780 "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""

781 }

782 ]

783 }

784 ]

785 }

786 }

787 ```

788 </Tab>

789 </Tabs>

790 

791 If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than overwriting. You can also ask Claude to write the hook for you by describing what you want in the CLI.

684 </Step>792 </Step>

685 793 

686 <Step title="Manage your worktrees">794 <Step title="Optionally narrow the matcher">

687 ```bash theme={null}795 By default the hook fires on all notification types. To fire only for specific events, set the `matcher` field to one of these values:

688 # List all worktrees

689 git worktree list

690 796 

691 # Remove a worktree when done797 | Matcher | Fires when |

692 git worktree remove ../project-feature-a798 | :------------------- | :---------------------------------------------- |

693 ```799 | `permission_prompt` | Claude needs you to approve a tool use |

800 | `idle_prompt` | Claude is done and waiting for your next prompt |

801 | `auth_success` | Authentication completes |

802 | `elicitation_dialog` | Claude is asking you a question |

694 </Step>803 </Step>

695</Steps>

696 804 

697<Tip>805 <Step title="Verify the hook">

698 Tips:806 Type `/hooks` and select `Notification` to confirm the hook appears. Selecting it shows the command that will run. To test it end-to-end, ask Claude to run a command that requires permission and switch away from the terminal, or ask Claude to trigger a notification directly.

807 </Step>

808</Steps>

699 809 

700 * Each worktree has its own independent file state, making it perfect for parallel Claude Code sessions810For the complete event schema and notification types, see the [Notification reference](/en/hooks#notification).

701 * Changes made in one worktree won't affect others, preventing Claude instances from interfering with each other

702 * All worktrees share the same Git history and remote connections

703 * For long-running tasks, you can have Claude working in one worktree while you continue development in another

704 * Use descriptive directory names to easily identify which task each worktree is for

705 * Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include:

706 * JavaScript projects: Running dependency installation (`npm install`, `yarn`)

707 * Python projects: Setting up virtual environments or installing with package managers

708 * Other languages: Following your project's standard setup process

709</Tip>

710 811 

711***812***

712 813 


801 902 

802### Example questions903### Example questions

803 904 

804```905```text theme={null}

805> can Claude Code create pull requests?906can Claude Code create pull requests?

806```907```

807 908 

808```909```text theme={null}

809> how does Claude Code handle permissions?910how does Claude Code handle permissions?

810```911```

811 912 

812```913```text theme={null}

813> what skills are available?914what skills are available?

814```915```

815 916 

816```917```text theme={null}

817> how do I use MCP with Claude Code?918how do I use MCP with Claude Code?

818```919```

819 920 

820```921```text theme={null}

821> how do I configure Claude Code for Amazon Bedrock?922how do I configure Claude Code for Amazon Bedrock?

822```923```

823 924 

824```925```text theme={null}

825> what are the limitations of Claude Code?926what are the limitations of Claude Code?

826```927```

827 928 

828<Note>929<Note>


858 Clone our development container reference implementation959 Clone our development container reference implementation

859 </Card>960 </Card>

860</CardGroup>961</CardGroup>

861 

862 

863 

864> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

costs.md +25 −9

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Manage costs effectively5# Manage costs effectively

2 6 

3> Track token usage, set team spend limits, and reduce Claude Code costs with context management, model selection, extended thinking settings, and preprocessing hooks.7> Track token usage, set team spend limits, and reduce Claude Code costs with context management, model selection, extended thinking settings, and preprocessing hooks.

4 8 

5Claude Code consumes tokens for each interaction. Costs vary based on codebase size, query complexity, and conversation length. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users.9Claude Code consumes tokens for each interaction. Costs vary based on codebase size, query complexity, and conversation length. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users.

6 10 

7For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.5 though there is large variance depending on how many instances users are running and whether they're using it in automation.11For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.6 though there is large variance depending on how many instances users are running and whether they're using it in automation.

8 12 

9This page covers how to [track your costs](#track-your-costs), [manage costs for teams](#managing-costs-for-teams), and [reduce token usage](#reduce-token-usage).13This page covers how to [track your costs](#track-your-costs), [manage costs for teams](#managing-costs-for-teams), and [reduce token usage](#reduce-token-usage).

10 14 


18 22 

19The `/cost` command provides detailed token usage statistics for your current session:23The `/cost` command provides detailed token usage statistics for your current session:

20 24 

21```25```text theme={null}

22Total cost: $0.5526Total cost: $0.55

23Total duration (API): 6m 19.7s27Total duration (API): 6m 19.7s

24Total duration (wall): 6h 33m 10.2s28Total duration (wall): 6h 33m 10.2s


33 When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace; it is exclusively for Claude Code authentication and usage.37 When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace; it is exclusively for Claude Code authentication and usage.

34</Note>38</Note>

35 39 

36On Bedrock, Vertex, and Foundry, Claude Code does not send metrics from your cloud. To get cost metrics, several large enterprises reported using [LiteLLM](/en/llm-gateway#litellm-configuration), which is an open-source tool that helps companies [track spend by key](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend). This project is unaffiliated with Anthropic and we have not audited its security.40On Bedrock, Vertex, and Foundry, Claude Code does not send metrics from your cloud. To get cost metrics, several large enterprises reported using [LiteLLM](/en/llm-gateway#litellm-configuration), which is an open-source tool that helps companies [track spend by key](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend). This project is unaffiliated with Anthropic and has not been audited for security.

37 41 

38### Rate limit recommendations42### Rate limit recommendations

39 43 


50 54 

51For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).55For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).

52 56 

53The TPM per user decreases as team size grows because we expect fewer users to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service.57The TPM per user decreases as team size grows because fewer users tend to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service.

54 58 

55<Note>59<Note>

56 If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user.60 If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user.

57</Note>61</Note>

58 62 

63### Agent team token costs

64 

65[Agent teams](/en/agent-teams) spawn multiple Claude Code instances, each with its own context window. Token usage scales with the number of active teammates and how long each one runs.

66 

67To keep agent team costs manageable:

68 

69* Use Sonnet for teammates. It balances capability and cost for coordination tasks.

70* Keep teams small. Each teammate runs its own context window, so token usage is roughly proportional to team size.

71* Keep spawn prompts focused. Teammates load CLAUDE.md, MCP servers, and skills automatically, but everything in the spawn prompt adds to their context from the start.

72* Clean up teams when work is done. Active teammates continue consuming tokens even if idle.

73* Agent teams are disabled by default. Set `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](/en/settings) or environment to enable them. See [enable agent teams](/en/agent-teams#enable-agent-teams).

74 

59## Reduce token usage75## Reduce token usage

60 76 

61Token costs scale with context size: the more context Claude processes, the more tokens you use. Claude Code automatically optimizes costs through prompt caching (which reduces costs for repeated content like system prompts) and auto-compaction (which summarizes conversation history when approaching context limits).77Token costs scale with context size: the more context Claude processes, the more tokens you use. Claude Code automatically optimizes costs through prompt caching (which reduces costs for repeated content like system prompts) and auto-compaction (which summarizes conversation history when approaching context limits).


149 165 

150### Adjust extended thinking166### Adjust extended thinking

151 167 

152Extended thinking is enabled by default with a budget of 31,999 tokens because it significantly improves performance on complex planning and reasoning tasks. However, thinking tokens are billed as output tokens, so for simpler tasks where deep reasoning isn't needed, you can reduce costs by disabling it in `/config` or lowering the budget (for example, `MAX_THINKING_TOKENS=8000`).168Extended thinking is enabled by default with a budget of 31,999 tokens because it significantly improves performance on complex planning and reasoning tasks. However, thinking tokens are billed as output tokens, so for simpler tasks where deep reasoning isn't needed, you can reduce costs by lowering the [effort level](/en/model-config#adjust-effort-level) with `/effort` or in `/model`, disabling thinking in `/config`, or lowering the budget (for example, `MAX_THINKING_TOKENS=8000`).

153 169 

154### Delegate verbose operations to subagents170### Delegate verbose operations to subagents

155 171 

156Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](/en/sub-agents#isolate-high-volume-operations) so the verbose output stays in the subagent's context while only a summary returns to your main conversation.172Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](/en/sub-agents#isolate-high-volume-operations) so the verbose output stays in the subagent's context while only a summary returns to your main conversation.

157 173 

174### Manage agent team costs

175 

176Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode, because each teammate maintains its own context window and runs as a separate Claude instance. Keep team tasks small and self-contained to limit per-teammate token usage. See [agent teams](/en/agent-teams) for details.

177 

158### Write specific prompts178### Write specific prompts

159 179 

160Vague requests like "improve this codebase" trigger broad scanning. Specific requests like "add input validation to the login function in auth.ts" let Claude work efficiently with minimal file reads.180Vague requests like "improve this codebase" trigger broad scanning. Specific requests like "add input validation to the login function in auth.ts" let Claude work efficiently with minimal file reads.


180## Understanding changes in Claude Code behavior200## Understanding changes in Claude Code behavior

181 201 

182Claude Code regularly receives updates that may change how features work, including cost reporting. Run `claude --version` to check your current version. For specific billing questions, contact Anthropic support through your [Console account](https://platform.claude.com/login). For team deployments, start with a small pilot group to establish usage patterns before wider rollout.202Claude Code regularly receives updates that may change how features work, including cost reporting. Run `claude --version` to check your current version. For specific billing questions, contact Anthropic support through your [Console account](https://platform.claude.com/login). For team deployments, start with a small pilot group to establish usage patterns before wider rollout.

183 

184 

185 

186> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

data-usage.md +18 −13

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Data usage5# Data usage

2 6 

3> Learn about Anthropic's data usage policies for Claude7> Learn about Anthropic's data usage policies for Claude


23 27 

24When you see the "How is Claude doing this session?" prompt in Claude Code, responding to this survey (including selecting "Dismiss"), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/bug` reports, this session quality survey is a simple product satisfaction metric. Your responses to this survey do not impact your data training preferences and cannot be used to train our AI models.28When you see the "How is Claude doing this session?" prompt in Claude Code, responding to this survey (including selecting "Dismiss"), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/bug` reports, this session quality survey is a simple product satisfaction metric. Your responses to this survey do not impact your data training preferences and cannot be used to train our AI models.

25 29 

30To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. To control frequency instead of disabling, set [`feedbackSurveyRate`](/en/settings#available-settings) in your settings file to a probability between `0` and `1`.

31 

26### Data retention32### Data retention

27 33 

28Anthropic retains Claude Code data based on your account type and preferences.34Anthropic retains Claude Code data based on your account type and preferences.


36**Commercial users (Team, Enterprise, and API)**:42**Commercial users (Team, Enterprise, and API)**:

37 43 

38* Standard: 30-day retention period44* Standard: 30-day retention period

39* Zero data retention: Available with appropriately configured API keys - Claude Code will not retain chat transcripts on servers45* [Zero data retention](/en/zero-data-retention): available for Claude Code on Claude for Enterprise. ZDR is enabled on a per-organization basis; each new organization must have ZDR enabled separately by your account team

40* Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable)46* Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable)

41 47 

48You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session's event data. For instructions on how to delete sessions, see [Managing sessions](/en/claude-code-on-the-web#managing-sessions).

49 

42Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).50Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).

43 51 

44For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).52For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).

45 53 

46## Data access54## Data access

47 55 

48For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.56For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). [Remote Control](/en/remote-control) sessions follow the local data flow since all execution happens on your machine. Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.

49 57 

50## Local Claude Code: Data flow and dependencies58## Local Claude Code: Data flow and dependencies

51 59 

52The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.60The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.

53 61 

54<img src="https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=9e77f476347e7c9983f6e211d27cf6a9" alt="Diagram showing Claude Code's external connections: install/update connects to NPM, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting" data-og-width="720" width="720" data-og-height="520" height="520" data-path="images/claude-code-data-flow.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=280&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=94c033b9b6db3d10b9e2d7c6d681d9dc 280w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=560&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=430aaaf77c28c501d5753ffa456ee227 560w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=840&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=63c3c3f160b522220a8291fe2f93f970 840w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=1100&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=a7f6e838482f4a1a0a0b4683439369ea 1100w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=1650&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=5fbf749c2f94babb3ef72edfb7aba1e9 1650w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=2500&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=7a1babbdccc4986957698d9c5c30c4a8 2500w" />62<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/claude-code-data-flow.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=b3f71c69d743bff63343207dfb7ad6ce" alt="Diagram showing Claude Code's external connections: install/update connects to NPM, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting" width="720" height="520" data-path="images/claude-code-data-flow.svg" />

55 63 

56Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.64Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.

57 65 


78 86 

79## Default behaviors by API provider87## Default behaviors by API provider

80 88 

81By default, we disable all non-essential traffic (including error reporting, telemetry, and bug reporting functionality) when using Bedrock or Vertex. You can also opt out of all of these at once by setting the `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` environment variable. Here are the full default behaviors:89By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, or Foundry. Session quality surveys are the exception and appear regardless of provider. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Here are the full default behaviors:

82 90 

83| Service | Claude API | Vertex API | Bedrock API |91| Service | Claude API | Vertex API | Bedrock API | Foundry API |

84| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |92| ------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- |

85| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |93| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

86| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |94| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

87| **Claude API (`/bug` reports)** | Default on.<br />`DISABLE_BUG_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |95| **Claude API (`/bug` reports)** | Default on.<br />`DISABLE_BUG_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

96| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. |

88 97 

89All environment variables can be checked into `settings.json` ([read more](/en/settings)).98All environment variables can be checked into `settings.json` ([read more](/en/settings)).

90 

91 

92 

93> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

desktop.md +559 −72

Details

1# Claude Code on desktop1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Run Claude Code tasks locally or on secure cloud infrastructure with the Claude desktop app5# Use Claude Code Desktop

4 6 

5<img src="https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=c4e9dc9737b437d36ab253b75a1cc595" alt="Claude Code on desktop interface" data-og-width="4132" width="4132" data-og-height="2620" height="2620" data-path="images/desktop-interface.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?w=280&fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=b1a8421a544c3e8c78679fa1a7b56190 280w, https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?w=560&fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=79cf4ea0923098cc429198678ea50903 560w, https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?w=840&fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=14bcbcd569d179770fe656686ffbf6bf 840w, https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?w=1100&fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=b873274db1e9ff8585ba545032aa24a5 1100w, https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?w=1650&fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=25553dced783c3a8c2a1134a53295f7e 1650w, https://mintcdn.com/claude-code/zEGbGSbinVtT3BLw/images/desktop-interface.png?w=2500&fit=max&auto=format&n=zEGbGSbinVtT3BLw&q=85&s=9ad49e6468c2f87b1895093deeea7bb2 2500w" />7> Get more out of Claude Code Desktop: parallel sessions with Git isolation, visual diff review, app previews, PR monitoring, permission modes, connectors, and enterprise configuration.

6 8 

7## Claude Code on desktop (Preview)9The Code tab within the Claude Desktop app lets you use Claude Code through a graphical interface instead of the terminal.

8 10 

9The Claude desktop app provides a native interface for running multiple Claude Code sessions on your local machine and seamless integration with Claude Code on the web.11Desktop adds these capabilities on top of the standard Claude Code experience:

10 12 

11## Installation13* [Visual diff review](#review-changes-with-diff-view) with inline comments

14* [Live app preview](#preview-your-app) with dev servers

15* [GitHub PR monitoring](#monitor-pull-request-status) with auto-fix and auto-merge

16* [Parallel sessions](#work-in-parallel-with-sessions) with automatic Git worktree isolation

17* [Scheduled tasks](#schedule-recurring-tasks) that run Claude on a recurring schedule

18* [Connectors](#connect-external-tools) for GitHub, Slack, Linear, and more

19* Local, [SSH](#ssh-sessions), and [cloud](#run-long-running-tasks-remotely) environments

12 20 

13Download the Claude desktop app for your platform:21<Tip>

22 New to Desktop? Start with [Get started](/en/desktop-quickstart) to install the app and make your first edit.

23</Tip>

14 24 

15<CardGroup cols={2}>25This page covers [working with code](#work-with-code), [managing sessions](#manage-sessions), [extending Claude Code](#extend-claude-code), [scheduled tasks](#schedule-recurring-tasks), and [configuration](#environment-configuration). It also includes a [CLI comparison](#coming-from-the-cli) and [troubleshooting](#troubleshooting).

16 <Card title="macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

17 Universal build for Intel and Apple Silicon

18 </Card>

19 26 

20 <Card title="Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs">27## Start a session

21 For x64 processors

22 </Card>

23</CardGroup>

24 28 

25For Windows ARM64, [download here](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs).29Before you send your first message, configure four things in the prompt area:

26 30 

27<Note>31* **Environment**: choose where Claude runs. Select **Local** for your machine, **Remote** for Anthropic-hosted cloud sessions, or an [**SSH connection**](#ssh-sessions) for a remote machine you manage. See [environment configuration](#environment-configuration).

28 Local sessions are not available on Windows ARM64.32* **Project folder**: select the folder or repository Claude works in. For remote sessions, you can add [multiple repositories](#run-long-running-tasks-remotely).

29</Note>33* **Model**: pick a [model](/en/model-config#available-models) from the dropdown next to the send button. The model is locked once the session starts.

34* **Permission mode**: choose how much autonomy Claude has from the [mode selector](#choose-a-permission-mode). You can change this during the session.

35 

36Type your task and press **Enter** to start. Each session tracks its own context and changes independently.

37 

38## Work with code

39 

40Give Claude the right context, control how much it does on its own, and review what it changed.

41 

42### Use the prompt box

43 

44Type what you want Claude to do and press **Enter** to send. Claude reads your project files, makes changes, and runs commands based on your [permission mode](#choose-a-permission-mode). You can interrupt Claude at any point: click the stop button or type your correction and press **Enter**. Claude stops what it's doing and adjusts based on your input.

45 

46The **+** button next to the prompt box gives you access to file attachments, [skills](#use-skills), [connectors](#connect-external-tools), and [plugins](#install-plugins).

47 

48### Add files and context to prompts

49 

50The prompt box supports two ways to bring in external context:

51 

52* **@mention files**: type `@` followed by a filename to add a file to the conversation context. Claude can then read and reference that file.

53* **Attach files**: attach images, PDFs, and other files to your prompt using the attachment button, or drag and drop files directly into the prompt. This is useful for sharing screenshots of bugs, design mockups, or reference documents.

54 

55### Choose a permission mode

56 

57Permission modes control how much autonomy Claude has during a session: whether it asks before editing files, running commands, or both. You can switch modes at any time using the mode selector next to the send button. Start with Ask permissions to see exactly what Claude does, then move to Auto accept edits or Plan mode as you get comfortable.

58 

59| Mode | Settings key | Behavior |

60| ---------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

61| **Ask permissions** | `default` | Claude asks before editing files or running commands. You see a diff and can accept or reject each change. Recommended for new users. |

62| **Auto accept edits** | `acceptEdits` | Claude auto-accepts file edits but still asks before running terminal commands. Use this when you trust file changes and want faster iteration. |

63| **Plan mode** | `plan` | Claude analyzes your code and creates a plan without modifying files or running commands. Good for complex tasks where you want to review the approach first. |

64| **Bypass permissions** | `bypassPermissions` | Claude runs without any permission prompts, equivalent to `--dangerously-skip-permissions` in the CLI. Enable in your Settings → Claude Code under "Allow bypass permissions mode". Only use this in sandboxed containers or VMs. Enterprise admins can disable this option. |

65 

66The `dontAsk` permission mode is available only in the [CLI](/en/permissions#permission-modes).

67 

68<Tip title="Best practice">

69 Start complex tasks in Plan mode so Claude maps out an approach before making changes. Once you approve the plan, switch to Auto accept edits or Ask permissions to execute it. See [explore first, then plan, then code](/en/best-practices#explore-first-then-plan-then-code) for more on this workflow.

70</Tip>

71 

72Remote sessions support Auto accept edits and Plan mode. Ask permissions is not available because remote sessions auto-accept file edits by default, and Bypass permissions is not available because the remote environment is already sandboxed.

73 

74Enterprise admins can restrict which permission modes are available. See [enterprise configuration](#enterprise-configuration) for details.

75 

76### Preview your app

77 

78Claude can start a dev server and open an embedded browser to verify its changes. This works for frontend web apps as well as backend servers: Claude can test API endpoints, view server logs, and iterate on issues it finds. In most cases, Claude starts the server automatically after editing project files. You can also ask Claude to preview at any time. By default, Claude [auto-verifies](#auto-verify-changes) changes after every edit.

30 79 

31## Features80From the preview panel, you can:

32 81 

33Claude Code on desktop provides:82* Interact with your running app directly in the embedded browser

83* Watch Claude verify its own changes automatically: it takes screenshots, inspects the DOM, clicks elements, fills forms, and fixes issues it finds

84* Start or stop servers from the **Preview** dropdown in the session toolbar

85* Persist cookies and local storage across server restarts by selecting **Persist sessions** in the dropdown, so you don't have to re-login during development

86* Edit the server configuration or stop all servers at once

34 87 

35* **Diff view**: Review Claude's changes file by file before creating a pull request, and comment on specific lines to iterate further88Claude creates the initial server configuration based on your project. If your app uses a custom dev command, edit `.claude/launch.json` to match your setup. See [Configure preview servers](#configure-preview-servers) for the full reference.

36* **Parallel local sessions with `git` worktrees**: Run multiple Claude Code sessions simultaneously in the same repository, each with its own isolated `git` worktree

37* **Include files listed in your `.gitignore` in your worktrees**: Automatically copy files in your `.gitignore`, like `.env`, to new worktrees using `.worktreeinclude`

38* **Launch Claude Code on the web**: Kick off secure cloud sessions directly from the desktop app

39 89 

40## Review changes with diff view90To clear saved session data, toggle **Persist preview sessions** off in Settings → Claude Code. To disable preview entirely, toggle off **Preview** in Settings → Claude Code.

91 

92### Review changes with diff view

41 93 

42After Claude makes changes to your code, the diff view lets you review modifications file by file before creating a pull request.94After Claude makes changes to your code, the diff view lets you review modifications file by file before creating a pull request.

43 95 

44When Claude makes changes to files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Click this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.96When Claude changes files, a diff stats indicator appears showing the number of lines added and removed, such as `+12 -1`. Click this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.

97 

98To comment on specific lines, click any line in the diff to open a comment box. Type your feedback and press **Enter** to add the comment. After adding comments to multiple lines, submit all comments at once:

99 

100* **macOS**: press **Cmd+Enter**

101* **Windows**: press **Ctrl+Enter**

102 

103Claude reads your comments and makes the requested changes, which appear as a new diff you can review.

104 

105### Review your code

106 

107In the diff view, click **Review code** in the top-right toolbar to ask Claude to evaluate the changes before you commit. Claude examines the current diffs and leaves comments directly in the diff view. You can respond to any comment or ask Claude to revise.

45 108 

46### Comment on specific lines109The review focuses on high-signal issues: compile errors, definite logic errors, security vulnerabilities, and obvious bugs. It does not flag style, formatting, pre-existing issues, or anything a linter would catch.

47 110 

48Click on any line in the diff to open a comment box. Type your feedback and press **Enter** to send. In the full diff view, press **Enter** to accept each comment, then **Cmd+Enter** to send them all. Claude reads your comments and makes the requested changes, which appear as a new diff you can review.111### Monitor pull request status

49 112 

50## Using Git worktrees113After you open a pull request, a CI status bar appears in the session. Claude Code uses the GitHub CLI to poll check results and surface failures.

51 114 

52Claude Code on desktop enables running multiple Claude Code sessions in the same repository using Git worktrees. Each session gets its own isolated worktree, allowing Claude to work on different tasks without conflicts. The default location for worktrees is `~/.claude-worktrees` but this can be configured in your settings on the Claude desktop app.115* **Auto-fix**: when enabled, Claude automatically attempts to fix failing CI checks by reading the failure output and iterating.

116* **Auto-merge**: when enabled, Claude merges the PR once all checks pass. The merge method is squash. Auto-merge must be [enabled in your GitHub repository settings](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-auto-merge-for-pull-requests-in-your-repository) for this to work.

117 

118Use the **Auto-fix** and **Auto-merge** toggles in the CI status bar to enable either option. Claude Code also sends a desktop notification when CI finishes.

53 119 

54<Note>120<Note>

55 If you start a local session in a folder that does not have Git initialized, the desktop app will not create a new worktree.121 PR monitoring requires the [GitHub CLI (`gh`)](https://cli.github.com/) to be installed and authenticated on your machine. If `gh` is not installed, Desktop prompts you to install it the first time you try to create a PR.

56</Note>122</Note>

57 123 

58### Copying files ignored with `.gitignore`124## Manage sessions

125 

126Each session is an independent conversation with its own context and changes. You can run multiple sessions in parallel or send work to the cloud.

127 

128### Work in parallel with sessions

129 

130Click **+ New session** in the sidebar to work on multiple tasks in parallel. For Git repositories, each session gets its own isolated copy of your project using [Git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees), so changes in one session don't affect other sessions until you commit them.

131 

132Worktrees are stored in `<project-root>/.claude/worktrees/` by default. You can change this to a custom directory in Settings → Claude Code under "Worktree location". You can also set a branch prefix that gets prepended to every worktree branch name, which is useful for keeping Claude-created branches organized. To remove a worktree when you're done, hover over the session in the sidebar and click the archive icon.

133 

134<Note>

135 Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check. On Windows, Git is required for the Code tab to work: [download Git for Windows](https://git-scm.com/downloads/win), install it, and restart the app. If you run into Git errors, try a Cowork session to help troubleshoot your setup.

136</Note>

137 

138Use the filter icon at the top of the sidebar to filter sessions by status (Active, Archived) and environment (Local, Cloud). To rename a session or check context usage, click the session title in the toolbar at the top of the active session. When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](/en/how-claude-code-works#the-context-window) for details on how compaction works.

139 

140### Run long-running tasks remotely

141 

142For large refactors, test suites, migrations, or other long-running tasks, select **Remote** instead of **Local** when starting a session. Remote sessions run on Anthropic's cloud infrastructure and continue even if you close the app or shut down your computer. Check back anytime to see progress or steer Claude in a different direction. You can also monitor remote sessions from [claude.ai/code](https://claude.ai/code) or the Claude iOS app.

143 

144Remote sessions also support multiple repositories. After selecting a cloud environment, click the **+** button next to the repo pill to add additional repositories to the session. Each repo gets its own branch selector. This is useful for tasks that span multiple codebases, such as updating a shared library and its consumers.

145 

146See [Claude Code on the web](/en/claude-code-on-the-web) for more on how remote sessions work.

147 

148### Continue in another surface

149 

150The **Continue in** menu, accessible from the VS Code icon in the bottom right of the session toolbar, lets you move your session to another surface:

151 

152* **Claude Code on the Web**: sends your local session to continue running remotely. Desktop pushes your branch, generates a summary of the conversation, and creates a new remote session with the full context. You can then choose to archive the local session or keep it. This requires a clean working tree, and is not available for SSH sessions.

153* **Your IDE**: opens your project in a supported IDE at the current working directory.

154 

155## Extend Claude Code

59 156 

60When Claude Code creates a worktree, files ignored via `.gitignore` aren't automatically available. Including a `.worktreeinclude` file solves this by specifying which ignored files should be copied to new worktrees.157Connect external services, add reusable workflows, customize Claude's behavior, and configure preview servers.

61 158 

62Create a `.worktreeinclude` file in your repository root:159### Connect external tools

63 160 

161For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Connectors** to add integrations like Google Calendar, Slack, GitHub, Linear, Notion, and more. You can add connectors before or during a session. Connectors are not available for remote sessions.

162 

163To manage or disconnect connectors, go to Settings → Connectors in the desktop app, or select **Manage connectors** from the Connectors menu in the prompt box.

164 

165Once connected, Claude can read your calendar, send messages, create issues, and interact with your tools directly. You can ask Claude what connectors are configured in your session.

166 

167Connectors are [MCP servers](/en/mcp) with a graphical setup flow. Use them for quick integration with supported services. For integrations not listed in Connectors, add MCP servers manually via [settings files](/en/mcp#installing-mcp-servers). You can also [create custom connectors](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp).

168 

169### Use skills

170 

171[Skills](/en/skills) extend what Claude can do. Claude loads them automatically when relevant, or you can invoke one directly: type `/` in the prompt box or click the **+** button and select **Slash commands** to browse what's available. This includes [built-in commands](/en/commands), your [custom skills](/en/skills#create-custom-skills), project skills from your codebase, and skills from any [installed plugins](/en/plugins). Select one and it appears highlighted in the input field. Type your task after it and send as usual.

172 

173### Install plugins

174 

175[Plugins](/en/plugins) are reusable packages that add skills, agents, hooks, MCP servers, and LSP configurations to Claude Code. You can install plugins from the desktop app without using the terminal.

176 

177For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their commands. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](/en/plugin-marketplaces) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.

178 

179Plugins can be scoped to your user account, a specific project, or local-only. Plugins are not available for remote sessions. For the full plugin reference including creating your own plugins, see [plugins](/en/plugins).

180 

181### Configure preview servers

182 

183Claude automatically detects your dev server setup and stores the configuration in `.claude/launch.json` at the root of the folder you selected when starting the session. Preview uses this folder as its working directory, so if you selected a parent folder, subfolders with their own dev servers won't be detected automatically. To work with a subfolder's server, either start a session in that folder directly or add a configuration manually.

184 

185To customize how your server starts, for example to use `yarn dev` instead of `npm run dev` or to change the port, edit the file manually or click **Edit configuration** in the Preview dropdown to open it in your code editor. The file supports JSON with comments.

186 

187```json theme={null}

188{

189 "version": "0.0.1",

190 "configurations": [

191 {

192 "name": "my-app",

193 "runtimeExecutable": "npm",

194 "runtimeArgs": ["run", "dev"],

195 "port": 3000

196 }

197 ]

198}

64```199```

65.env200 

66.env.local201You can define multiple configurations to run different servers from the same project, such as a frontend and an API. See the [examples](#examples) below.

67.env.*202 

68**/.claude/settings.local.json203#### Auto-verify changes

204 

205When `autoVerify` is enabled, Claude automatically verifies code changes after editing files. It takes screenshots, checks for errors, and confirms changes work before completing its response.

206 

207Auto-verify is on by default. Disable it per-project by adding `"autoVerify": false` to `.claude/launch.json`, or toggle it from the **Preview** dropdown menu.

208 

209```json theme={null}

210{

211 "version": "0.0.1",

212 "autoVerify": false,

213 "configurations": [...]

214}

69```215```

70 216 

71The file uses `.gitignore`-style patterns. When a worktree is created, files matching these patterns that are also in your `.gitignore` will be copied from your main repository to the worktree.217When disabled, preview tools are still available and you can ask Claude to verify at any time. Auto-verify makes it automatic after every edit.

72 218 

73<Tip>219#### Configuration fields

74 Only files that are both matched by `.worktreeinclude` AND listed in `.gitignore` are copied. This prevents accidentally duplicating tracked files.220 

75</Tip>221Each entry in the `configurations` array accepts the following fields:

222 

223| Field | Type | Description |

224| ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

225| `name` | string | A unique identifier for this server |

226| `runtimeExecutable` | string | The command to run, such as `npm`, `yarn`, or `node` |

227| `runtimeArgs` | string\[] | Arguments passed to `runtimeExecutable`, such as `["run", "dev"]` |

228| `port` | number | The port your server listens on. Defaults to 3000 |

229| `cwd` | string | Working directory relative to your project root. Defaults to the project root. Use `${workspaceFolder}` to reference the project root explicitly |

230| `env` | object | Additional environment variables as key-value pairs, such as `{ "NODE_ENV": "development" }`. Don't put secrets here since this file is committed to your repo. Secrets set in your shell profile are inherited automatically. |

231| `autoPort` | boolean | How to handle port conflicts. See below |

232| `program` | string | A script to run with `node`. See [when to use `program` vs `runtimeExecutable`](#when-to-use-program-vs-runtimeexecutable) |

233| `args` | string\[] | Arguments passed to `program`. Only used when `program` is set |

234 

235##### When to use `program` vs `runtimeExecutable`

76 236 

77### Launch Claude Code on the web237Use `runtimeExecutable` with `runtimeArgs` to start a dev server through a package manager. For example, `"runtimeExecutable": "npm"` with `"runtimeArgs": ["run", "dev"]` runs `npm run dev`.

78 238 

79From the desktop app, you can kick off Claude Code sessions that run on Anthropic's secure cloud infrastructure.239Use `program` when you have a standalone script you want to run with `node` directly. For example, `"program": "server.js"` runs `node server.js`. Pass additional flags with `args`.

80 240 

81To start a web session from desktop, select a remote environment when creating a new session.241#### Port conflicts

82 242 

83For more details, see [Claude Code on the web](/en/claude-code-on-the-web).243The `autoPort` field controls what happens when your preferred port is already in use:

84 244 

85## Bundled Claude Code version245* **`true`**: Claude finds and uses a free port automatically. Suitable for most dev servers.

246* **`false`**: Claude fails with an error. Use this when your server must use a specific port, such as for OAuth callbacks or CORS allowlists.

247* **Not set (default)**: Claude asks whether the server needs that exact port, then saves your answer.

86 248 

87Claude Code on desktop includes a bundled, stable version of Claude Code to ensure a consistent experience for all desktop users. The bundled version is required and downloaded on first launch even if a version of Claude Code exists on the computer. Desktop automatically manages version updates and cleans up old versions.249When Claude picks a different port, it passes the assigned port to your server via the `PORT` environment variable.

250 

251#### Examples

252 

253These configurations show common setups for different project types:

254 

255<Tabs>

256 <Tab title="Next.js">

257 This configuration runs a Next.js app using Yarn on port 3000:

258 

259 ```json theme={null}

260 {

261 "version": "0.0.1",

262 "configurations": [

263 {

264 "name": "web",

265 "runtimeExecutable": "yarn",

266 "runtimeArgs": ["dev"],

267 "port": 3000

268 }

269 ]

270 }

271 ```

272 </Tab>

273 

274 <Tab title="Multiple servers">

275 For a monorepo with a frontend and an API server, define multiple configurations. The frontend uses `autoPort: true` so it picks a free port if 3000 is taken, while the API server requires port 8080 exactly:

276 

277 ```json theme={null}

278 {

279 "version": "0.0.1",

280 "configurations": [

281 {

282 "name": "frontend",

283 "runtimeExecutable": "npm",

284 "runtimeArgs": ["run", "dev"],

285 "cwd": "apps/web",

286 "port": 3000,

287 "autoPort": true

288 },

289 {

290 "name": "api",

291 "runtimeExecutable": "npm",

292 "runtimeArgs": ["run", "start"],

293 "cwd": "server",

294 "port": 8080,

295 "env": { "NODE_ENV": "development" },

296 "autoPort": false

297 }

298 ]

299 }

300 ```

301 </Tab>

302 

303 <Tab title="Node.js script">

304 To run a Node.js script directly instead of using a package manager command, use the `program` field:

305 

306 ```json theme={null}

307 {

308 "version": "0.0.1",

309 "configurations": [

310 {

311 "name": "server",

312 "program": "server.js",

313 "args": ["--verbose"],

314 "port": 4000

315 }

316 ]

317 }

318 ```

319 </Tab>

320</Tabs>

321 

322## Schedule recurring tasks

323 

324Scheduled tasks start a new local session automatically at a time and frequency you choose. Use them for recurring work like daily code reviews, dependency update checks, or morning briefings that pull from your calendar and inbox.

325 

326Tasks run on your machine, so the desktop app must be open and your computer awake for them to fire. See [How scheduled tasks run](#how-scheduled-tasks-run) for details on missed runs and catch-up behavior.

88 327 

89<Note>328<Note>

90 The bundled Claude Code version in Desktop may differ from the latest CLI version. Desktop prioritizes stability while the CLI may have newer features.329 By default, scheduled tasks run against whatever state your working directory is in, including uncommitted changes. Enable the worktree toggle in the prompt input to give each run its own isolated Git worktree, the same way [parallel sessions](#work-in-parallel-with-sessions) work.

91</Note>330</Note>

92 331 

332To create a scheduled task, click **Schedule** in the sidebar, then **+ New task**. Configure these fields:

333 

334| Field | Description |

335| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

336| Name | Identifier for the task. Converted to lowercase kebab-case and used as the folder name on disk. Must be unique across your tasks. |

337| Description | Short summary shown in the task list. |

338| Prompt | The instructions sent to Claude when the task runs. Write this the same way you'd write any message in the prompt box. The prompt input also includes controls for model, permission mode, working folder, and worktree. |

339| Frequency | How often the task runs. See [frequency options](#frequency-options) below. |

340 

341You can also create a task by describing what you want in any session. For example, "set up a daily code review that runs every morning at 9am."

342 

343### Frequency options

344 

345* **Manual**: no schedule, only runs when you click **Run now**. Useful for saving a prompt you trigger on demand

346* **Hourly**: runs every hour. Each task gets a fixed offset of up to 10 minutes from the top of the hour to stagger API traffic

347* **Daily**: shows a time picker, defaults to 9:00 AM local time

348* **Weekdays**: same as Daily but skips Saturday and Sunday

349* **Weekly**: shows a time picker and a day picker

350 

351For intervals the picker doesn't offer (every 15 minutes, first of each month, etc.), ask Claude in any Desktop session to set the schedule. Use plain language; for example, "schedule a task to run all the tests every 6 hours."

352 

353### How scheduled tasks run

354 

355Scheduled tasks run locally on your machine. Desktop checks the schedule every minute while the app is open and starts a fresh session when a task is due, independent of any manual sessions you have open. Each task gets a fixed delay of up to 10 minutes after the scheduled time to stagger API traffic. The delay is deterministic: the same task always starts at the same offset.

356 

357When a task fires, you get a desktop notification and a new session appears under a **Scheduled** section in the sidebar. Open it to see what Claude did, review changes, or respond to permission prompts. The session works like any other: Claude can edit files, run commands, create commits, and open pull requests.

358 

359Tasks only run while the desktop app is running and your computer is awake. If your computer sleeps through a scheduled time, the run is skipped. To prevent idle-sleep, enable **Keep computer awake** in Settings under **Desktop app → General**. Closing the laptop lid still puts it to sleep.

360 

361### Missed runs

362 

363When the app starts or your computer wakes, Desktop checks whether each task missed any runs in the last seven days. If it did, Desktop starts exactly one catch-up run for the most recently missed time and discards anything older. A daily task that missed six days runs once on wake. Desktop shows a notification when a catch-up run starts.

364 

365Keep this in mind when writing prompts. A task scheduled for 9am might run at 11pm if your computer was asleep all day. If timing matters, add guardrails to the prompt itself, for example: "Only review today's commits. If it's after 5pm, skip the review and just post a summary of what was missed."

366 

367### Permissions for scheduled tasks

368 

369Each task has its own permission mode, which you set when creating or editing the task. Allow rules from `~/.claude/settings.json` also apply to scheduled task sessions. If a task runs in Ask mode and needs to run a tool it doesn't have permission for, the run stalls until you approve it. The session stays open in the sidebar so you can answer later.

370 

371To avoid stalls, click **Run now** after creating a task, watch for permission prompts, and select "always allow" for each one. Future runs of that task auto-approve the same tools without prompting. You can review and revoke these approvals from the task's detail page.

372 

373### Manage scheduled tasks

374 

375Click a task in the **Schedule** list to open its detail page. From here you can:

376 

377* **Run now**: start the task immediately without waiting for the next scheduled time

378* **Toggle repeats**: pause or resume scheduled runs without deleting the task

379* **Edit**: change the prompt, frequency, folder, or other settings

380* **Review history**: see every past run, including ones that were skipped because your computer was asleep

381* **Review allowed permissions**: see and revoke saved tool approvals for this task from the **Always allowed** panel

382* **Delete**: remove the task and archive all sessions it created

383 

384You can also manage tasks by asking Claude in any Desktop session. For example, "pause my dependency-audit task", "delete the standup-prep task", or "show me my scheduled tasks."

385 

386To edit a task's prompt on disk, open `~/.claude/scheduled-tasks/<task-name>/SKILL.md` (or under [`CLAUDE_CONFIG_DIR`](/en/env-vars) if set). The file uses YAML frontmatter for `name` and `description`, with the prompt as the body. Changes take effect on the next run. Schedule, folder, model, and enabled state are not in this file: change them through the Edit form or ask Claude.

387 

93## Environment configuration388## Environment configuration

94 389 

95For local environments, Claude Code on desktop automatically extracts your `$PATH` environment variable from your shell configuration. This allows local sessions to access development tools like `yarn`, `npm`, `node`, and other commands available in your terminal without additional setup.390The environment you pick when [starting a session](#start-a-session) determines where Claude executes and how you connect:

96 391 

97### Custom environment variables392* **Local**: runs on your machine with direct access to your files

393* **Remote**: runs on Anthropic's cloud infrastructure. Sessions continue even if you close the app.

394* **SSH**: runs on a remote machine you connect to over SSH, such as your own servers, cloud VMs, or dev containers

98 395 

99Select "Local" environment, then to the right, select the settings button. This will open a dialog where you can update local environment variables. This is useful for setting project-specific variables or API keys that your development workflows require. Environment variable values are masked in the UI for security reasons.396### Local sessions

100 397 

101<Note>398Local sessions inherit environment variables from your shell. If you need additional variables, set them in your shell profile, such as `~/.zshrc` or `~/.bashrc`, and restart the desktop app. See [environment variables](/en/env-vars) for the full list of supported variables.

102 Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:

103 399 

104 ```400[Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS=0` in your shell profile. On Opus, `MAX_THINKING_TOKENS` is ignored except for `0` because adaptive reasoning controls thinking depth instead.

105 API_KEY=your_api_key

106 DEBUG=true

107 401 

108 # Multiline values - wrap in quotes402### Remote sessions

109 CERT="-----BEGIN CERT-----403 

110 MIIE...404Remote sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](/en/costs) with no separate compute charges.

111 -----END CERT-----"405 

112 ```406You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a remote session and choose **Add environment**. See [cloud environments](/en/claude-code-on-the-web#cloud-environment) for details on configuring network access and environment variables.

113</Note>407 

408### SSH sessions

409 

410SSH sessions let you run Claude Code on a remote machine while using the desktop app as your interface. This is useful for working with codebases that live on cloud VMs, dev containers, or servers with specific hardware or dependencies.

411 

412To add an SSH connection, click the environment dropdown before starting a session and select **+ Add SSH connection**. The dialog asks for:

413 

414* **Name**: a friendly label for this connection

415* **SSH Host**: `user@hostname` or a host defined in `~/.ssh/config`

416* **SSH Port**: defaults to 22 if left empty, or uses the port from your SSH config

417* **Identity File**: path to your private key, such as `~/.ssh/id_rsa`. Leave empty to use the default key or your SSH config.

418 

419Once added, the connection appears in the environment dropdown. Select it to start a session on that machine. Claude runs on the remote machine with access to its files and tools.

420 

421Claude Code must be installed on the remote machine. Once connected, SSH sessions support permission modes, connectors, plugins, and MCP servers.

114 422 

115## Enterprise configuration423## Enterprise configuration

116 424 

117Organizations can disable local Claude Code use in the desktop application with the `isClaudeCodeForDesktopEnabled` [enterprise policy option](https://support.claude.com/en/articles/12622667-enterprise-configuration#h_003283c7cb). Additionally, Claude Code on the web can be disabled in your [admin settings](https://claude.ai/admin-settings/claude-code).425Organizations on Teams or Enterprise plans can manage desktop app behavior through admin console controls, managed settings files, and device management policies.

426 

427### Admin console controls

428 

429These settings are configured through the [admin settings console](https://claude.ai/admin-settings/claude-code):

430 

431* **Enable or disable the Code tab**: control whether users in your organization can access Claude Code in the desktop app

432* **Disable Bypass permissions mode**: prevent users in your organization from enabling bypass permissions mode

433* **Disable Claude Code on the web**: enable or disable remote sessions for your organization

434 

435### Managed settings

436 

437Managed settings override project and user settings and apply when Desktop spawns CLI sessions. You can set these keys in your organization's [managed settings](/en/settings#settings-precedence) file or push them remotely through the admin console.

438 

439| Key | Description |

440| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |

441| `disableBypassPermissionsMode` | set to `"disable"` to prevent users from enabling Bypass permissions mode. See [managed settings](/en/permissions#managed-only-settings). |

442 

443For the complete list of managed-only settings including `allowManagedPermissionRulesOnly` and `allowManagedHooksOnly`, see [managed-only settings](/en/permissions#managed-only-settings).

444 

445Remote managed settings uploaded through the admin console currently apply to CLI and IDE sessions only. For Desktop-specific restrictions, use the admin console controls above.

446 

447### Device management policies

448 

449IT teams can manage the desktop app through MDM on macOS or group policy on Windows. Available policies include enabling or disabling the Claude Code feature, controlling auto-updates, and setting a custom deployment URL.

450 

451* **macOS**: configure via `com.anthropic.Claude` preference domain using tools like Jamf or Kandji

452* **Windows**: configure via registry at `SOFTWARE\Policies\Claude`

453 

454### Authentication and SSO

455 

456Enterprise organizations can require SSO for all users. See [authentication](/en/authentication) for plan-level details and [Setting up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso) for SAML and OIDC configuration.

457 

458### Data handling

459 

460Claude Code processes your code locally in local sessions or on Anthropic's cloud infrastructure in remote sessions. Conversations and code context are sent to Anthropic's API for processing. See [data handling](/en/data-usage) for details on data retention, privacy, and compliance.

461 

462### Deployment

463 

464Desktop can be distributed through enterprise deployment tools:

465 

466* **macOS**: distribute via MDM such as Jamf or Kandji using the `.dmg` installer

467* **Windows**: deploy via MSIX package or `.exe` installer. See [Deploy Claude Desktop for Windows](https://support.claude.com/en/articles/12622703-deploy-claude-desktop-for-windows) for enterprise deployment options including silent installation

468 

469For network configuration such as proxy settings, firewall allowlisting, and LLM gateways, see [network configuration](/en/network-config).

470 

471For the full enterprise configuration reference, see the [enterprise configuration guide](https://support.claude.com/en/articles/12622667-enterprise-configuration).

472 

473## Coming from the CLI?

474 

475If you already use the Claude Code CLI, Desktop runs the same underlying engine with a graphical interface. You can run both simultaneously on the same machine, even on the same project. Each maintains separate session history, but they share configuration and project memory via CLAUDE.md files.

476 

477To move a CLI session into Desktop, run `/desktop` in the terminal. Claude saves your session and opens it in the desktop app, then exits the CLI. This command is available on macOS and Windows only.

478 

479<Tip>

480 When to use Desktop vs CLI: use Desktop when you want visual diff review, file attachments, or session management in a sidebar. Use the CLI when you need scripting, automation, third-party providers, or prefer a terminal workflow.

481</Tip>

482 

483### CLI flag equivalents

484 

485This table shows the desktop app equivalent for common CLI flags. Flags not listed have no desktop equivalent because they are designed for scripting or automation.

486 

487| CLI | Desktop equivalent |

488| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |

489| `--model sonnet` | model dropdown next to the send button, before starting a session |

490| `--resume`, `--continue` | click a session in the sidebar |

491| `--permission-mode` | mode selector next to the send button |

492| `--dangerously-skip-permissions` | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode". Enterprise admins can disable this setting. |

493| `--add-dir` | add multiple repos with the **+** button in remote sessions |

494| `--allowedTools`, `--disallowedTools` | not available in Desktop |

495| `--verbose` | not available. Check system logs: Console.app on macOS, Event Viewer → Windows Logs → Application on Windows |

496| `--print`, `--output-format` | not available. Desktop is interactive only. |

497| `ANTHROPIC_MODEL` env var | model dropdown next to the send button |

498| `MAX_THINKING_TOKENS` env var | set in shell profile; applies to local sessions. See [environment configuration](#environment-configuration). |

499 

500### Shared configuration

501 

502Desktop and CLI read the same configuration files, so your setup carries over:

503 

504* **[CLAUDE.md](/en/memory)** files in your project are used by both

505* **[MCP servers](/en/mcp)** configured in `~/.claude.json` or `.mcp.json` work in both

506* **[Hooks](/en/hooks)** and **[skills](/en/skills)** defined in settings apply to both

507* **[Settings](/en/settings)** in `~/.claude.json` and `~/.claude/settings.json` are shared. Permission rules, allowed tools, and other settings in `settings.json` apply to Desktop sessions.

508* **Models**: Sonnet, Opus, and Haiku are available in both. In Desktop, select the model from the dropdown next to the send button before starting a session. You cannot change the model during an active session.

509 

510<Note>

511 **MCP servers: desktop chat app vs Claude Code**: MCP servers configured for the Claude Desktop chat app in `claude_desktop_config.json` are separate from Claude Code and will not appear in the Code tab. To use MCP servers in Claude Code, configure them in `~/.claude.json` or your project's `.mcp.json` file. See [MCP configuration](/en/mcp#installing-mcp-servers) for details.

512</Note>

513 

514### Feature comparison

515 

516This table compares core capabilities between the CLI and Desktop. For a full list of CLI flags, see the [CLI reference](/en/cli-reference).

517 

518| Feature | CLI | Desktop |

519| ----------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------- |

520| Permission modes | all modes including `dontAsk` | Ask permissions, Auto accept edits, Plan mode, and Bypass permissions via Settings |

521| `--dangerously-skip-permissions` | CLI flag | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode" |

522| [Third-party providers](/en/third-party-integrations) | Bedrock, Vertex, Foundry | not available. Desktop connects to Anthropic's API directly. |

523| [MCP servers](/en/mcp) | configure in settings files | Connectors UI for local and SSH sessions, or settings files |

524| [Plugins](/en/plugins) | `/plugin` command | plugin manager UI |

525| @mention files | text-based | with autocomplete |

526| File attachments | not available | images, PDFs |

527| Session isolation | [`--worktree`](/en/cli-reference) flag | automatic worktrees |

528| Multiple sessions | separate terminals | sidebar tabs |

529| Recurring tasks | cron jobs, CI pipelines | [scheduled tasks](#schedule-recurring-tasks) |

530| Scripting and automation | [`--print`](/en/cli-reference), [Agent SDK](/en/headless) | not available |

531 

532### What's not available in Desktop

533 

534The following features are only available in the CLI or VS Code extension:

535 

536* **Third-party providers**: Desktop connects to Anthropic's API directly. Use the [CLI](/en/quickstart) with Bedrock, Vertex, or Foundry instead.

537* **Linux**: the desktop app is available on macOS and Windows only.

538* **Inline code suggestions**: Desktop does not provide autocomplete-style suggestions. It works through conversational prompts and explicit code changes.

539* **Agent teams**: multi-agent orchestration is available via the [CLI](/en/agent-teams) and [Agent SDK](/en/headless), not in Desktop.

540 

541## Troubleshooting

542 

543### Check your version

544 

545To see which version of the desktop app you're running:

546 

547* **macOS**: click **Claude** in the menu bar, then **About Claude**

548* **Windows**: click **Help**, then **About**

549 

550Click the version number to copy it to your clipboard.

551 

552### 403 or authentication errors in the Code tab

118 553 

119## Related resources554If you see `Error 403: Forbidden` or other authentication failures when using the Code tab:

120 555 

121* [Claude Code on the web](/en/claude-code-on-the-web)5561. Sign out and back in from the app menu. This is the most common fix.

122* [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop)5572. Verify you have an active paid subscription: Pro, Max, Teams, or Enterprise.

123* [Enterprise Configuration](https://support.claude.com/en/articles/12622667-enterprise-configuration)5583. If the CLI works but Desktop does not, quit the desktop app completely, not just close the window, then reopen and sign in again.

124* [Common workflows](/en/common-workflows)5594. Check your internet connection and proxy settings.

125* [Settings reference](/en/settings)560 

561### Blank or stuck screen on launch

562 

563If the app opens but shows a blank or unresponsive screen:

564 

5651. Restart the app.

5662. Check for pending updates. The app auto-updates on launch.

5673. On Windows, check Event Viewer for crash logs under **Windows Logs → Application**.

568 

569### "Failed to load session"

570 

571If you see `Failed to load session`, the selected folder may no longer exist, a Git repository may require Git LFS that isn't installed, or file permissions may prevent access. Try selecting a different folder or restarting the app.

572 

573### Session not finding installed tools

574 

575If Claude can't find tools like `npm`, `node`, or other CLI commands, verify the tools work in your regular terminal, check that your shell profile properly sets up PATH, and restart the desktop app to reload environment variables.

576 

577### Git and Git LFS errors

578 

579On Windows, Git is required for the Code tab to start local sessions. If you see "Git is required," install [Git for Windows](https://git-scm.com/downloads/win) and restart the app.

580 

581If you see "Git LFS is required by this repository but is not installed," install Git LFS from [git-lfs.com](https://git-lfs.com/), run `git lfs install`, and restart the app.

582 

583### MCP servers not working on Windows

584 

585If MCP server toggles don't respond or servers fail to connect on Windows, check that the server is properly configured in your settings, restart the app, verify the server process is running in Task Manager, and review server logs for connection errors.

586 

587### App won't quit

588 

589* **macOS**: press Cmd+Q. If the app doesn't respond, use Force Quit with Cmd+Option+Esc, select Claude, and click Force Quit.

590* **Windows**: use Task Manager with Ctrl+Shift+Esc to end the Claude process.

591 

592### Windows-specific issues

593 

594* **PATH not updated after install**: open a new terminal window. PATH updates only apply to new terminal sessions.

595* **Concurrent installation error**: if you see an error about another installation in progress but there isn't one, try running the installer as Administrator.

596* **ARM64**: Windows ARM64 devices are fully supported.

597 

598### Cowork tab unavailable on Intel Macs

599 

600The Cowork tab requires Apple Silicon (M1 or later) on macOS. On Windows, Cowork is available on all supported hardware. The Chat and Code tabs work normally on Intel Macs.

601 

602### "Branch doesn't exist yet" when opening in CLI

603 

604Remote sessions can create branches that don't exist on your local machine. Click the branch name in the session toolbar to copy it, then fetch it locally:

605 

606```bash theme={null}

607git fetch origin <branch-name>

608git checkout <branch-name>

609```

126 610 

611### Still stuck?

127 612 

613* Search or file a bug on [GitHub Issues](https://github.com/anthropics/claude-code/issues)

614* Visit the [Claude support center](https://support.claude.com/)

128 615 

129> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt616When filing a bug, include your desktop app version, your operating system, the exact error message, and relevant logs. On macOS, check Console.app. On Windows, check Event Viewer → Windows Logs → Application.

desktop-quickstart.md +139 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Get started with the desktop app

6 

7> Install Claude Code on desktop and start your first coding session

8 

9The desktop app gives you Claude Code with a graphical interface: visual diff review, live app preview, GitHub PR monitoring with auto-merge, parallel sessions with Git worktree isolation, scheduled tasks, and the ability to run tasks remotely. No terminal required.

10 

11This page walks through installing the app and starting your first session. If you're already set up, see [Use Claude Code Desktop](/en/desktop) for the full reference.

12 

13<Frame>

14 <img src="https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=9a36a7a27b9f4c6f2e1c83bdb34f69ce" className="block dark:hidden" alt="The Claude Code Desktop interface showing the Code tab selected, with a prompt box, permission mode selector set to Ask permissions, model picker, folder selector, and Local environment option" width="2500" height="1376" data-path="images/desktop-code-tab-light.png" />

15 

16 <img src="https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=5463defe81c459fb9b1f91f6a958cfb8" className="hidden dark:block" alt="The Claude Code Desktop interface in dark mode showing the Code tab selected, with a prompt box, permission mode selector set to Ask permissions, model picker, folder selector, and Local environment option" width="2504" height="1374" data-path="images/desktop-code-tab-dark.png" />

17</Frame>

18 

19The desktop app has three tabs:

20 

21* **Chat**: General conversation with no file access, similar to claude.ai.

22* **Cowork**: An autonomous background agent that works on tasks in a cloud VM with its own environment. It can run independently while you do other work.

23* **Code**: An interactive coding assistant with direct access to your local files. You review and approve each change in real time.

24 

25Chat and Cowork are covered in the [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop). This page focuses on the **Code** tab.

26 

27<Note>

28 Claude Code requires a [Pro, Max, Teams, or Enterprise subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_pricing).

29</Note>

30 

31## Install

32 

33<Steps>

34 <Step title="Download the app">

35 Download Claude for your platform.

36 

37 <CardGroup cols={2}>

38 <Card title="macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

39 Universal build for Intel and Apple Silicon

40 </Card>

41 

42 <Card title="Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs">

43 For x64 processors

44 </Card>

45 </CardGroup>

46 

47 For Windows ARM64, [download here](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs).

48 

49 Linux is not currently supported.

50 </Step>

51 

52 <Step title="Sign in">

53 Launch Claude from your Applications folder (macOS) or Start menu (Windows). Sign in with your Anthropic account.

54 </Step>

55 

56 <Step title="Open the Code tab">

57 Click the **Code** tab at the top center. If clicking Code prompts you to upgrade, you need to [subscribe to a paid plan](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_upgrade) first. If it prompts you to sign in online, complete the sign-in and restart the app. If you see a 403 error, see [authentication troubleshooting](/en/desktop#403-or-authentication-errors-in-the-code-tab).

58 </Step>

59</Steps>

60 

61The desktop app includes Claude Code. You don't need to install Node.js or the CLI separately. To use `claude` from the terminal, install the CLI separately. See [Get started with the CLI](/en/quickstart).

62 

63## Start your first session

64 

65With the Code tab open, choose a project and give Claude something to do.

66 

67<Steps>

68 <Step title="Choose an environment and folder">

69 Select **Local** to run Claude on your machine using your files directly. Click **Select folder** and choose your project directory.

70 

71 <Tip>

72 Start with a small project you know well. It's the fastest way to see what Claude Code can do. On Windows, [Git](https://git-scm.com/downloads/win) must be installed for local sessions to work. Most Macs include Git by default.

73 </Tip>

74 

75 You can also select:

76 

77 * **Remote**: Run sessions on Anthropic's cloud infrastructure that continue even if you close the app. Remote sessions use the same infrastructure as [Claude Code on the web](/en/claude-code-on-the-web).

78 * **SSH**: Connect to a remote machine over SSH (your own servers, cloud VMs, or dev containers). Claude Code must be installed on the remote machine.

79 </Step>

80 

81 <Step title="Choose a model">

82 Select a model from the dropdown next to the send button. See [models](/en/model-config#available-models) for a comparison of Opus, Sonnet, and Haiku. You cannot change the model after the session starts.

83 </Step>

84 

85 <Step title="Tell Claude what to do">

86 Type what you want Claude to do:

87 

88 * `Find a TODO comment and fix it`

89 * `Add tests for the main function`

90 * `Create a CLAUDE.md with instructions for this codebase`

91 

92 A [session](/en/desktop#work-in-parallel-with-sessions) is a conversation with Claude about your code. Each session tracks its own context and changes, so you can work on multiple tasks without them interfering with each other.

93 </Step>

94 

95 <Step title="Review and accept changes">

96 By default, the Code tab starts in [Ask permissions mode](/en/desktop#choose-a-permission-mode), where Claude proposes changes and waits for your approval before applying them. You'll see:

97 

98 1. A [diff view](/en/desktop#review-changes-with-diff-view) showing exactly what will change in each file

99 2. Accept/Reject buttons to approve or decline each change

100 3. Real-time updates as Claude works through your request

101 

102 If you reject a change, Claude will ask how you'd like to proceed differently. Your files aren't modified until you accept.

103 </Step>

104</Steps>

105 

106## Now what?

107 

108You've made your first edit. For the full reference on everything Desktop can do, see [Use Claude Code Desktop](/en/desktop). Here are some things to try next.

109 

110**Interrupt and steer.** You can interrupt Claude at any point. If it's going down the wrong path, click the stop button or type your correction and press **Enter**. Claude stops what it's doing and adjusts based on your input. You don't have to wait for it to finish or start over.

111 

112**Give Claude more context.** Type `@filename` in the prompt box to pull a specific file into the conversation, attach images and PDFs using the attachment button, or drag and drop files directly into the prompt. The more context Claude has, the better the results. See [Add files and context](/en/desktop#add-files-and-context-to-prompts).

113 

114**Use skills for repeatable tasks.** Type `/` or click **+** → **Slash commands** to browse [built-in commands](/en/commands), [custom skills](/en/skills), and plugin skills. Skills are reusable prompts you can invoke whenever you need them, like code review checklists or deployment steps.

115 

116**Review changes before committing.** After Claude edits files, a `+12 -1` indicator appears. Click it to open the [diff view](/en/desktop#review-changes-with-diff-view), review modifications file by file, and comment on specific lines. Claude reads your comments and revises. Click **Review code** to have Claude evaluate the diffs itself and leave inline suggestions.

117 

118**Adjust how much control you have.** Your [permission mode](/en/desktop#choose-a-permission-mode) controls the balance. Ask permissions (default) requires approval before every edit. Auto accept edits auto-accepts file edits for faster iteration. Plan mode lets Claude map out an approach without touching any files, which is useful before a large refactor.

119 

120**Add plugins for more capabilities.** Click the **+** button next to the prompt box and select **Plugins** to browse and install [plugins](/en/desktop#install-plugins) that add skills, agents, MCP servers, and more.

121 

122**Preview your app.** Click the **Preview** dropdown to run your dev server directly in the desktop. Claude can view the running app, test endpoints, inspect logs, and iterate on what it sees. See [Preview your app](/en/desktop#preview-your-app).

123 

124**Track your pull request.** After opening a PR, Claude Code monitors CI check results and can automatically fix failures or merge the PR once all checks pass. See [Monitor pull request status](/en/desktop#monitor-pull-request-status).

125 

126**Put Claude on a schedule.** Set up [scheduled tasks](/en/desktop#schedule-recurring-tasks) to run Claude automatically on a recurring basis: a daily code review every morning, a weekly dependency audit, or a briefing that pulls from your connected tools.

127 

128**Scale up when you're ready.** Open [parallel sessions](/en/desktop#work-in-parallel-with-sessions) from the sidebar to work on multiple tasks at once, each in its own Git worktree. Send [long-running work to the cloud](/en/desktop#run-long-running-tasks-remotely) so it continues even if you close the app, or [continue a session on the web or in your IDE](/en/desktop#continue-in-another-surface) if a task takes longer than expected. [Connect external tools](/en/desktop#extend-claude-code) like GitHub, Slack, and Linear to bring your workflow together.

129 

130## Coming from the CLI?

131 

132Desktop runs the same engine as the CLI with a graphical interface. You can run both simultaneously on the same project, and they share configuration (CLAUDE.md files, MCP servers, hooks, skills, and settings). For a full comparison of features, flag equivalents, and what's not available in Desktop, see [CLI comparison](/en/desktop#coming-from-the-cli).

133 

134## What's next

135 

136* [Use Claude Code Desktop](/en/desktop): permission modes, parallel sessions, diff view, connectors, and enterprise configuration

137* [Troubleshooting](/en/desktop#troubleshooting): solutions to common errors and setup issues

138* [Best practices](/en/best-practices): tips for writing effective prompts and getting the most out of Claude Code

139* [Common workflows](/en/common-workflows): tutorials for debugging, refactoring, testing, and more

devcontainer.md +4 −4

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Development containers5# Development containers

2 6 

3> Learn about the Claude Code development container for teams that need consistent, secure environments.7> Learn about the Claude Code development container for teams that need consistent, secure environments.


75* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)79* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)

76* [Claude Code security best practices](/en/security)80* [Claude Code security best practices](/en/security)

77* [Enterprise network configuration](/en/network-config)81* [Enterprise network configuration](/en/network-config)

78 

79 

80 

81> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Discover and install prebuilt plugins through marketplaces5# Discover and install prebuilt plugins through marketplaces

2 6 

3> Find and install plugins from marketplaces to extend Claude Code with new commands, agents, and capabilities.7> Find and install plugins from marketplaces to extend Claude Code with new commands, agents, and capabilities.


33```37```

34 38 

35<Note>39<Note>

36 The official marketplace is maintained by Anthropic. To distribute your own plugins, [create your own marketplace](/en/plugin-marketplaces) and share it with users.40 The official marketplace is maintained by Anthropic. To submit a plugin to the official marketplace, use one of the in-app submission forms:

41 

42 * **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

43 * **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

44 

45 To distribute plugins independently, [create your own marketplace](/en/plugin-marketplaces) and share it with users.

37</Note>46</Note>

38 47 

39The official marketplace includes several categories of plugins:48The official marketplace includes several categories of plugins:


145 </Step>154 </Step>

146 155 

147 <Step title="Use your new plugin">156 <Step title="Use your new plugin">

148 After installing, the plugin's commands are immediately available. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`.157 After installing, run `/reload-plugins` to activate the plugin. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`.

149 158 

150 Try it out by making a change to a file and running:159 Try it out by making a change to a file and running:

151 160 


285claude plugin uninstall formatter@your-org --scope project294claude plugin uninstall formatter@your-org --scope project

286```295```

287 296 

297### Apply plugin changes without restarting

298 

299When you install, enable, or disable plugins during a session, run `/reload-plugins` to pick up all changes without restarting:

300 

301```shell theme={null}

302/reload-plugins

303```

304 

305Claude Code reloads all active plugins and shows counts for reloaded commands, skills, agents, hooks, plugin MCP servers, and plugin LSP servers.

306 

288## Manage marketplaces307## Manage marketplaces

289 308 

290You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.309You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.


326 345 

327### Configure auto-updates346### Configure auto-updates

328 347 

329Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you'll see a notification suggesting you restart Claude Code.348Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you'll see a notification prompting you to run `/reload-plugins`.

330 349 

331Toggle auto-update for individual marketplaces through the UI:350Toggle auto-update for individual marketplaces through the UI:

332 351 


352 371 

353Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins.372Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins.

354 373 

374Add `extraKnownMarketplaces` to your project's `.claude/settings.json`:

375 

376```json theme={null}

377{

378 "extraKnownMarketplaces": {

379 "my-team-tools": {

380 "source": {

381 "source": "github",

382 "repo": "your-org/claude-plugins"

383 }

384 }

385 }

386}

387```

388 

355For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/en/settings#plugin-settings).389For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/en/settings#plugin-settings).

356 390 

391## Security

392 

393Plugins and marketplaces are highly trusted components that can execute arbitrary code on your machine with your user privileges. Only install plugins and add marketplaces from sources you trust. Organizations can restrict which marketplaces users are allowed to add using [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).

394 

357## Troubleshooting395## Troubleshooting

358 396 

359### /plugin command not recognized397### /plugin command not recognized


387* **Build your own plugins**: See [Plugins](/en/plugins) to create skills, agents, and hooks425* **Build your own plugins**: See [Plugins](/en/plugins) to create skills, agents, and hooks

388* **Create a marketplace**: See [Create a plugin marketplace](/en/plugin-marketplaces) to distribute plugins to your team or community426* **Create a marketplace**: See [Create a plugin marketplace](/en/plugin-marketplaces) to distribute plugins to your team or community

389* **Technical reference**: See [Plugins reference](/en/plugins-reference) for complete specifications427* **Technical reference**: See [Plugins reference](/en/plugins-reference) for complete specifications

390 

391 

392 

393> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

env-vars.md +117 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Environment variables

6 

7> Complete reference for environment variables that control Claude Code behavior.

8 

9Claude Code supports the following environment variables to control its behavior. Set them in your shell before launching `claude`, or configure them in [`settings.json`](/en/settings#available-settings) under the `env` key to apply them to every session or roll them out across your team.

10 

11| Variable | Purpose |

12| :--------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

13| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |

14| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) |

15| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) |

16| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

17| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

18| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

19| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry authentication (see [Microsoft Foundry](/en/microsoft-foundry)) |

20| `ANTHROPIC_FOUNDRY_BASE_URL` | Full base URL for the Foundry resource (for example, `https://my-resource.services.ai.azure.com/anthropic`). Alternative to `ANTHROPIC_FOUNDRY_RESOURCE` (see [Microsoft Foundry](/en/microsoft-foundry)) |

21| `ANTHROPIC_FOUNDRY_RESOURCE` | Foundry resource name (for example, `my-resource`). Required if `ANTHROPIC_FOUNDRY_BASE_URL` is not set (see [Microsoft Foundry](/en/microsoft-foundry)) |

22| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) |

23| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |

24| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |

25| `AWS_BEARER_TOKEN_BEDROCK` | Bedrock API key for authentication (see [Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)) |

26| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |

27| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |

28| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |

29| `CLAUDECODE` | Set to `1` in shell environments Claude Code spawns (Bash tool, tmux sessions). Not set in [hooks](/en/hooks) or [status line](/en/statusline) commands. Use to detect when a script is running inside a shell spawned by Claude Code |

30| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Set the percentage of context capacity (1-100) at which auto-compaction triggers. By default, auto-compaction triggers at approximately 95% capacity. Use lower values like `50` to compact earlier. Values above the default threshold have no effect. Applies to both main conversations and subagents. This percentage aligns with the `context_window.used_percentage` field available in [status line](/en/statusline) |

31| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |

32| `CLAUDE_CODE_ACCOUNT_UUID` | Account UUID for the authenticated user. Used by SDK callers to provide account information synchronously, avoiding a race condition where early telemetry events lack account metadata. Requires `CLAUDE_CODE_USER_EMAIL` and `CLAUDE_CODE_ORGANIZATION_UUID` to also be set |

33| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load CLAUDE.md files from directories specified with `--add-dir`. By default, additional directories do not load memory files |

34| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model's context window: 200K for standard models or 1M for [extended context](/en/model-config#extended-context) models. Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model's actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line's `used_percentage`, which always uses the model's full context window |

35| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](/en/settings#available-settings)) |

36| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |

37| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |

38| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |

39| `CLAUDE_CODE_DISABLE_1M_CONTEXT` | Set to `1` to disable [1M context window](/en/model-config#extended-context) support. When set, 1M model variants are unavailable in the model picker. Useful for enterprise environments with compliance requirements |

40| `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | Set to `1` to disable [adaptive reasoning](/en/model-config#adjust-effort-level) for Opus 4.6 and Sonnet 4.6. When disabled, these models fall back to the fixed thinking budget controlled by `MAX_THINKING_TOKENS` |

41| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | Set to `1` to disable [auto memory](/en/memory#auto-memory). Set to `0` to force auto memory on during the gradual rollout. When disabled, Claude does not create or load auto memory files |

42| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | Set to `1` to remove built-in commit and PR workflow instructions from Claude's system prompt. Useful when using your own git workflow skills. Takes precedence over the [`includeGitInstructions`](/en/settings#available-settings) setting when set |

43| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Set to `1` to disable all background task functionality, including the `run_in_background` parameter on Bash and subagent tools, auto-backgrounding, and the Ctrl+B shortcut |

44| `CLAUDE_CODE_DISABLE_CRON` | Set to `1` to disable [scheduled tasks](/en/scheduled-tasks). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session |

45| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to disable Anthropic API-specific `anthropic-beta` headers. Use this if experiencing issues like "Unexpected value(s) for the `anthropic-beta` header" when using an LLM gateway with third-party providers |

46| `CLAUDE_CODE_DISABLE_FAST_MODE` | Set to `1` to disable [fast mode](/en/fast-mode) |

47| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. See [Session quality surveys](/en/data-usage#session-quality-surveys) |

48| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |

49| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |

50| `CLAUDE_CODE_EFFORT_LEVEL` | Set the effort level for supported models. Values: `low`, `medium`, `high`, `max` (Opus 4.6 only), or `auto` to use the model default. Takes precedence over `/effort` and the `effortLevel` setting. See [Adjust effort level](/en/model-config#adjust-effort-level) |

51| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | Set to `false` to disable prompt suggestions (the "Prompt suggestions" toggle in `/config`). These are the grayed-out predictions that appear in your prompt input after Claude responds. See [Prompt suggestions](/en/interactive-mode#prompt-suggestions) |

52| `CLAUDE_CODE_ENABLE_TASKS` | Set to `true` to enable the task tracking system in non-interactive mode (the `-p` flag). Tasks are on by default in interactive mode. See [Task list](/en/interactive-mode#task-list) |

53| `CLAUDE_CODE_ENABLE_TELEMETRY` | Set to `1` to enable OpenTelemetry data collection for metrics and logging. Required before configuring OTel exporters. See [Monitoring](/en/monitoring-usage) |

54| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | Time in milliseconds to wait after the query loop becomes idle before automatically exiting. Useful for automated workflows and scripts using SDK mode |

55| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Set to `1` to enable [agent teams](/en/agent-teams). Agent teams are experimental and disabled by default |

56| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | Override the default token limit for file reads. Useful when you need to read larger files in full |

57| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |

58| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Default: 32,000. Maximum: 64,000. Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers. |

59| `CLAUDE_CODE_ORGANIZATION_UUID` | Organization UUID for the authenticated user. Used by SDK callers to provide account information synchronously. Requires `CLAUDE_CODE_ACCOUNT_UUID` and `CLAUDE_CODE_USER_EMAIL` to also be set |

60| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic OpenTelemetry headers in milliseconds (default: 1740000 / 29 minutes). See [Dynamic headers](/en/monitoring-usage#dynamic-headers) |

61| `CLAUDE_CODE_PLAN_MODE_REQUIRED` | Auto-set to `true` on [agent team](/en/agent-teams) teammates that require plan approval. Read-only: set by Claude Code when spawning teammates. See [require plan approval](/en/agent-teams#require-plan-approval-for-teammates) |

62| `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` | Timeout in milliseconds for git operations when installing or updating plugins (default: 120000). Increase this value for large repositories or slow network connections. See [Git operations time out](/en/plugin-marketplaces#git-operations-time-out) |

63| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `true` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |

64| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Maximum time in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks to complete (default: `1500`). Applies to both session exit and `/clear`. Per-hook `timeout` values are also capped by this budget |

65| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |

66| `CLAUDE_CODE_SHELL_PREFIX` | Command prefix to wrap all bash commands (for example, for logging or auditing). Example: `/path/to/logger.sh` will execute `/path/to/logger.sh <command>` |

67| `CLAUDE_CODE_SIMPLE` | Set to `1` to run with a minimal system prompt and only the Bash, file read, and file edit tools. Disables MCP tools, attachments, hooks, and CLAUDE.md files |

68| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |

69| `CLAUDE_CODE_SKIP_FAST_MODE_NETWORK_ERRORS` | Set to `1` to allow [fast mode](/en/fast-mode) when the organization status check fails due to a network error. Useful when a corporate proxy blocks the status endpoint. The API still enforces organization-level disable separately |

70| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |

71| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) |

72| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) |

73| `CLAUDE_CODE_TASK_LIST_ID` | Share a task list across sessions. Set the same ID in multiple Claude Code instances to coordinate on a shared task list. See [Task list](/en/interactive-mode#task-list) |

74| `CLAUDE_CODE_TEAM_NAME` | Name of the agent team this teammate belongs to. Set automatically on [agent team](/en/agent-teams) members |

75| `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude/` to this path. Default: `/tmp` on Unix/macOS, `os.tmpdir()` on Windows |

76| `CLAUDE_CODE_USER_EMAIL` | Email address for the authenticated user. Used by SDK callers to provide account information synchronously. Requires `CLAUDE_CODE_ACCOUNT_UUID` and `CLAUDE_CODE_ORGANIZATION_UUID` to also be set |

77| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |

78| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) |

79| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |

80| `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files |

81| `CLAUDE_ENV_FILE` | Path to a shell script that Claude Code sources before each Bash command. Use to persist virtualenv or conda activation across commands. Also populated dynamically by [SessionStart hooks](/en/hooks#persist-environment-variables) |

82| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. |

83| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |

84| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |

85| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |

86| `DISABLE_INSTALLATION_CHECKS` | Set to `1` to disable installation warnings. Use only when manually managing the installation location, as this can mask issues with standard installations |

87| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |

88| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

89| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

90| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

91| `DISABLE_TELEMETRY` | Set to `1` to opt out of Statsig telemetry (note that Statsig events do not include user data like code, file paths, or bash commands) |

92| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/en/mcp#use-mcp-servers-from-claudeai) in Claude Code. Enabled by default for logged-in users |

93| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/en/mcp#scale-with-mcp-tool-search). Unset: enabled by default, but disabled when `ANTHROPIC_BASE_URL` points to a non-first-party host. Values: `true` (always on including proxies), `auto` (enables at 10% context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `false` (disabled) |

94| `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |

95| `HTTP_PROXY` | Specify HTTP proxy server for network connections |

96| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |

97| `IS_DEMO` | Set to `true` to enable demo mode: hides email and organization from the UI, skips onboarding, and hides internal commands. Useful for streaming or recording sessions |

98| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000) |

99| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token budget. Thinking is enabled at max budget (31,999 tokens) by default. Use this to limit the budget (for example, `MAX_THINKING_TOKENS=10000`) or disable thinking entirely (`MAX_THINKING_TOKENS=0`). For Opus 4.6, thinking depth is controlled by [effort level](/en/model-config#adjust-effort-level) instead, and this variable is ignored unless set to `0` to disable thinking. |

100| `MCP_CLIENT_SECRET` | OAuth client secret for MCP servers that require [pre-configured credentials](/en/mcp#use-pre-configured-oauth-credentials). Avoids the interactive prompt when adding a server with `--client-secret` |

101| `MCP_OAUTH_CALLBACK_PORT` | Fixed port for the OAuth redirect callback, as an alternative to `--callback-port` when adding an MCP server with [pre-configured credentials](/en/mcp#use-pre-configured-oauth-credentials) |

102| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |

103| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |

104| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |

105| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Override the character budget for skill metadata shown to the [Skill tool](/en/skills#control-who-invokes-a-skill). The budget scales dynamically at 2% of the context window, with a fallback of 16,000 characters. Legacy name kept for backwards compatibility |

106| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code |

107| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |

108| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |

109| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |

110| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |

111| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |

112 

113## See also

114 

115* [Settings](/en/settings): configure environment variables in `settings.json` so they apply to every session

116* [CLI reference](/en/cli-reference): launch-time flags

117* [Network configuration](/en/network-config): proxy and TLS setup

fast-mode.md +150 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Speed up responses with fast mode

6 

7> Get faster Opus 4.6 responses in Claude Code by toggling fast mode.

8 

9<Note>

10 Fast mode is in [research preview](#research-preview). The feature, pricing, and availability may change based on feedback.

11</Note>

12 

13Fast mode is a high-speed configuration for Claude Opus 4.6, making the model 2.5x faster at a higher cost per token. Toggle it on with `/fast` when you need speed for interactive work like rapid iteration or live debugging, and toggle it off when cost matters more than latency.

14 

15Fast mode is not a different model. It uses the same Opus 4.6 with a different API configuration that prioritizes speed over cost efficiency. You get identical quality and capabilities, just faster responses.

16 

17<Note>

18 Fast mode requires Claude Code v2.1.36 or later. Check your version with `claude --version`.

19</Note>

20 

21What to know:

22 

23* Use `/fast` to toggle on fast mode in Claude Code CLI. Also available via `/fast` in Claude Code VS Code Extension.

24* Fast mode for Opus 4.6 pricing is \$30/150 MTok.

25* Available to all Claude Code users on subscription plans (Pro/Max/Team/Enterprise) and Claude Console.

26* For Claude Code users on subscription plans (Pro/Max/Team/Enterprise), fast mode is available via extra usage only and not included in the subscription rate limits.

27 

28This page covers how to [toggle fast mode](#toggle-fast-mode), its [cost tradeoff](#understand-the-cost-tradeoff), [when to use it](#decide-when-to-use-fast-mode), [requirements](#requirements), [per-session opt-in](#require-per-session-opt-in), and [rate limit behavior](#handle-rate-limits).

29 

30## Toggle fast mode

31 

32Toggle fast mode in either of these ways:

33 

34* Type `/fast` and press Tab to toggle on or off

35* Set `"fastMode": true` in your [user settings file](/en/settings)

36 

37By default, fast mode persists across sessions. Administrators can configure fast mode to reset each session. See [require per-session opt-in](#require-per-session-opt-in) for details.

38 

39For the best cost efficiency, enable fast mode at the start of a session rather than switching mid-conversation. See [understand the cost tradeoff](#understand-the-cost-tradeoff) for details.

40 

41When you enable fast mode:

42 

43* If you're on a different model, Claude Code automatically switches to Opus 4.6

44* You'll see a confirmation message: "Fast mode ON"

45* A small `↯` icon appears next to the prompt while fast mode is active

46* Run `/fast` again at any time to check whether fast mode is on or off

47 

48When you disable fast mode with `/fast` again, you remain on Opus 4.6. The model does not revert to your previous model. To switch to a different model, use `/model`.

49 

50## Understand the cost tradeoff

51 

52Fast mode has higher per-token pricing than standard Opus 4.6:

53 

54| Mode | Input (MTok) | Output (MTok) |

55| --------------------- | ------------ | ------------- |

56| Fast mode on Opus 4.6 | \$30 | \$150 |

57 

58Fast mode pricing is flat across the full 1M token context window.

59 

60When you switch into fast mode mid-conversation, you pay the full fast mode uncached input token price for the entire conversation context. This costs more than if you had enabled fast mode from the start.

61 

62## Decide when to use fast mode

63 

64Fast mode is best for interactive work where response latency matters more than cost:

65 

66* Rapid iteration on code changes

67* Live debugging sessions

68* Time-sensitive work with tight deadlines

69 

70Standard mode is better for:

71 

72* Long autonomous tasks where speed matters less

73* Batch processing or CI/CD pipelines

74* Cost-sensitive workloads

75 

76### Fast mode vs effort level

77 

78Fast mode and effort level both affect response speed, but differently:

79 

80| Setting | Effect |

81| ---------------------- | -------------------------------------------------------------------------------- |

82| **Fast mode** | Same model quality, lower latency, higher cost |

83| **Lower effort level** | Less thinking time, faster responses, potentially lower quality on complex tasks |

84 

85You can combine both: use fast mode with a lower [effort level](/en/model-config#adjust-effort-level) for maximum speed on straightforward tasks.

86 

87## Requirements

88 

89Fast mode requires all of the following:

90 

91* **Not available on third-party cloud providers**: fast mode is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Azure Foundry. Fast mode is available through the Anthropic Console API and for Claude subscription plans using extra usage.

92* **Extra usage enabled**: your account must have extra usage enabled, which allows billing beyond your plan's included usage. For individual accounts, enable this in your [Console billing settings](https://platform.claude.com/settings/organization/billing). For Teams and Enterprise, an admin must enable extra usage for the organization.

93 

94<Note>

95 Fast mode usage is billed directly to extra usage, even if you have remaining usage on your plan. This means fast mode tokens do not count against your plan's included usage and are charged at the fast mode rate from the first token.

96</Note>

97 

98* **Admin enablement for Teams and Enterprise**: fast mode is disabled by default for Teams and Enterprise organizations. An admin must explicitly [enable fast mode](#enable-fast-mode-for-your-organization) before users can access it.

99 

100<Note>

101 If your admin has not enabled fast mode for your organization, the `/fast` command will show "Fast mode has been disabled by your organization."

102</Note>

103 

104### Enable fast mode for your organization

105 

106Admins can enable fast mode in:

107 

108* **Console** (API customers): [Claude Code preferences](https://platform.claude.com/claude-code/preferences)

109* **Claude AI** (Teams and Enterprise): [Admin Settings > Claude Code](https://claude.ai/admin-settings/claude-code)

110 

111Another option to disable fast mode entirely is to set `CLAUDE_CODE_DISABLE_FAST_MODE=1`. See [Environment variables](/en/env-vars).

112 

113### Require per-session opt-in

114 

115By default, fast mode persists across sessions: if a user enables fast mode, it stays on in future sessions. Administrators on [Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_teams#team-&-enterprise) or [Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_enterprise) plans can prevent this by setting `fastModePerSessionOptIn` to `true` in [managed settings](/en/settings#settings-files) or [server-managed settings](/en/server-managed-settings). This causes each session to start with fast mode off, requiring users to explicitly enable it with `/fast`.

116 

117```json theme={null}

118{

119 "fastModePerSessionOptIn": true

120}

121```

122 

123This is useful for controlling costs in organizations where users run multiple concurrent sessions. Users can still enable fast mode with `/fast` when they need speed, but it resets at the start of each new session. The user's fast mode preference is still saved, so removing this setting restores the default persistent behavior.

124 

125## Handle rate limits

126 

127Fast mode has separate rate limits from standard Opus 4.6. When you hit the fast mode rate limit or run out of extra usage credits:

128 

1291. Fast mode automatically falls back to standard Opus 4.6

1302. The `↯` icon turns gray to indicate cooldown

1313. You continue working at standard speed and pricing

1324. When the cooldown expires, fast mode automatically re-enables

133 

134To disable fast mode manually instead of waiting for cooldown, run `/fast` again.

135 

136## Research preview

137 

138Fast mode is a research preview feature. This means:

139 

140* The feature may change based on feedback

141* Availability and pricing are subject to change

142* The underlying API configuration may evolve

143 

144Report issues or feedback through your usual Anthropic support channels.

145 

146## See also

147 

148* [Model configuration](/en/model-config): switch models and adjust effort levels

149* [Manage costs effectively](/en/costs): track token usage and reduce costs

150* [Status line configuration](/en/statusline): display model and context information

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Extend Claude Code5# Extend Claude Code

2 6 

3> Understand when to use CLAUDE.md, Skills, subagents, hooks, MCP, and plugins.7> Understand when to use CLAUDE.md, Skills, subagents, hooks, MCP, and plugins.


18* **[Skills](/en/skills)** add reusable knowledge and invocable workflows22* **[Skills](/en/skills)** add reusable knowledge and invocable workflows

19* **[MCP](/en/mcp)** connects Claude to external services and tools23* **[MCP](/en/mcp)** connects Claude to external services and tools

20* **[Subagents](/en/sub-agents)** run their own loops in isolated context, returning summaries24* **[Subagents](/en/sub-agents)** run their own loops in isolated context, returning summaries

25* **[Agent teams](/en/agent-teams)** coordinate multiple independent sessions with shared tasks and peer-to-peer messaging

21* **[Hooks](/en/hooks)** run outside the loop entirely as deterministic scripts26* **[Hooks](/en/hooks)** run outside the loop entirely as deterministic scripts

22* **[Plugins](/en/plugins)** and **[marketplaces](/en/plugin-marketplaces)** package and distribute these features27* **[Plugins](/en/plugins)** and **[marketplaces](/en/plugin-marketplaces)** package and distribute these features

23 28 

24[Skills](/en/skills) are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a slash command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents.29[Skills](/en/skills) are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents.

25 30 

26## Match features to your goal31## Match features to your goal

27 32 

28Features range from always-on context that Claude sees every session, to on-demand capabilities you or Claude can invoke, to background automation that runs on specific events. The table below shows what's available and when each one makes sense.33Features range from always-on context that Claude sees every session, to on-demand capabilities you or Claude can invoke, to background automation that runs on specific events. The table below shows what's available and when each one makes sense.

29 34 

30| Feature | What it does | When to use it | Example |35| Feature | What it does | When to use it | Example |

31| ------------- | ---------------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------- |36| ---------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |

32| **CLAUDE.md** | Persistent context loaded every conversation | Project conventions, "always do X" rules | "Use pnpm, not npm. Run tests before committing." |37| **CLAUDE.md** | Persistent context loaded every conversation | Project conventions, "always do X" rules | "Use pnpm, not npm. Run tests before committing." |

33| **Skill** | Instructions, knowledge, and workflows Claude can use | Reusable content, reference docs, repeatable tasks | `/review` runs your code review checklist; API docs skill with endpoint patterns |38| **Skill** | Instructions, knowledge, and workflows Claude can use | Reusable content, reference docs, repeatable tasks | `/deploy` runs your deployment checklist; API docs skill with endpoint patterns |

34| **Subagent** | Isolated execution context that returns summarized results | Context isolation, parallel tasks, specialized workers | Research task that reads many files but returns only key findings |39| **Subagent** | Isolated execution context that returns summarized results | Context isolation, parallel tasks, specialized workers | Research task that reads many files but returns only key findings |

40| **[Agent teams](/en/agent-teams)** | Coordinate multiple independent Claude Code sessions | Parallel research, new feature development, debugging with competing hypotheses | Spawn reviewers to check security, performance, and tests simultaneously |

35| **MCP** | Connect to external services | External data or actions | Query your database, post to Slack, control a browser |41| **MCP** | Connect to external services | External data or actions | Query your database, post to Slack, control a browser |

36| **Hook** | Deterministic script that runs on events | Predictable automation, no LLM involved | Run ESLint after every file edit |42| **Hook** | Deterministic script that runs on events | Predictable automation, no LLM involved | Run ESLint after every file edit |

37 43 


75 81 

76 **Put it in a skill** if it's reference material Claude needs sometimes (API docs, style guides) or a workflow you trigger with `/<name>` (deploy, review, release).82 **Put it in a skill** if it's reference material Claude needs sometimes (API docs, style guides) or a workflow you trigger with `/<name>` (deploy, review, release).

77 83 

78 **Rule of thumb:** Keep CLAUDE.md under \~500 lines. If it's growing, move reference content to skills.84 **Rule of thumb:** Keep CLAUDE.md under 200 lines. If it's growing, move reference content to skills or split into [`.claude/rules/`](/en/memory#organize-rules-with-clauderules) files.

85 </Tab>

86 

87 <Tab title="CLAUDE.md vs Rules vs Skills">

88 All three store instructions, but they load differently:

89 

90 | Aspect | CLAUDE.md | `.claude/rules/` | Skill |

91 | ------------ | ----------------------------------- | -------------------------------------------------- | ---------------------------------------- |

92 | **Loads** | Every session | Every session, or when matching files are opened | On demand, when invoked or relevant |

93 | **Scope** | Whole project | Can be scoped to file paths | Task-specific |

94 | **Best for** | Core conventions and build commands | Language-specific or directory-specific guidelines | Reference material, repeatable workflows |

95 

96 **Use CLAUDE.md** for instructions every session needs: build commands, test conventions, project architecture.

97 

98 **Use rules** to keep CLAUDE.md focused. Rules with [`paths` frontmatter](/en/memory#path-specific-rules) only load when Claude works with matching files, saving context.

99 

100 **Use skills** for content Claude only needs sometimes, like API documentation or a deployment checklist you trigger with `/<name>`.

101 </Tab>

102 

103 <Tab title="Subagent vs Agent team">

104 Both parallelize work, but they're architecturally different:

105 

106 * **Subagents** run inside your session and report results back to your main context

107 * **Agent teams** are independent Claude Code sessions that communicate with each other

108 

109 | Aspect | Subagent | Agent team |

110 | ----------------- | ------------------------------------------------ | --------------------------------------------------- |

111 | **Context** | Own context window; results return to the caller | Own context window; fully independent |

112 | **Communication** | Reports results back to the main agent only | Teammates message each other directly |

113 | **Coordination** | Main agent manages all work | Shared task list with self-coordination |

114 | **Best for** | Focused tasks where only the result matters | Complex work requiring discussion and collaboration |

115 | **Token cost** | Lower: results summarized back to main context | Higher: each teammate is a separate Claude instance |

116 

117 **Use a subagent** when you need a quick, focused worker: research a question, verify a claim, review a file. The subagent does the work and returns a summary. Your main conversation stays clean.

118 

119 **Use an agent team** when teammates need to share findings, challenge each other, and coordinate independently. Agent teams are best for research with competing hypotheses, parallel code review, and new feature development where each teammate owns a separate piece.

120 

121 **Transition point:** If you're running parallel subagents but hitting context limits, or if your subagents need to communicate with each other, agent teams are the natural next step.

122 

123 <Note>

124 Agent teams are experimental and disabled by default. See [agent teams](/en/agent-teams) for setup and current limitations.

125 </Note>

79 </Tab>126 </Tab>

80 127 

81 <Tab title="MCP vs Skill">128 <Tab title="MCP vs Skill">


101 148 

102Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here's how they layer:149Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here's how they layer:

103 150 

104* **CLAUDE.md files** are additive: all levels contribute content to Claude's context simultaneously. Files from your working directory and above load at launch; subdirectories load as you work in them. When instructions conflict, Claude uses judgment to reconcile them, with more specific instructions typically taking precedence. See [how Claude looks up memories](/en/memory#how-claude-looks-up-memories).151* **CLAUDE.md files** are additive: all levels contribute content to Claude's context simultaneously. Files from your working directory and above load at launch; subdirectories load as you work in them. When instructions conflict, Claude uses judgment to reconcile them, with more specific instructions typically taking precedence. See [how CLAUDE.md files load](/en/memory#how-claudemd-files-load).

105* **Skills and subagents** override by name: when the same name exists at multiple levels, one definition wins based on priority (managed > user > project for skills; managed > CLI flag > project > user > plugin for subagents). Plugin skills are [namespaced](/en/plugins#add-skills-to-your-plugin) to avoid conflicts. See [skill discovery](/en/skills#where-skills-live) and [subagent scope](/en/sub-agents#choose-the-subagent-scope).152* **Skills and subagents** override by name: when the same name exists at multiple levels, one definition wins based on priority (managed > user > project for skills; managed > CLI flag > project > user > plugin for subagents). Plugin skills are [namespaced](/en/plugins#add-skills-to-your-plugin) to avoid conflicts. See [skill discovery](/en/skills#where-skills-live) and [subagent scope](/en/sub-agents#choose-the-subagent-scope).

106* **MCP servers** override by name: local > project > user. See [MCP scope](/en/mcp#scope-hierarchy-and-precedence).153* **MCP servers** override by name: local > project > user. See [MCP scope](/en/mcp#scope-hierarchy-and-precedence).

107* **Hooks** merge: all registered hooks fire for their matching events regardless of source. See [hooks](/en/hooks).154* **Hooks** merge: all registered hooks fire for their matching events regardless of source. See [hooks](/en/hooks).


113For example, you might use CLAUDE.md for project conventions, a skill for your deployment workflow, MCP to connect to your database, and a hook to run linting after every edit. Each feature handles what it's best at.160For example, you might use CLAUDE.md for project conventions, a skill for your deployment workflow, MCP to connect to your database, and a hook to run linting after every edit. Each feature handles what it's best at.

114 161 

115| Pattern | How it works | Example |162| Pattern | How it works | Example |

116| ---------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |163| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |

117| **Skill + MCP** | MCP provides the connection; a skill teaches Claude how to use it well | MCP connects to your database, a skill documents your schema and query patterns |164| **Skill + MCP** | MCP provides the connection; a skill teaches Claude how to use it well | MCP connects to your database, a skill documents your schema and query patterns |

118| **Skill + Subagent** | A skill spawns subagents for parallel work | `/review` skill kicks off security, performance, and style subagents that work in isolated context |165| **Skill + Subagent** | A skill spawns subagents for parallel work | `/audit` skill kicks off security, performance, and style subagents that work in isolated context |

119| **CLAUDE.md + Skills** | CLAUDE.md holds always-on rules; skills hold reference material loaded on demand | CLAUDE.md says "follow our API conventions," a skill contains the full API style guide |166| **CLAUDE.md + Skills** | CLAUDE.md holds always-on rules; skills hold reference material loaded on demand | CLAUDE.md says "follow our API conventions," a skill contains the full API style guide |

120| **Hook + MCP** | A hook triggers external actions through MCP | Post-edit hook sends a Slack notification when Claude modifies critical files |167| **Hook + MCP** | A hook triggers external actions through MCP | Post-edit hook sends a Slack notification when Claude modifies critical files |

121 168 


141 188 

142Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context.189Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context.

143 190 

144<img src="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=bd2e24b8e6a99b31ecfffb63f5b23bf5" alt="Context loading: CLAUDE.md and MCP load at session start and stay in every request. Skills load descriptions at start, full content on invocation. Subagents get isolated context. Hooks run externally." data-og-width="720" width="720" data-og-height="410" height="410" data-path="images/context-loading.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=280&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=aebaadd1f484f285dd9cb4e0ea6d49b9 280w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=560&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=030c9b46126d750de315612560082727 560w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=840&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=6c73f8b0389da4f3190843140c810fe9 840w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=1100&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=9844c55d08d2c386672447f2e8518669 1100w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=1650&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=21a9522d0e4bd10ced146aab850ede76 1650w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=2500&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=d318525915aee1a1a6a4215cfaa61fb9 2500w" />191<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/context-loading.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=729b5b634ba831d1d64772c6c9485b30" alt="Context loading: CLAUDE.md and MCP load at session start and stay in every request. Skills load descriptions at start, full content on invocation. Subagents get isolated context. Hooks run externally." width="720" height="410" data-path="images/context-loading.svg" />

145 192 

146<Tabs>193<Tabs>

147 <Tab title="CLAUDE.md">194 <Tab title="CLAUDE.md">


149 196 

150 **What loads:** Full content of all CLAUDE.md files (managed, user, and project levels).197 **What loads:** Full content of all CLAUDE.md files (managed, user, and project levels).

151 198 

152 **Inheritance:** Claude reads CLAUDE.md files from your working directory up to the root, and discovers nested ones in subdirectories as it accesses those files. See [How Claude looks up memories](/en/memory#how-claude-looks-up-memories) for details.199 **Inheritance:** Claude reads CLAUDE.md files from your working directory up to the root, and discovers nested ones in subdirectories as it accesses those files. See [How CLAUDE.md files load](/en/memory#how-claudemd-files-load) for details.

153 200 

154 <Tip>Keep CLAUDE.md under \~500 lines. Move reference material to skills, which load on-demand.</Tip>201 <Tip>Keep CLAUDE.md under \~500 lines. Move reference material to skills, which load on-demand.</Tip>

155 </Tab>202 </Tab>

156 203 

157 <Tab title="Skills">204 <Tab title="Skills">

158 Skills are extra capabilities in Claude's toolkit. They can be reference material (like an API style guide) or invocable workflows you trigger with `/<name>` (like `/deploy`). Some are built-in; you can also create your own. Claude uses skills when appropriate, or you can invoke one directly.205 Skills are extra capabilities in Claude's toolkit. They can be reference material (like an API style guide) or invocable workflows you trigger with `/<name>` (like `/deploy`). Claude Code ships with [bundled skills](/en/skills#bundled-skills) like `/simplify`, `/batch`, and `/debug` that work out of the box. You can also create your own. Claude uses skills when appropriate, or you can invoke one directly.

159 206 

160 **When:** Depends on the skill's configuration. By default, descriptions load at session start and full content loads when used. For user-only skills (`disable-model-invocation: true`), nothing loads until you invoke them.207 **When:** Depends on the skill's configuration. By default, descriptions load at session start and full content loads when used. For user-only skills (`disable-model-invocation: true`), nothing loads until you invoke them.

161 208 


198 </Tab>245 </Tab>

199 246 

200 <Tab title="Hooks">247 <Tab title="Hooks">

201 **When:** On trigger. Hooks can run before or after tool executions, at session start, before compaction, and at other lifecycle events. See [Hooks](/en/hooks) for the full list.248 **When:** On trigger. Hooks fire at specific lifecycle events like tool execution, session boundaries, prompt submission, permission requests, and compaction. See [Hooks](/en/hooks) for the full list.

202 249 

203 **What loads:** Nothing by default. Hooks run as external scripts.250 **What loads:** Nothing by default. Hooks run as external scripts.

204 251 


225 Offload work to isolated context272 Offload work to isolated context

226 </Card>273 </Card>

227 274 

275 <Card title="Agent teams" icon="network" href="/en/agent-teams">

276 Coordinate multiple sessions working in parallel

277 </Card>

278 

228 <Card title="MCP" icon="plug" href="/en/mcp">279 <Card title="MCP" icon="plug" href="/en/mcp">

229 Connect Claude to external services280 Connect Claude to external services

230 </Card>281 </Card>

231 282 

232 <Card title="Hooks" icon="bolt" href="/en/hooks">283 <Card title="Hooks" icon="bolt" href="/en/hooks-guide">

233 Run scripts on Claude Code events284 Automate workflows with hooks

234 </Card>285 </Card>

235 286 

236 <Card title="Plugins" icon="puzzle-piece" href="/en/plugins">287 <Card title="Plugins" icon="puzzle-piece" href="/en/plugins">


241 Host and distribute plugin collections292 Host and distribute plugin collections

242 </Card>293 </Card>

243</CardGroup>294</CardGroup>

244 

245 

246 

247> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

github-actions.md +22 −25

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code GitHub Actions5# Claude Code GitHub Actions

2 6 

3> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions7> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions

4 8 

5Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards.9Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards. For automatic reviews posted on every PR without a trigger, see [GitHub Code Review](/en/code-review).

6 10 

7<Note>11<Note>

8 Claude Code GitHub Actions is built on top of the [Claude Code12 Claude Code GitHub Actions is built on top of the [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions.

9 SDK](https://docs.claude.com/en/docs/agent-sdk), which enables programmatic integration of

10 Claude Code into your applications. You can use the SDK to build custom

11 automation workflows beyond GitHub Actions.

12</Note>13</Note>

13 14 

14<Info>15<Info>

15 **Claude Opus 4.5 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.5, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-5-20251101`.16 **Claude Opus 4.6 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.6, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-6`.

16</Info>17</Info>

17 18 

18## Why use Claude Code GitHub Actions?19## Why use Claude Code GitHub Actions?


90### Breaking Changes Reference91### Breaking Changes Reference

91 92 

92| Old Beta Input | New v1.0 Input |93| Old Beta Input | New v1.0 Input |

93| --------------------- | -------------------------------- |94| --------------------- | ------------------------------------- |

94| `mode` | *(Removed - auto-detected)* |95| `mode` | *(Removed - auto-detected)* |

95| `direct_prompt` | `prompt` |96| `direct_prompt` | `prompt` |

96| `override_prompt` | `prompt` with GitHub variables |97| `override_prompt` | `prompt` with GitHub variables |

97| `custom_instructions` | `claude_args: --system-prompt` |98| `custom_instructions` | `claude_args: --append-system-prompt` |

98| `max_turns` | `claude_args: --max-turns` |99| `max_turns` | `claude_args: --max-turns` |

99| `model` | `claude_args: --model` |100| `model` | `claude_args: --model` |

100| `allowed_tools` | `claude_args: --allowedTools` |101| `allowed_tools` | `claude_args: --allowedTools` |


113 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}114 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

114 custom_instructions: "Follow our coding standards"115 custom_instructions: "Follow our coding standards"

115 max_turns: "10"116 max_turns: "10"

116 model: "claude-sonnet-4-5-20250929"117 model: "claude-sonnet-4-6"

117```118```

118 119 

119**GA version (v1.0):**120**GA version (v1.0):**


124 prompt: "Review this PR for security issues"125 prompt: "Review this PR for security issues"

125 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}126 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

126 claude_args: |127 claude_args: |

127 --system-prompt "Follow our coding standards"128 --append-system-prompt "Follow our coding standards"

128 --max-turns 10129 --max-turns 10

129 --model claude-sonnet-4-5-20250929130 --model claude-sonnet-4-6

130```131```

131 132 

132<Tip>133<Tip>


170 - uses: anthropics/claude-code-action@v1171 - uses: anthropics/claude-code-action@v1

171 with:172 with:

172 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}173 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

173 prompt: "/review"174 prompt: "Review this pull request for code quality, correctness, and security. Analyze the diff, then post your findings as review comments."

174 claude_args: "--max-turns 5"175 claude_args: "--max-turns 5"

175```176```

176 177 


189 with:190 with:

190 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}191 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

191 prompt: "Generate a summary of yesterday's commits and open issues"192 prompt: "Generate a summary of yesterday's commits and open issues"

192 claude_args: "--model claude-opus-4-5-20251101"193 claude_args: "--model opus"

193```194```

194 195 

195### Common use cases196### Common use cases

196 197 

197In issue or PR comments:198In issue or PR comments:

198 199 

199```200```text theme={null}

200@claude implement this feature based on the issue description201@claude implement this feature based on the issue description

201@claude how should I implement user authentication for this endpoint?202@claude how should I implement user authentication for this endpoint?

202@claude fix the TypeError in the user dashboard component203@claude fix the TypeError in the user dashboard component


266Key features:267Key features:

267 268 

268* **Unified prompt interface** - Use `prompt` for all instructions269* **Unified prompt interface** - Use `prompt` for all instructions

269* **Commands** - Prebuilt prompts like `/review` or `/fix`270* **Skills** - Invoke installed [skills](/en/skills) directly from the prompt

270* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`271* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`

271* **Flexible triggers** - Works with any GitHub event272* **Flexible triggers** - Works with any GitHub event

272 273 


517 with:518 with:

518 github_token: ${{ steps.app-token.outputs.token }}519 github_token: ${{ steps.app-token.outputs.token }}

519 use_bedrock: "true"520 use_bedrock: "true"

520 claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0 --max-turns 10'521 claude_args: '--model us.anthropic.claude-sonnet-4-6 --max-turns 10'

521 ```522 ```

522 523 

523 <Tip>524 <Tip>

524 The model ID format for Bedrock includes the region prefix (e.g., `us.anthropic.claude...`) and version suffix.525 The model ID format for Bedrock includes a region prefix (for example, `us.anthropic.claude-sonnet-4-6`).

525 </Tip>526 </Tip>

526 </Accordion>527 </Accordion>

527 528 


624The Claude Code Action v1 uses a simplified configuration:625The Claude Code Action v1 uses a simplified configuration:

625 626 

626| Parameter | Description | Required |627| Parameter | Description | Required |

627| ------------------- | ------------------------------------------------------ | -------- |628| ------------------- | ------------------------------------------------------------------ | -------- |

628| `prompt` | Instructions for Claude (text or skill like `/review`) | No\* |629| `prompt` | Instructions for Claude (plain text or a [skill](/en/skills) name) | No\* |

629| `claude_args` | CLI arguments passed to Claude Code | No |630| `claude_args` | CLI arguments passed to Claude Code | No |

630| `anthropic_api_key` | Claude API key | Yes\*\* |631| `anthropic_api_key` | Claude API key | Yes\*\* |

631| `github_token` | GitHub token for API access | No |632| `github_token` | GitHub token for API access | No |


641The `claude_args` parameter accepts any Claude Code CLI arguments:642The `claude_args` parameter accepts any Claude Code CLI arguments:

642 643 

643```yaml theme={null}644```yaml theme={null}

644claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json"645claude_args: "--max-turns 5 --model claude-sonnet-4-6 --mcp-config /path/to/config.json"

645```646```

646 647 

647Common arguments:648Common arguments:

648 649 

649* `--max-turns`: Maximum conversation turns (default: 10)650* `--max-turns`: Maximum conversation turns (default: 10)

650* `--model`: Model to use (for example, `claude-sonnet-4-5-20250929`)651* `--model`: Model to use (for example, `claude-sonnet-4-6`)

651* `--mcp-config`: Path to MCP configuration652* `--mcp-config`: Path to MCP configuration

652* `--allowed-tools`: Comma-separated list of allowed tools653* `--allowed-tools`: Comma-separated list of allowed tools

653* `--debug`: Enable debug output654* `--debug`: Enable debug output


6702. **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude's behavior for different workflows or tasks.6712. **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude's behavior for different workflows or tasks.

671 672 

672Claude will follow these guidelines when creating PRs and responding to requests.673Claude will follow these guidelines when creating PRs and responding to requests.

673 

674 

675 

676> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

gitlab-ci-cd.md +10 −10

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code GitLab CI/CD5# Claude Code GitLab CI/CD

2 6 

3> Learn about integrating Claude Code into your development workflow with GitLab CI/CD7> Learn about integrating Claude Code into your development workflow with GitLab CI/CD


9</Info>13</Info>

10 14 

11<Note>15<Note>

12 This integration is built on top of the [Claude Code CLI and SDK](https://docs.claude.com/en/docs/agent-sdk), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.16 This integration is built on top of the [Claude Code CLI and Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.

13</Note>17</Note>

14 18 

15## Why use Claude Code with GitLab?19## Why use Claude Code with GitLab?


122 126 

123In an issue comment:127In an issue comment:

124 128 

125```129```text theme={null}

126@claude implement this feature based on the issue description130@claude implement this feature based on the issue description

127```131```

128 132 


132 136 

133In an MR discussion:137In an MR discussion:

134 138 

135```139```text theme={null}

136@claude suggest a concrete approach to cache the results of this API call140@claude suggest a concrete approach to cache the results of this API call

137```141```

138 142 


142 146 

143In an issue or MR comment:147In an issue or MR comment:

144 148 

145```149```text theme={null}

146@claude fix the TypeError in the user dashboard component150@claude fix the TypeError in the user dashboard component

147```151```

148 152 


315```319```

316 320 

317<Note>321<Note>

318 Model IDs for Bedrock include region-specific prefixes and version suffixes (for example, `us.anthropic.claude-sonnet-4-5-20250929-v1:0`). Pass the desired model via your job configuration or prompt if your workflow supports it.322 Model IDs for Bedrock include region-specific prefixes (for example, `us.anthropic.claude-sonnet-4-6`). Pass the desired model via your job configuration or prompt if your workflow supports it.

319</Note>323</Note>

320 324 

321### Google Vertex AI job example (Workload Identity Federation)325### Google Vertex AI job example (Workload Identity Federation)


404* **API costs**:408* **API costs**:

405 * Each Claude interaction consumes tokens based on prompt and response size409 * Each Claude interaction consumes tokens based on prompt and response size

406 * Token usage varies by task complexity and codebase size410 * Token usage varies by task complexity and codebase size

407 * See [Anthropic pricing](https://docs.claude.com/en/docs/about-claude/pricing) for details411 * See [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing) for details

408 412 

409* **Cost optimization tips**:413* **Cost optimization tips**:

410 * Use specific `@claude` commands to reduce unnecessary turns414 * Use specific `@claude` commands to reduce unnecessary turns


460 464 

4611. **CLAUDE.md**: Define coding standards, security requirements, and project conventions. Claude reads this during runs and follows your rules.4651. **CLAUDE.md**: Define coding standards, security requirements, and project conventions. Claude reads this during runs and follows your rules.

4622. **Custom prompts**: Pass task-specific instructions via `prompt`/`prompt_file` in the job. Use different prompts for different jobs (for example, review, implement, refactor).4662. **Custom prompts**: Pass task-specific instructions via `prompt`/`prompt_file` in the job. Use different prompts for different jobs (for example, review, implement, refactor).

463 

464 

465 

466> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code on Google Vertex AI5# Claude Code on Google Vertex AI

2 6 

3> Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting.7> Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting.


8 12 

9* A Google Cloud Platform (GCP) account with billing enabled13* A Google Cloud Platform (GCP) account with billing enabled

10* A GCP project with Vertex AI API enabled14* A GCP project with Vertex AI API enabled

11* Access to desired Claude models (for example, Claude Sonnet 4.5)15* Access to desired Claude models (for example, Claude Sonnet 4.6)

12* Google Cloud SDK (`gcloud`) installed and configured16* Google Cloud SDK (`gcloud`) installed and configured

13* Quota allocated in desired GCP region17* Quota allocated in desired GCP region

14 18 

19<Note>

20 If you are deploying Claude Code to multiple users, [pin your model versions](#5-pin-model-versions) to prevent breakage when Anthropic releases new models.

21</Note>

22 

15## Region Configuration23## Region Configuration

16 24 

17Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.25Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.

18 26 

19<Note>27<Note>

20 Vertex AI may not support the Claude Code default models on all regions. You may need to switch to a [supported region or model](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models).28 Vertex AI may not support the Claude Code default models in all [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models) or on [global endpoints](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models). You may need to switch to a supported region, use a regional endpoint, or specify a supported model.

21</Note>

22 

23<Note>

24 Vertex AI may not support the Claude Code default models on global endpoints. You may need to switch to a regional endpoint or [supported model](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models).

25</Note>29</Note>

26 30 

27## Setup31## Setup


44 48 

451. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)491. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)

462. Search for "Claude" models502. Search for "Claude" models

473. Request access to desired Claude models (for example, Claude Sonnet 4.5)513. Request access to desired Claude models (for example, Claude Sonnet 4.6)

484. Wait for approval (may take 24-48 hours)524. Wait for approval (may take 24-48 hours)

49 53 

50### 3. Configure GCP credentials54### 3. Configure GCP credentials


81export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west185export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1

82```86```

83 87 

84<Note>88[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support. When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials.

85 [Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support.

86</Note>

87 89 

88<Note>90### 5. Pin model versions

89 When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials.91 

90</Note>92<Warning>

93 Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn't enabled in your Vertex AI project, breaking existing users when Anthropic releases updates.

94</Warning>

91 95 

92### 5. Model configuration96Set these environment variables to specific Vertex AI model IDs:

93 97 

94Claude Code uses these default models for Vertex AI:98```bash theme={null}

99export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'

100export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

101export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

102```

103 

104For current and legacy model IDs, see [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables.

105 

106Claude Code uses these default models when no pinning variables are set:

95 107 

96| Model type | Default value |108| Model type | Default value |

97| :--------------- | :--------------------------- |109| :--------------- | :-------------------------- |

98| Primary model | `claude-sonnet-4-5@20250929` |110| Primary model | `claude-sonnet-4-6` |

99| Small/fast model | `claude-haiku-4-5@20251001` |111| Small/fast model | `claude-haiku-4-5@20251001` |

100 112 

101<Note>113To customize models further:

102 For Vertex AI users, Claude Code will not automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `claude-haiku-4-5@20251001`).

103</Note>

104 

105To customize models:

106 114 

107```bash theme={null}115```bash theme={null}

108export ANTHROPIC_MODEL='claude-opus-4-1@20250805'116export ANTHROPIC_MODEL='claude-opus-4-6'

109export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'117export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'

110```118```

111 119 


122For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).130For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).

123 131 

124<Note>132<Note>

125 We recommend creating a dedicated GCP project for Claude Code to simplify cost tracking and access control.133 Create a dedicated GCP project for Claude Code to simplify cost tracking and access control.

126</Note>134</Note>

127 135 

128## 1M token context window136## 1M token context window

129 137 

130Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) on Vertex AI.138Claude Opus 4.6, Sonnet 4.6, Sonnet 4.5, and Sonnet 4 support the [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) on Vertex AI. Claude Code automatically enables the extended context window when you select a 1M model variant.

131 139 

132<Note>140To enable the 1M context window for your pinned model, append `[1m]` to the model ID. See [Pin models for third-party deployments](/en/model-config#pin-models-for-third-party-deployments) for details.

133 The 1M token context window is currently in beta. To use the extended context window, include the `context-1m-2025-08-07` beta header in your Vertex AI requests.

134</Note>

135 141 

136## Troubleshooting142## Troubleshooting

137 143 


157* [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs)163* [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs)

158* [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing)164* [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing)

159* [Vertex AI quotas and limits](https://cloud.google.com/vertex-ai/docs/quotas)165* [Vertex AI quotas and limits](https://cloud.google.com/vertex-ai/docs/quotas)

160 

161 

162 

163> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

headless.md +28 −24

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Run Claude Code programmatically5# Run Claude Code programmatically

2 6 

3> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.7> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.


73 ```77 ```

74</Tip>78</Tip>

75 79 

80### Stream responses

81 

82Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they're generated. Each line is a JSON object representing an event:

83 

84```bash theme={null}

85claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages

86```

87 

88The following example uses [jq](https://jqlang.github.io/jq/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:

89 

90```bash theme={null}

91claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \

92 jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

93```

94 

95For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](https://platform.claude.com/docs/en/agent-sdk/streaming-output) in the Agent SDK documentation.

96 

76### Auto-approve tools97### Auto-approve tools

77 98 

78Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:99Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:


88 109 

89```bash theme={null}110```bash theme={null}

90claude -p "Look at my staged changes and create an appropriate commit" \111claude -p "Look at my staged changes and create an appropriate commit" \

91 --allowedTools "Bash(git diff:*),Bash(git log:*),Bash(git status:*),Bash(git commit:*)"112 --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

92```113```

93 114 

94The `--allowedTools` flag uses [permission rule syntax](/en/settings#permission-rule-syntax). The `:*` suffix enables prefix matching, so `Bash(git diff:*)` allows any command starting with `git diff`.115The `--allowedTools` flag uses [permission rule syntax](/en/settings#permission-rule-syntax). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`.

95 116 

96<Note>117<Note>

97 User-invoked [skills](/en/skills) like `/commit` and [built-in commands](/en/interactive-mode#built-in-commands) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.118 User-invoked [skills](/en/skills) like `/commit` and [built-in commands](/en/commands) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.

98</Note>119</Note>

99 120 

100### Customize the system prompt121### Customize the system prompt


131 152 

132## Next steps153## Next steps

133 154 

134<CardGroup cols={2}>155* [Agent SDK quickstart](https://platform.claude.com/docs/en/agent-sdk/quickstart): build your first agent with Python or TypeScript

135 <Card title="Agent SDK quickstart" icon="play" href="https://platform.claude.com/docs/en/agent-sdk/quickstart">156* [CLI reference](/en/cli-reference): all CLI flags and options

136 Build your first agent with Python or TypeScript157* [GitHub Actions](/en/github-actions): use the Agent SDK in GitHub workflows

137 </Card>158* [GitLab CI/CD](/en/gitlab-ci-cd): use the Agent SDK in GitLab pipelines

138 

139 <Card title="CLI reference" icon="terminal" href="/en/cli-reference">

140 Explore all CLI flags and options

141 </Card>

142 

143 <Card title="GitHub Actions" icon="github" href="/en/github-actions">

144 Use the Agent SDK in GitHub workflows

145 </Card>

146 

147 <Card title="GitLab CI/CD" icon="gitlab" href="/en/gitlab-ci-cd">

148 Use the Agent SDK in GitLab pipelines

149 </Card>

150</CardGroup>

151 

152 

153 

154> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

hooks.md +1569 −890

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Hooks reference5# Hooks reference

2 6 

3> This page provides reference documentation for implementing hooks in Claude Code.7> Reference for Claude Code hook events, configuration schema, JSON input/output formats, exit codes, async hooks, HTTP hooks, prompt hooks, and MCP tool hooks.

4 8 

5<Tip>9<Tip>

6 For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/hooks-guide).10 For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide).

7</Tip>11</Tip>

8 12 

13Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead.

14 

9## Hook lifecycle15## Hook lifecycle

10 16 

11Hooks fire at specific points during a Claude Code session.17Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:

12 18 

13<div style={{maxWidth: "500px", margin: "0 auto"}}>19<div style={{maxWidth: "500px", margin: "0 auto"}}>

14 <Frame>20 <Frame>

15 <img src="https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=5c25fedbc3db6f8882af50c3cc478c32" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop to SessionEnd" data-og-width="8876" width="8876" data-og-height="12492" height="12492" data-path="images/hooks-lifecycle.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=280&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=62406fcd5d4a189cc8842ee1bd946b84 280w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=560&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=fa3049022a6973c5f974e0f95b28169d 560w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=840&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=bd2890897db61a03160b93d4f972ff8e 840w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=1100&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=7ae8e098340479347135e39df4a13454 1100w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=1650&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=848a8606aab22c2ccaa16b6a18431e32 1650w, https://mintcdn.com/claude-code/z2YM37Ycg6eMbID3/images/hooks-lifecycle.png?w=2500&fit=max&auto=format&n=z2YM37Ycg6eMbID3&q=85&s=f3a9ef7feb61fa8fe362005aa185efbc 2500w" />21 <img src="https://mintcdn.com/claude-code/lBsitdsGyD9caWJQ/images/hooks-lifecycle.svg?fit=max&auto=format&n=lBsitdsGyD9caWJQ&q=85&s=be3486ef2cf2563eb213b6cbbce93982" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCompleted) to PostCompact and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, and InstructionsLoaded as standalone async events" width="520" height="1100" data-path="images/hooks-lifecycle.svg" />

16 </Frame>22 </Frame>

17</div>23</div>

18 24 

19| Hook | When it fires |25The table below summarizes when each event fires. The [Hook events](#hook-events) section documents the full input schema and decision control options for each one.

20| :------------------- | :------------------------------ |26 

21| `SessionStart` | Session begins or resumes |27| Event | When it fires |

22| `UserPromptSubmit` | User submits a prompt |28| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |

23| `PreToolUse` | Before tool execution |29| `SessionStart` | When a session begins or resumes |

24| `PermissionRequest` | When permission dialog appears |30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

25| `PostToolUse` | After tool succeeds |31| `PreToolUse` | Before a tool call executes. Can block it |

26| `PostToolUseFailure` | After tool fails |32| `PermissionRequest` | When a permission dialog appears |

27| `SubagentStart` | When spawning a subagent |33| `PostToolUse` | After a tool call succeeds |

28| `SubagentStop` | When subagent finishes |34| `PostToolUseFailure` | After a tool call fails |

29| `Stop` | Claude finishes responding |35| `Notification` | When Claude Code sends a notification |

36| `SubagentStart` | When a subagent is spawned |

37| `SubagentStop` | When a subagent finishes |

38| `Stop` | When Claude finishes responding |

39| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

40| `TaskCompleted` | When a task is being marked as completed |

41| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

42| `ConfigChange` | When a configuration file changes during a session |

43| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

44| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

30| `PreCompact` | Before context compaction |45| `PreCompact` | Before context compaction |

31| `SessionEnd` | Session terminates |46| `PostCompact` | After context compaction completes |

32| `Notification` | Claude Code sends notifications |47| `Elicitation` | When an MCP server requests user input during a tool call |

33 48| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

34## Configuration49| `SessionEnd` | When a session terminates |

35 

36Claude Code hooks are configured in your [settings files](/en/settings):

37 

38* `~/.claude/settings.json` - User settings

39* `.claude/settings.json` - Project settings

40* `.claude/settings.local.json` - Local project settings (not committed)

41* Managed policy settings

42 

43<Note>

44 Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration).

45</Note>

46 50 

47### Structure51### How a hook resolves

48 52 

49Hooks are organized by matchers, where each matcher can have multiple hooks:53To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The hook runs `block-rm.sh` before every Bash tool call:

50 54 

51```json theme={null}55```json theme={null}

52{56{

53 "hooks": {57 "hooks": {

54 "EventName": [58 "PreToolUse": [

55 {59 {

56 "matcher": "ToolPattern",60 "matcher": "Bash",

57 "hooks": [61 "hooks": [

58 {62 {

59 "type": "command",63 "type": "command",

60 "command": "your-command-here"64 "command": ".claude/hooks/block-rm.sh"

61 }65 }

62 ]66 ]

63 }67 }


66}70}

67```71```

68 72 

69* **matcher**: Pattern to match tool names, case-sensitive (only applicable for73The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:

70 `PreToolUse`, `PermissionRequest`, and `PostToolUse`)

71 * Simple strings match exactly: `Write` matches only the Write tool

72 * Supports regex: `Edit|Write` or `Notebook.*`

73 * Use `*` to match all tools. You can also use empty string (`""`) or leave

74 `matcher` blank.

75* **hooks**: Array of hooks to execute when the pattern matches

76 * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation

77 * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable)

78 * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation

79 * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook

80 

81For events like `UserPromptSubmit`, `Stop`, `SubagentStop`, and `Setup`

82that don't use matchers, you can omit the matcher field:

83 74 

84```json theme={null}75```bash theme={null}

85{76#!/bin/bash

86 "hooks": {77# .claude/hooks/block-rm.sh

87 "UserPromptSubmit": [78COMMAND=$(jq -r '.tool_input.command')

88 {79 

89 "hooks": [80if echo "$COMMAND" | grep -q 'rm -rf'; then

90 {81 jq -n '{

91 "type": "command",82 hookSpecificOutput: {

92 "command": "/path/to/prompt-validator.py"83 hookEventName: "PreToolUse",

93 }84 permissionDecision: "deny",

94 ]85 permissionDecisionReason: "Destructive command blocked by hook"

95 }

96 ]

97 }86 }

98}87 }'

88else

89 exit 0 # allow the command

90fi

99```91```

100 92 

101### Project-Specific Hook Scripts93Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:

102 

103You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when

104Claude Code spawns the hook command) to reference scripts stored in your project,

105ensuring they work regardless of Claude's current directory:

106 

107```json theme={null}

108{

109 "hooks": {

110 "PostToolUse": [

111 {

112 "matcher": "Write|Edit",

113 "hooks": [

114 {

115 "type": "command",

116 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"

117 }

118 ]

119 }

120 ]

121 }

122}

123```

124 94 

125### Plugin hooks95<Frame>

96 <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/hook-resolution.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=ad667ee6d86ab2276aa48a4e73e220df" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" width="780" height="290" data-path="images/hook-resolution.svg" />

97</Frame>

126 98 

127[Plugins](/en/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled.99<Steps>

100 <Step title="Event fires">

101 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:

128 102 

129**How plugin hooks work**:103 ```json theme={null}

104 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }

105 ```

106 </Step>

130 107 

131* Plugin hooks are defined in the plugin's `hooks/hooks.json` file or in a file given by a custom path to the `hooks` field.108 <Step title="Matcher checks">

132* When a plugin is enabled, its hooks are merged with user and project hooks109 The matcher `"Bash"` matches the tool name, so `block-rm.sh` runs. If you omit the matcher or use `"*"`, the hook runs on every occurrence of the event. Hooks only skip when a matcher is defined and doesn't match.

133* Multiple hooks from different sources can respond to the same event110 </Step>

134* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files

135 111 

136**Example plugin hook configuration**:112 <Step title="Hook handler runs">

113 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:

137 114 

138```json theme={null}115 ```json theme={null}

139{

140 "description": "Automatic code formatting",

141 "hooks": {

142 "PostToolUse": [

143 {

144 "matcher": "Write|Edit",

145 "hooks": [

146 {116 {

147 "type": "command",117 "hookSpecificOutput": {

148 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",118 "hookEventName": "PreToolUse",

149 "timeout": 30119 "permissionDecision": "deny",

150 }120 "permissionDecisionReason": "Destructive command blocked by hook"

151 ]

152 }121 }

153 ]

154 }122 }

155}123 ```

156```

157 

158<Note>

159 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.

160</Note>

161 

162<Note>

163 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.

164</Note>

165 124 

166**Environment variables for plugins**:125 If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.

126 </Step>

167 127 

168* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory128 <Step title="Claude Code acts on the result">

169* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)129 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.

170* All standard environment variables are available130 </Step>

131</Steps>

171 132 

172See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.133The [Configuration](#configuration) section below documents the full schema, and each [hook event](#hook-events) section documents what input your command receives and what output it can return.

173 

174### Hooks in skills and agents

175 

176In addition to settings files and plugins, hooks can be defined directly in [skills](/en/skills) and [subagents](/en/sub-agents) using frontmatter. These hooks are scoped to the component's lifecycle and only run when that component is active.

177 134 

178**Supported events**: `PreToolUse`, `PostToolUse`, and `Stop`135## Configuration

179 136 

180**Example in a Skill**:137Hooks are defined in JSON settings files. The configuration has three levels of nesting:

181 138 

182```yaml theme={null}1391. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`

183name: secure-operations1402. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"

184description: Perform operations with security checks1413. Define one or more [hook handlers](#hook-handler-fields) to run when matched

185hooks:

186 PreToolUse:

187 - matcher: "Bash"

188 hooks:

189 - type: command

190 command: "./scripts/security-check.sh"

191```

192 142 

193**Example in an agent**:143See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.

194 144 

195```yaml theme={null}145<Note>

196name: code-reviewer146 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, prompt, or agent that runs. "Hook" on its own refers to the general feature.

197description: Review code changes147</Note>

198hooks:

199 PostToolUse:

200 - matcher: "Edit|Write"

201 hooks:

202 - type: command

203 command: "./scripts/run-linter.sh"

204```

205 148 

206Component-scoped hooks follow the same configuration format as settings-based hooks but are automatically cleaned up when the component finishes executing.149### Hook locations

207 150 

208**Additional option for skills:**151Where you define a hook determines its scope:

209 152 

210* `once`: Set to `true` to run the hook only once per session. After the first successful execution, the hook is removed. Note: This option is currently only supported for skills, not for agents.153| Location | Scope | Shareable |

154| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |

155| `~/.claude/settings.json` | All your projects | No, local to your machine |

156| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

157| `.claude/settings.local.json` | Single project | No, gitignored |

158| Managed policy settings | Organization-wide | Yes, admin-controlled |

159| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

160| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |

211 161 

212## Prompt-Based Hooks162For details on settings file resolution, see [settings](/en/settings). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration).

213 163 

214In addition to bash command hooks (`type: "command"`), Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action. Prompt-based hooks are currently only supported for `Stop` and `SubagentStop` hooks, where they enable intelligent, context-aware decisions.164### Matcher patterns

215 165 

216### How prompt-based hooks work166The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:

217 167 

218Instead of executing a bash command, prompt-based hooks:168| Event | What the matcher filters | Example matcher values |

169| :-------------------------------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |

170| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

171| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

172| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

173| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

174| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

175| `PreCompact` | what triggered compaction | `manual`, `auto` |

176| `SubagentStop` | agent type | same values as `SubagentStart` |

177| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

178| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded` | no matcher support | always fires on every occurrence |

219 179 

2201. Send the hook input and your prompt to a fast LLM (Haiku)180The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.

2212. The LLM responds with structured JSON containing a decision

2223. Claude Code processes the decision automatically

223 181 

224### Configuration182This example runs a linting script only when Claude writes or edits a file:

225 183 

226```json theme={null}184```json theme={null}

227{185{

228 "hooks": {186 "hooks": {

229 "Stop": [187 "PostToolUse": [

230 {188 {

189 "matcher": "Edit|Write",

231 "hooks": [190 "hooks": [

232 {191 {

233 "type": "prompt",192 "type": "command",

234 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."193 "command": "/path/to/lint-check.sh"

235 }194 }

236 ]195 ]

237 }196 }


244}199}

245```200```

246 201 

247**Fields:**202`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `InstructionsLoaded` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.

248 

249* `type`: Must be `"prompt"`

250* `prompt`: The prompt text to send to the LLM

251 * Use `$ARGUMENTS` as a placeholder for the hook input JSON

252 * If `$ARGUMENTS` is not present, input JSON is appended to the prompt

253* `timeout`: (Optional) Timeout in seconds (default: 30 seconds)

254 

255### Response schema

256 

257The LLM must respond with JSON containing:

258 203 

259```json theme={null}204#### Match MCP tools

260{

261 "ok": true | false,

262 "reason": "Explanation for the decision"

263}

264```

265 205 

266**Response fields:**206[MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`), so you can match them the same way you match any other tool name.

267 207 

268* `ok`: `true` allows the action, `false` prevents it208MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:

269* `reason`: Required when `ok` is `false`. Explanation shown to Claude

270 209 

271### Supported hook events210* `mcp__memory__create_entities`: Memory server's create entities tool

211* `mcp__filesystem__read_file`: Filesystem server's read file tool

212* `mcp__github__search_repositories`: GitHub server's search tool

272 213 

273Prompt-based hooks work with any hook event, but are most useful for:214Use regex patterns to target specific MCP tools or groups of tools:

274 215 

275* **Stop**: Intelligently decide if Claude should continue working216* `mcp__memory__.*` matches all tools from the `memory` server

276* **SubagentStop**: Evaluate if a subagent has completed its task217* `mcp__.*__write.*` matches any tool containing "write" from any server

277* **UserPromptSubmit**: Validate user prompts with LLM assistance

278* **PreToolUse**: Make context-aware permission decisions

279* **PermissionRequest**: Intelligently allow or deny permission dialogs

280 218 

281### Example: Intelligent Stop hook219This example logs all memory server operations and validates write operations from any MCP server:

282 220 

283```json theme={null}221```json theme={null}

284{222{

285 "hooks": {223 "hooks": {

286 "Stop": [224 "PreToolUse": [

287 {225 {

226 "matcher": "mcp__memory__.*",

288 "hooks": [227 "hooks": [

289 {228 {

290 "type": "prompt",229 "type": "command",

291 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.",230 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

292 "timeout": 30

293 }

294 ]

295 }231 }

296 ]232 ]

297 }233 },

298}

299```

300 

301### Example: SubagentStop with custom logic

302 

303```json theme={null}

304{

305 "hooks": {

306 "SubagentStop": [

307 {234 {

235 "matcher": "mcp__.*__write.*",

308 "hooks": [236 "hooks": [

309 {237 {

310 "type": "prompt",238 "type": "command",

311 "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"explanation\"} to continue."239 "command": "/home/user/scripts/validate-mcp-write.py"

312 }240 }

313 ]241 ]

314 }242 }


317}245}

318```246```

319 247 

320### Comparison with bash command hooks248### Hook handler fields

321 249 

322| Feature | Bash Command Hooks | Prompt-Based Hooks |250Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, LLM prompt, or agent that runs when the matcher matches. There are four types:

323| --------------------- | ----------------------- | ------------------------------ |

324| **Execution** | Runs bash script | Queries LLM |

325| **Decision logic** | You implement in code | LLM evaluates context |

326| **Setup complexity** | Requires script file | Configure prompt |

327| **Context awareness** | Limited to script logic | Natural language understanding |

328| **Performance** | Fast (local execution) | Slower (API call) |

329| **Use case** | Deterministic rules | Context-aware decisions |

330 251 

331### Best practices252* **[Command hooks](#command-hook-fields)** (`type: "command"`): run a shell command. Your script receives the event's [JSON input](#hook-input-and-output) on stdin and communicates results back through exit codes and stdout.

253* **[HTTP hooks](#http-hook-fields)** (`type: "http"`): send the event's JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same [JSON output format](#json-output) as command hooks.

254* **[Prompt hooks](#prompt-and-agent-hook-fields)** (`type: "prompt"`): send a prompt to a Claude model for single-turn evaluation. The model returns a yes/no decision as JSON. See [Prompt-based hooks](#prompt-based-hooks).

255* **[Agent hooks](#prompt-and-agent-hook-fields)** (`type: "agent"`): spawn a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. See [Agent-based hooks](#agent-based-hooks).

332 256 

333* **Be specific in prompts**: Clearly state what you want the LLM to evaluate257#### Common fields

334* **Include decision criteria**: List the factors the LLM should consider

335* **Test your prompts**: Verify the LLM makes correct decisions for your use cases

336* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed

337* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules

338 258 

339See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.259These fields apply to all hook types:

340 260 

341## Hook Events261| Field | Required | Description |

262| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |

263| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |

264| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |

265| `statusMessage` | no | Custom spinner message displayed while the hook runs |

266| `once` | no | If `true`, runs only once per session then is removed. Skills only, not agents. See [Hooks in skills and agents](#hooks-in-skills-and-agents) |

342 267 

343### PreToolUse268#### Command hook fields

344 269 

345Runs after Claude creates tool parameters and before processing the tool call.270In addition to the [common fields](#common-fields), command hooks accept these fields:

346 271 

347**Common matchers:**272| Field | Required | Description |

273| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ |

274| `command` | yes | Shell command to execute |

275| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |

348 276 

349* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents))277#### HTTP hook fields

350* `Bash` - Shell commands

351* `Glob` - File pattern matching

352* `Grep` - Content search

353* `Read` - File reading

354* `Edit` - File editing

355* `Write` - File writing

356* `WebFetch`, `WebSearch` - Web operations

357 278 

358Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.279In addition to the [common fields](#common-fields), HTTP hooks accept these fields:

359 280 

360### PermissionRequest281| Field | Required | Description |

282| :--------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

283| `url` | yes | URL to send the POST request to |

284| `headers` | no | Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved |

285| `allowedEnvVars` | no | List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work |

361 286 

362Runs when the user is shown a permission dialog.287Claude Code sends the hook's [JSON input](#hook-input-and-output) as the POST request body with `Content-Type: application/json`. The response body uses the same [JSON output format](#json-output) as command hooks.

363Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

364 288 

365Recognizes the same matcher values as PreToolUse.289Error handling differs from command hooks: non-2xx responses, connection failures, and timeouts all produce non-blocking errors that allow execution to continue. To block a tool call or deny a permission, return a 2xx response with a JSON body containing `decision: "block"` or a `hookSpecificOutput` with `permissionDecision: "deny"`.

366 290 

367### PostToolUse291This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:

368 292 

369Runs immediately after a tool completes successfully.293```json theme={null}

294{

295 "hooks": {

296 "PreToolUse": [

297 {

298 "matcher": "Bash",

299 "hooks": [

300 {

301 "type": "http",

302 "url": "http://localhost:8080/hooks/pre-tool-use",

303 "timeout": 30,

304 "headers": {

305 "Authorization": "Bearer $MY_TOKEN"

306 },

307 "allowedEnvVars": ["MY_TOKEN"]

308 }

309 ]

310 }

311 ]

312 }

313}

314```

370 315 

371Recognizes the same matcher values as PreToolUse.316#### Prompt and agent hook fields

372 317 

373### Notification318In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:

374 319 

375Runs when Claude Code sends notifications. Supports matchers to filter by notification type.320| Field | Required | Description |

321| :------- | :------- | :------------------------------------------------------------------------------------------ |

322| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

323| `model` | no | Model to use for evaluation. Defaults to a fast model |

376 324 

377**Common matchers:**325All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.

378 326 

379* `permission_prompt` - Permission requests from Claude Code327### Reference scripts by path

380* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time)

381* `auth_success` - Authentication success notifications

382* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation

383 328 

384You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications.329Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:

385 330 

386**Example: Different notifications for different types**331* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.

332* `${CLAUDE_PLUGIN_ROOT}`: the plugin's root directory, for scripts bundled with a [plugin](/en/plugins).

387 333 

388```json theme={null}334<Tabs>

389{335 <Tab title="Project scripts">

336 This example uses `$CLAUDE_PROJECT_DIR` to run a style checker from the project's `.claude/hooks/` directory after any `Write` or `Edit` tool call:

337 

338 ```json theme={null}

339 {

390 "hooks": {340 "hooks": {

391 "Notification": [341 "PostToolUse": [

392 {342 {

393 "matcher": "permission_prompt",343 "matcher": "Write|Edit",

394 "hooks": [344 "hooks": [

395 {345 {

396 "type": "command",346 "type": "command",

397 "command": "/path/to/permission-alert.sh"347 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"

398 }348 }

399 ]349 ]

400 },350 }

351 ]

352 }

353 }

354 ```

355 </Tab>

356 

357 <Tab title="Plugin scripts">

358 Define plugin hooks in `hooks/hooks.json` with an optional top-level `description` field. When a plugin is enabled, its hooks merge with your user and project hooks.

359 

360 This example runs a formatting script bundled with the plugin:

361 

362 ```json theme={null}

401 {363 {

402 "matcher": "idle_prompt",364 "description": "Automatic code formatting",

365 "hooks": {

366 "PostToolUse": [

367 {

368 "matcher": "Write|Edit",

403 "hooks": [369 "hooks": [

404 {370 {

405 "type": "command",371 "type": "command",

406 "command": "/path/to/idle-notification.sh"372 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",

373 "timeout": 30

407 }374 }

408 ]375 ]

409 }376 }

410 ]377 ]

411 }378 }

412}379 }

413```380 ```

414 381 

415### UserPromptSubmit382 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.

383 </Tab>

384</Tabs>

416 385 

417Runs when the user submits a prompt, before Claude processes it. This allows you386### Hooks in skills and agents

418to add additional context based on the prompt/conversation, validate prompts, or

419block certain types of prompts.

420 387 

421### Stop388In addition to settings files and plugins, hooks can be defined directly in [skills](/en/skills) and [subagents](/en/sub-agents) using frontmatter. These hooks are scoped to the component's lifecycle and only run when that component is active.

422 389 

423Runs when the main Claude Code agent has finished responding. Does not run if390All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.

424the stoppage occurred due to a user interrupt.

425 391 

426### SubagentStop392Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.

427 393 

428Runs when a Claude Code subagent (Task tool call) has finished responding.394This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:

429 395 

430### PreCompact396```yaml theme={null}

397---

398name: secure-operations

399description: Perform operations with security checks

400hooks:

401 PreToolUse:

402 - matcher: "Bash"

403 hooks:

404 - type: command

405 command: "./scripts/security-check.sh"

406---

407```

431 408 

432Runs before Claude Code is about to run a compact operation.409Agents use the same format in their YAML frontmatter.

433 410 

434**Matchers:**411### The `/hooks` menu

435 412 

436* `manual` - Invoked from `/compact`413Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook's command, prompt, or URL.

437* `auto` - Invoked from auto-compact (due to full context window)

438 414 

439### Setup415The menu displays all four hook types: `command`, `prompt`, `agent`, and `http`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:

440 416 

441Runs when Claude Code is invoked with repository setup and maintenance flags (`--init`, `--init-only`, or `--maintenance`). Use this hook for operations you don't want on every session—such as installing dependencies, running migrations, or periodic maintenance tasks.417* `User`: from `~/.claude/settings.json`

418* `Project`: from `.claude/settings.json`

419* `Local`: from `.claude/settings.local.json`

420* `Plugin`: from a plugin's `hooks/hooks.json`

421* `Session`: registered in memory for the current session

422* `Built-in`: registered internally by Claude Code

442 423 

443<Note>424Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.

444 Use **Setup** hooks for one-time or occasional operations (dependency installation, migrations, cleanup). Use **SessionStart** hooks for things you want on every session (loading context, setting environment variables). Setup hooks require explicit flags because running them automatically would slow down every session start.

445</Note>

446 425 

447**Matchers:**426### Disable or remove hooks

448 427 

449* `init` - Invoked from `--init` or `--init-only` flags428To remove a hook, delete its entry from the settings JSON file.

450* `maintenance` - Invoked from `--maintenance` flag

451 429 

452Setup hooks have access to the `CLAUDE_ENV_FILE` environment variable for persisting environment variables, similar to SessionStart hooks.430To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration.

453 431 

454### SessionStart432The `disableAllHooks` setting respects the managed settings hierarchy. If an administrator has configured hooks through managed policy settings, `disableAllHooks` set in user, project, or local settings cannot disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks.

455 433 

456Runs when Claude Code starts a new session or resumes an existing session (which434Direct edits to hooks in settings files are normally picked up automatically by the file watcher.

457currently does start a new session under the hood). Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables.

458 435 

459<Note>436## Hook input and output

460 For one-time operations like installing dependencies or running migrations, use [Setup hooks](#setup) instead. SessionStart runs on every session, so keep these hooks fast.

461</Note>

462 437 

463**Matchers:**438Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options.

464 439 

465* `startup` - Invoked from startup440### Common input fields

466* `resume` - Invoked from `--resume`, `--continue`, or `/resume`

467* `clear` - Invoked from `/clear`

468* `compact` - Invoked from auto or manual compact.

469 441 

470#### Persisting environment variables442All hook events receive these fields as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.

471 443 

472SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent bash commands.444| Field | Description |

445| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |

446| `session_id` | Current session identifier |

447| `transcript_path` | Path to conversation JSON |

448| `cwd` | Current working directory when the hook is invoked |

449| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |

450| `hook_event_name` | Name of the event that fired |

473 451 

474**Example: Setting individual environment variables**452When running with `--agent` or inside a subagent, two additional fields are included:

475 453 

476```bash theme={null}454| Field | Description |

477#!/bin/bash455| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

456| `agent_id` | Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls. |

457| `agent_type` | Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent's type takes precedence over the session's `--agent` value. |

478 458 

479if [ -n "$CLAUDE_ENV_FILE" ]; then459For example, a `PreToolUse` hook for a Bash command receives this on stdin:

480 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"

481 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"

482 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"

483fi

484 460 

485exit 0461```json theme={null}

462{

463 "session_id": "abc123",

464 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",

465 "cwd": "/home/user/my-project",

466 "permission_mode": "default",

467 "hook_event_name": "PreToolUse",

468 "tool_name": "Bash",

469 "tool_input": {

470 "command": "npm test"

471 }

472}

486```473```

487 474 

488**Example: Persisting all environment changes from the hook**475The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.

489 476 

490When your setup modifies the environment (for example, `nvm use`), capture and persist all changes by diffing the environment:477### Exit code output

491 478 

492```bash theme={null}479The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.

493#!/bin/bash

494 480 

495ENV_BEFORE=$(export -p | sort)481**Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output). JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.

496 482 

497# Run your setup commands that modify the environment483**Exit 2** means a blocking error. Claude Code ignores stdout and any JSON in it. Instead, stderr text is fed back to Claude as an error message. The effect depends on the event: `PreToolUse` blocks the tool call, `UserPromptSubmit` rejects the prompt, and so on. See [exit code 2 behavior](#exit-code-2-behavior-per-event) for the full list.

498source ~/.nvm/nvm.sh

499nvm use 20

500 484 

501if [ -n "$CLAUDE_ENV_FILE" ]; then485**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.

502 ENV_AFTER=$(export -p | sort)486 

503 comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE"487For example, a hook command script that blocks dangerous Bash commands:

488 

489```bash theme={null}

490#!/bin/bash

491# Reads JSON input from stdin, checks the command

492command=$(jq -r '.tool_input.command' < /dev/stdin)

493 

494if [[ "$command" == rm* ]]; then

495 echo "Blocked: rm commands are not allowed" >&2

496 exit 2 # Blocking error: tool call is prevented

504fi497fi

505 498 

506exit 0499exit 0 # Success: tool call proceeds

507```500```

508 501 

509Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.502#### Exit code 2 behavior per event

503 

504Exit code 2 is the way a hook signals "stop, don't do this." The effect depends on the event, because some events represent actions that can be blocked (like a tool call that hasn't happened yet) and others represent things that already happened or can't be prevented.

505 

506| Hook event | Can block? | What happens on exit 2 |

507| :------------------- | :--------- | :---------------------------------------------------------------------------- |

508| `PreToolUse` | Yes | Blocks the tool call |

509| `PermissionRequest` | Yes | Denies the permission |

510| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |

511| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |

512| `SubagentStop` | Yes | Prevents the subagent from stopping |

513| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |

514| `TaskCompleted` | Yes | Prevents the task from being marked as completed |

515| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |

516| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |

517| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |

518| `Notification` | No | Shows stderr to user only |

519| `SubagentStart` | No | Shows stderr to user only |

520| `SessionStart` | No | Shows stderr to user only |

521| `SessionEnd` | No | Shows stderr to user only |

522| `PreCompact` | No | Shows stderr to user only |

523| `PostCompact` | No | Shows stderr to user only |

524| `Elicitation` | Yes | Denies the elicitation |

525| `ElicitationResult` | Yes | Blocks the response (action becomes decline) |

526| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |

527| `WorktreeRemove` | No | Failures are logged in debug mode only |

528| `InstructionsLoaded` | No | Exit code is ignored |

529 

530### HTTP response handling

531 

532HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:

533 

534* **2xx with an empty body**: success, equivalent to exit code 0 with no output

535* **2xx with a plain text body**: success, the text is added as context

536* **2xx with a JSON body**: success, parsed using the same [JSON output](#json-output) schema as command hooks

537* **Non-2xx status**: non-blocking error, execution continues

538* **Connection failure or timeout**: non-blocking error, execution continues

539 

540Unlike command hooks, HTTP hooks cannot signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.

541 

542### JSON output

543 

544Exit codes let you allow or block, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including [decision control](#decision-control) for blocking, allowing, or escalating to the user.

510 545 

511<Note>546<Note>

512 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.547 You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored.

513</Note>548</Note>

514 549 

515### SessionEnd550Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.

516 

517Runs when a Claude Code session ends. Useful for cleanup tasks, logging session

518statistics, or saving session state.

519 551 

520The `reason` field in the hook input will be one of:552The JSON object supports three kinds of fields:

521 553 

522* `clear` - Session cleared with /clear command554* **Universal fields** like `continue` work across all events. These are listed in the table below.

523* `logout` - User logged out555* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.

524* `prompt_input_exit` - User exited while prompt input was visible556* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.

525* `other` - Other exit reasons

526 557 

527## Hook Input558| Field | Default | Description |

559| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |

560| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |

561| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |

562| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |

563| `systemMessage` | none | Warning message shown to the user |

528 564 

529Hooks receive JSON data via stdin containing session information and565To stop Claude entirely regardless of event type:

530event-specific data:

531 566 

532```typescript theme={null}567```json theme={null}

533{568{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }

534 // Common fields

535 session_id: string

536 transcript_path: string // Path to conversation JSON

537 cwd: string // The current working directory when the hook is invoked

538 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", "dontAsk", or "bypassPermissions"

539 

540 // Event-specific fields

541 hook_event_name: string

542 ...

543}

544```569```

545 570 

546### PreToolUse Input571#### Decision control

547 572 

548The exact schema for `tool_input` depends on the tool. Here are examples for commonly hooked tools.573Not every event supports blocking or controlling behavior through JSON. The events that do each use a different set of fields to express that decision. Use this table as a quick reference before writing a hook:

549 574 

550#### Bash tool575| Events | Decision pattern | Key fields |

576| :------------------------------------------------------------------------------------ | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

577| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |

578| TeammateIdle, TaskCompleted | Exit code or `continue: false` | Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior |

579| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |

580| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |

581| WorktreeCreate | stdout path | Hook prints absolute path to created worktree. Non-zero exit fails creation |

582| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |

583| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |

584| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded | None | No decision control. Used for side effects like logging or cleanup |

551 585 

552The Bash tool is the most commonly hooked tool for command validation:586Here are examples of each pattern in action:

553 587 

554```json theme={null}588<Tabs>

589 <Tab title="Top-level decision">

590 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, and `ConfigChange`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:

591 

592 ```json theme={null}

593 {

594 "decision": "block",

595 "reason": "Test suite must pass before proceeding"

596 }

597 ```

598 </Tab>

599 

600 <Tab title="PreToolUse">

601 Uses `hookSpecificOutput` for richer control: allow, deny, or escalate to the user. You can also modify tool input before it runs or inject additional context for Claude. See [PreToolUse decision control](#pretooluse-decision-control) for the full set of options.

602 

603 ```json theme={null}

604 {

605 "hookSpecificOutput": {

606 "hookEventName": "PreToolUse",

607 "permissionDecision": "deny",

608 "permissionDecisionReason": "Database writes are not allowed"

609 }

610 }

611 ```

612 </Tab>

613 

614 <Tab title="PermissionRequest">

615 Uses `hookSpecificOutput` to allow or deny a permission request on behalf of the user. When allowing, you can also modify the tool's input or apply permission rules so the user isn't prompted again. See [PermissionRequest decision control](#permissionrequest-decision-control) for the full set of options.

616 

617 ```json theme={null}

618 {

619 "hookSpecificOutput": {

620 "hookEventName": "PermissionRequest",

621 "decision": {

622 "behavior": "allow",

623 "updatedInput": {

624 "command": "npm run lint"

625 }

626 }

627 }

628 }

629 ```

630 </Tab>

631</Tabs>

632 

633For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](/en/hooks-guide#what-you-can-automate) in the guide and the [Bash command validator reference implementation](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py).

634 

635## Hook events

636 

637Each event corresponds to a point in Claude Code's lifecycle where hooks can run. The sections below are ordered to match the lifecycle: from session setup through the agentic loop to session end. Each section describes when the event fires, what matchers it supports, the JSON input it receives, and how to control behavior through output.

638 

639### SessionStart

640 

641Runs when Claude Code starts a new session or resumes an existing session. Useful for loading development context like existing issues or recent changes to your codebase, or setting up environment variables. For static context that does not require a script, use [CLAUDE.md](/en/memory) instead.

642 

643SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.

644 

645The matcher value corresponds to how the session was initiated:

646 

647| Matcher | When it fires |

648| :-------- | :------------------------------------- |

649| `startup` | New session |

650| `resume` | `--resume`, `--continue`, or `/resume` |

651| `clear` | `/clear` |

652| `compact` | Auto or manual compaction |

653 

654#### SessionStart input

655 

656In addition to the [common input fields](#common-input-fields), SessionStart hooks receive `source`, `model`, and optionally `agent_type`. The `source` field indicates how the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction. The `model` field contains the model identifier. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name.

657 

658```json theme={null}

555{659{

556 "session_id": "abc123",660 "session_id": "abc123",

557 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",661 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

558 "cwd": "/Users/...",662 "cwd": "/Users/...",

559 "permission_mode": "default",663 "permission_mode": "default",

560 "hook_event_name": "PreToolUse",664 "hook_event_name": "SessionStart",

561 "tool_name": "Bash",665 "source": "startup",

562 "tool_input": {666 "model": "claude-sonnet-4-6"

563 "command": "psql -c 'SELECT * FROM users'",

564 "description": "Query the users table",

565 "timeout": 120000

566 },

567 "tool_use_id": "toolu_01ABC123..."

568}667}

569```668```

570 669 

571| Field | Type | Description |670#### SessionStart decision control

572| :------------------ | :------ | :-------------------------------------------- |671 

573| `command` | string | The shell command to execute |672Any text your hook script prints to stdout is added as context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields:

574| `description` | string | Optional description of what the command does |673 

575| `timeout` | number | Optional timeout in milliseconds |674| Field | Description |

576| `run_in_background` | boolean | Whether to run the command in background |675| :------------------ | :------------------------------------------------------------------------ |

676| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |

677 

678```json theme={null}

679{

680 "hookSpecificOutput": {

681 "hookEventName": "SessionStart",

682 "additionalContext": "My additional context here"

683 }

684}

685```

686 

687#### Persist environment variables

688 

689SessionStart hooks have access to the `CLAUDE_ENV_FILE` environment variable, which provides a file path where you can persist environment variables for subsequent Bash commands.

690 

691To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:

692 

693```bash theme={null}

694#!/bin/bash

695 

696if [ -n "$CLAUDE_ENV_FILE" ]; then

697 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"

698 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"

699 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"

700fi

701 

702exit 0

703```

704 

705To capture all environment changes from setup commands, compare the exported variables before and after:

706 

707```bash theme={null}

708#!/bin/bash

709 

710ENV_BEFORE=$(export -p | sort)

711 

712# Run your setup commands that modify the environment

713source ~/.nvm/nvm.sh

714nvm use 20

715 

716if [ -n "$CLAUDE_ENV_FILE" ]; then

717 ENV_AFTER=$(export -p | sort)

718 comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE"

719fi

720 

721exit 0

722```

723 

724Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.

725 

726<Note>

727 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.

728</Note>

729 

730### InstructionsLoaded

731 

732Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes.

577 733 

578#### Write tool734InstructionsLoaded does not support matchers and fires on every load occurrence.

735 

736#### InstructionsLoaded input

737 

738In addition to the [common input fields](#common-input-fields), InstructionsLoaded hooks receive these fields:

739 

740| Field | Description |

741| :------------------ | :-------------------------------------------------------------------------------------------------------- |

742| `file_path` | Absolute path to the instruction file that was loaded |

743| `memory_type` | Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` |

744| `load_reason` | Why the file was loaded: `"session_start"`, `"nested_traversal"`, `"path_glob_match"`, or `"include"` |

745| `globs` | Path glob patterns from the file's `paths:` frontmatter, if any. Present only for `path_glob_match` loads |

746| `trigger_file_path` | Path to the file whose access triggered this load, for lazy loads |

747| `parent_file_path` | Path to the parent instruction file that included this one, for `include` loads |

579 748 

580```json theme={null}749```json theme={null}

581{750{

582 "session_id": "abc123",751 "session_id": "abc123",

583 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",752 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

584 "cwd": "/Users/...",753 "cwd": "/Users/my-project",

585 "permission_mode": "default",754 "permission_mode": "default",

586 "hook_event_name": "PreToolUse",755 "hook_event_name": "InstructionsLoaded",

587 "tool_name": "Write",756 "file_path": "/Users/my-project/CLAUDE.md",

588 "tool_input": {757 "memory_type": "Project",

589 "file_path": "/path/to/file.txt",758 "load_reason": "session_start"

590 "content": "file content"

591 },

592 "tool_use_id": "toolu_01ABC123..."

593}759}

594```760```

595 761 

596| Field | Type | Description |762#### InstructionsLoaded decision control

597| :---------- | :----- | :--------------------------------- |

598| `file_path` | string | Absolute path to the file to write |

599| `content` | string | Content to write to the file |

600 763 

601#### Edit tool764InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.

765 

766### UserPromptSubmit

767 

768Runs when the user submits a prompt, before Claude processes it. This allows you

769to add additional context based on the prompt/conversation, validate prompts, or

770block certain types of prompts.

771 

772#### UserPromptSubmit input

773 

774In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.

602 775 

603```json theme={null}776```json theme={null}

604{777{


606 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",779 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

607 "cwd": "/Users/...",780 "cwd": "/Users/...",

608 "permission_mode": "default",781 "permission_mode": "default",

609 "hook_event_name": "PreToolUse",782 "hook_event_name": "UserPromptSubmit",

610 "tool_name": "Edit",783 "prompt": "Write a function to calculate the factorial of a number"

611 "tool_input": {784}

612 "file_path": "/path/to/file.txt",785```

613 "old_string": "original text",786 

614 "new_string": "replacement text"787#### UserPromptSubmit decision control

788 

789`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.

790 

791There are two ways to add context to the conversation on exit code 0:

792 

793* **Plain text stdout**: any non-JSON text written to stdout is added as context

794* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context

795 

796Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.

797 

798To block a prompt, return a JSON object with `decision` set to `"block"`:

799 

800| Field | Description |

801| :------------------ | :----------------------------------------------------------------------------------------------------------------- |

802| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |

803| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |

804| `additionalContext` | String added to Claude's context |

805 

806```json theme={null}

807{

808 "decision": "block",

809 "reason": "Explanation for decision",

810 "hookSpecificOutput": {

811 "hookEventName": "UserPromptSubmit",

812 "additionalContext": "My additional context here"

813 }

814}

815```

816 

817<Note>

818 The JSON format isn't required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to

819 block prompts or want more structured control.

820</Note>

821 

822### PreToolUse

823 

824Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).

825 

826Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.

827 

828#### PreToolUse input

829 

830In addition to the [common input fields](#common-input-fields), PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:

831 

832##### Bash

833 

834Executes shell commands.

835 

836| Field | Type | Example | Description |

837| :------------------ | :------ | :----------------- | :-------------------------------------------- |

838| `command` | string | `"npm test"` | The shell command to execute |

839| `description` | string | `"Run test suite"` | Optional description of what the command does |

840| `timeout` | number | `120000` | Optional timeout in milliseconds |

841| `run_in_background` | boolean | `false` | Whether to run the command in background |

842 

843##### Write

844 

845Creates or overwrites a file.

846 

847| Field | Type | Example | Description |

848| :---------- | :----- | :-------------------- | :--------------------------------- |

849| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |

850| `content` | string | `"file content"` | Content to write to the file |

851 

852##### Edit

853 

854Replaces a string in an existing file.

855 

856| Field | Type | Example | Description |

857| :------------ | :------ | :-------------------- | :--------------------------------- |

858| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |

859| `old_string` | string | `"original text"` | Text to find and replace |

860| `new_string` | string | `"replacement text"` | Replacement text |

861| `replace_all` | boolean | `false` | Whether to replace all occurrences |

862 

863##### Read

864 

865Reads file contents.

866 

867| Field | Type | Example | Description |

868| :---------- | :----- | :-------------------- | :----------------------------------------- |

869| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |

870| `offset` | number | `10` | Optional line number to start reading from |

871| `limit` | number | `50` | Optional number of lines to read |

872 

873##### Glob

874 

875Finds files matching a glob pattern.

876 

877| Field | Type | Example | Description |

878| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |

879| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |

880| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |

881 

882##### Grep

883 

884Searches file contents with regular expressions.

885 

886| Field | Type | Example | Description |

887| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |

888| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |

889| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |

890| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |

891| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |

892| `-i` | boolean | `true` | Case insensitive search |

893| `multiline` | boolean | `false` | Enable multiline matching |

894 

895##### WebFetch

896 

897Fetches and processes web content.

898 

899| Field | Type | Example | Description |

900| :------- | :----- | :---------------------------- | :----------------------------------- |

901| `url` | string | `"https://example.com/api"` | URL to fetch content from |

902| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |

903 

904##### WebSearch

905 

906Searches the web.

907 

908| Field | Type | Example | Description |

909| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |

910| `query` | string | `"react hooks best practices"` | Search query |

911| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |

912| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |

913 

914##### Agent

915 

916Spawns a [subagent](/en/sub-agents).

917 

918| Field | Type | Example | Description |

919| :-------------- | :----- | :------------------------- | :------------------------------------------- |

920| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |

921| `description` | string | `"Find API endpoints"` | Short description of the task |

922| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |

923| `model` | string | `"sonnet"` | Optional model alias to override the default |

924 

925#### PreToolUse decision control

926 

927`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: three outcomes (allow, deny, or ask) plus the ability to modify tool input before execution.

928 

929| Field | Description |

930| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |

931| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |

932| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |

933| `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user |

934| `additionalContext` | String added to Claude's context before the tool executes |

935 

936When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.

937 

938```json theme={null}

939{

940 "hookSpecificOutput": {

941 "hookEventName": "PreToolUse",

942 "permissionDecision": "allow",

943 "permissionDecisionReason": "My reason here",

944 "updatedInput": {

945 "field_to_modify": "new value"

615 },946 },

616 "tool_use_id": "toolu_01ABC123..."947 "additionalContext": "Current environment: production. Proceed with caution."

948 }

617}949}

618```950```

619 951 

620| Field | Type | Description |952<Note>

621| :------------ | :------ | :-------------------------------------------------- |953 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.

622| `file_path` | string | Absolute path to the file to edit |954</Note>

623| `old_string` | string | Text to find and replace |955 

624| `new_string` | string | Replacement text |956### PermissionRequest

625| `replace_all` | boolean | Whether to replace all occurrences (default: false) |957 

958Runs when the user is shown a permission dialog.

959Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

960 

961Matches on tool name, same values as PreToolUse.

962 

963#### PermissionRequest input

626 964 

627#### Read tool965PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog. The difference is when the hook fires: PermissionRequest hooks run when a permission dialog is about to be shown to the user, while PreToolUse hooks run before tool execution regardless of permission status.

628 966 

629```json theme={null}967```json theme={null}

630{968{


632 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",970 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

633 "cwd": "/Users/...",971 "cwd": "/Users/...",

634 "permission_mode": "default",972 "permission_mode": "default",

635 "hook_event_name": "PreToolUse",973 "hook_event_name": "PermissionRequest",

636 "tool_name": "Read",974 "tool_name": "Bash",

637 "tool_input": {975 "tool_input": {

638 "file_path": "/path/to/file.txt"976 "command": "rm -rf node_modules",

977 "description": "Remove node_modules directory"

639 },978 },

640 "tool_use_id": "toolu_01ABC123..."979 "permission_suggestions": [

980 {

981 "type": "addRules",

982 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],

983 "behavior": "allow",

984 "destination": "localSettings"

985 }

986 ]

987}

988```

989 

990#### PermissionRequest decision control

991 

992`PermissionRequest` hooks can allow or deny permission requests. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return a `decision` object with these event-specific fields:

993 

994| Field | Description |

995| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

996| `behavior` | `"allow"` grants the permission, `"deny"` denies it |

997| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |

998| `updatedPermissions` | For `"allow"` only: array of [permission update entries](#permission-update-entries) to apply, such as adding an allow rule or changing the session permission mode |

999| `message` | For `"deny"` only: tells Claude why the permission was denied |

1000| `interrupt` | For `"deny"` only: if `true`, stops Claude |

1001 

1002```json theme={null}

1003{

1004 "hookSpecificOutput": {

1005 "hookEventName": "PermissionRequest",

1006 "decision": {

1007 "behavior": "allow",

1008 "updatedInput": {

1009 "command": "npm run lint"

1010 }

1011 }

1012 }

641}1013}

642```1014```

643 1015 

644| Field | Type | Description |1016#### Permission update entries

645| :---------- | :----- | :----------------------------------------- |1017 

646| `file_path` | string | Absolute path to the file to read |1018The `updatedPermissions` output field and the [`permission_suggestions` input field](#permissionrequest-input) both use the same array of entry objects. Each entry has a `type` that determines its other fields, and a `destination` that controls where the change is written.

647| `offset` | number | Optional line number to start reading from |1019 

648| `limit` | number | Optional number of lines to read |1020| `type` | Fields | Effect |

1021| :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1022| `addRules` | `rules`, `behavior`, `destination` | Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"` |

1023| `replaceRules` | `rules`, `behavior`, `destination` | Replaces all rules of the given `behavior` at the `destination` with the provided `rules` |

1024| `removeRules` | `rules`, `behavior`, `destination` | Removes matching rules of the given `behavior` |

1025| `setMode` | `mode`, `destination` | Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan` |

1026| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |

1027| `removeDirectories` | `directories`, `destination` | Removes working directories |

1028 

1029The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.

649 1030 

650### PostToolUse Input1031| `destination` | Writes to |

1032| :---------------- | :---------------------------------------------- |

1033| `session` | in-memory only, discarded when the session ends |

1034| `localSettings` | `.claude/settings.local.json` |

1035| `projectSettings` | `.claude/settings.json` |

1036| `userSettings` | `~/.claude/settings.json` |

651 1037 

652The exact schema for `tool_input` and `tool_response` depends on the tool.1038A hook can echo one of the `permission_suggestions` it received as its own `updatedPermissions` output, which is equivalent to the user selecting that "always allow" option in the dialog.

1039 

1040### PostToolUse

1041 

1042Runs immediately after a tool completes successfully.

1043 

1044Matches on tool name, same values as PreToolUse.

1045 

1046#### PostToolUse input

1047 

1048`PostToolUse` hooks fire after a tool has already executed successfully. The input includes both `tool_input`, the arguments sent to the tool, and `tool_response`, the result it returned. The exact schema for both depends on the tool.

653 1049 

654```json theme={null}1050```json theme={null}

655{1051{


671}1067}

672```1068```

673 1069 

674### Notification Input1070#### PostToolUse decision control

1071 

1072`PostToolUse` hooks can provide feedback to Claude after tool execution. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:

1073 

1074| Field | Description |

1075| :--------------------- | :----------------------------------------------------------------------------------------- |

1076| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |

1077| `reason` | Explanation shown to Claude when `decision` is `"block"` |

1078| `additionalContext` | Additional context for Claude to consider |

1079| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |

1080 

1081```json theme={null}

1082{

1083 "decision": "block",

1084 "reason": "Explanation for decision",

1085 "hookSpecificOutput": {

1086 "hookEventName": "PostToolUse",

1087 "additionalContext": "Additional information for Claude"

1088 }

1089}

1090```

1091 

1092### PostToolUseFailure

1093 

1094Runs when a tool execution fails. This event fires for tool calls that throw errors or return failure results. Use this to log failures, send alerts, or provide corrective feedback to Claude.

1095 

1096Matches on tool name, same values as PreToolUse.

1097 

1098#### PostToolUseFailure input

1099 

1100PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:

1101 

1102```json theme={null}

1103{

1104 "session_id": "abc123",

1105 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1106 "cwd": "/Users/...",

1107 "permission_mode": "default",

1108 "hook_event_name": "PostToolUseFailure",

1109 "tool_name": "Bash",

1110 "tool_input": {

1111 "command": "npm test",

1112 "description": "Run test suite"

1113 },

1114 "tool_use_id": "toolu_01ABC123...",

1115 "error": "Command exited with non-zero status code 1",

1116 "is_interrupt": false

1117}

1118```

1119 

1120| Field | Description |

1121| :------------- | :------------------------------------------------------------------------------ |

1122| `error` | String describing what went wrong |

1123| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |

1124 

1125#### PostToolUseFailure decision control

1126 

1127`PostToolUseFailure` hooks can provide context to Claude after a tool failure. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:

1128 

1129| Field | Description |

1130| :------------------ | :------------------------------------------------------------ |

1131| `additionalContext` | Additional context for Claude to consider alongside the error |

1132 

1133```json theme={null}

1134{

1135 "hookSpecificOutput": {

1136 "hookEventName": "PostToolUseFailure",

1137 "additionalContext": "Additional information about the failure for Claude"

1138 }

1139}

1140```

1141 

1142### Notification

1143 

1144Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`. Omit the matcher to run hooks for all notification types.

1145 

1146Use separate matchers to run different handlers depending on the notification type. This configuration triggers a permission-specific alert script when Claude needs permission approval and a different notification when Claude has been idle:

1147 

1148```json theme={null}

1149{

1150 "hooks": {

1151 "Notification": [

1152 {

1153 "matcher": "permission_prompt",

1154 "hooks": [

1155 {

1156 "type": "command",

1157 "command": "/path/to/permission-alert.sh"

1158 }

1159 ]

1160 },

1161 {

1162 "matcher": "idle_prompt",

1163 "hooks": [

1164 {

1165 "type": "command",

1166 "command": "/path/to/idle-notification.sh"

1167 }

1168 ]

1169 }

1170 ]

1171 }

1172}

1173```

1174 

1175#### Notification input

1176 

1177In addition to the [common input fields](#common-input-fields), Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.

675 1178 

676```json theme={null}1179```json theme={null}

677{1180{


681 "permission_mode": "default",1184 "permission_mode": "default",

682 "hook_event_name": "Notification",1185 "hook_event_name": "Notification",

683 "message": "Claude needs your permission to use Bash",1186 "message": "Claude needs your permission to use Bash",

1187 "title": "Permission needed",

684 "notification_type": "permission_prompt"1188 "notification_type": "permission_prompt"

685}1189}

686```1190```

687 1191 

688### UserPromptSubmit Input1192Notification hooks cannot block or modify notifications. In addition to the [JSON output fields](#json-output) available to all hooks, you can return `additionalContext` to add context to the conversation:

1193 

1194| Field | Description |

1195| :------------------ | :------------------------------- |

1196| `additionalContext` | String added to Claude's context |

1197 

1198### SubagentStart

1199 

1200Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).

1201 

1202#### SubagentStart input

1203 

1204In addition to the [common input fields](#common-input-fields), SubagentStart hooks receive `agent_id` with the unique identifier for the subagent and `agent_type` with the agent name (built-in agents like `"Bash"`, `"Explore"`, `"Plan"`, or custom agent names).

1205 

1206```json theme={null}

1207{

1208 "session_id": "abc123",

1209 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1210 "cwd": "/Users/...",

1211 "permission_mode": "default",

1212 "hook_event_name": "SubagentStart",

1213 "agent_id": "agent-abc123",

1214 "agent_type": "Explore"

1215}

1216```

1217 

1218SubagentStart hooks cannot block subagent creation, but they can inject context into the subagent. In addition to the [JSON output fields](#json-output) available to all hooks, you can return:

1219 

1220| Field | Description |

1221| :------------------ | :------------------------------------- |

1222| `additionalContext` | String added to the subagent's context |

1223 

1224```json theme={null}

1225{

1226 "hookSpecificOutput": {

1227 "hookEventName": "SubagentStart",

1228 "additionalContext": "Follow security guidelines for this task"

1229 }

1230}

1231```

1232 

1233### SubagentStop

1234 

1235Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.

1236 

1237#### SubagentStop input

1238 

1239In addition to the [common input fields](#common-input-fields), SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, `agent_transcript_path`, and `last_assistant_message`. The `agent_type` field is the value used for matcher filtering. The `transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder. The `last_assistant_message` field contains the text content of the subagent's final response, so hooks can access it without parsing the transcript file.

1240 

1241```json theme={null}

1242{

1243 "session_id": "abc123",

1244 "transcript_path": "~/.claude/projects/.../abc123.jsonl",

1245 "cwd": "/Users/...",

1246 "permission_mode": "default",

1247 "hook_event_name": "SubagentStop",

1248 "stop_hook_active": false,

1249 "agent_id": "def456",

1250 "agent_type": "Explore",

1251 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",

1252 "last_assistant_message": "Analysis complete. Found 3 potential issues..."

1253}

1254```

1255 

1256SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).

1257 

1258### Stop

1259 

1260Runs when the main Claude Code agent has finished responding. Does not run if

1261the stoppage occurred due to a user interrupt.

1262 

1263#### Stop input

1264 

1265In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active` and `last_assistant_message`. The `stop_hook_active` field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to prevent Claude Code from running indefinitely. The `last_assistant_message` field contains the text content of Claude's final response, so hooks can access it without parsing the transcript file.

1266 

1267```json theme={null}

1268{

1269 "session_id": "abc123",

1270 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1271 "cwd": "/Users/...",

1272 "permission_mode": "default",

1273 "hook_event_name": "Stop",

1274 "stop_hook_active": true,

1275 "last_assistant_message": "I've completed the refactoring. Here's a summary..."

1276}

1277```

1278 

1279#### Stop decision control

1280 

1281`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:

1282 

1283| Field | Description |

1284| :--------- | :------------------------------------------------------------------------- |

1285| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |

1286| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |

1287 

1288```json theme={null}

1289{

1290 "decision": "block",

1291 "reason": "Must be provided when Claude is blocked from stopping"

1292}

1293```

1294 

1295### TeammateIdle

1296 

1297Runs when an [agent team](/en/agent-teams) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist.

1298 

1299When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.

1300 

1301#### TeammateIdle input

1302 

1303In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.

1304 

1305```json theme={null}

1306{

1307 "session_id": "abc123",

1308 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1309 "cwd": "/Users/...",

1310 "permission_mode": "default",

1311 "hook_event_name": "TeammateIdle",

1312 "teammate_name": "researcher",

1313 "team_name": "my-project"

1314}

1315```

1316 

1317| Field | Description |

1318| :-------------- | :-------------------------------------------- |

1319| `teammate_name` | Name of the teammate that is about to go idle |

1320| `team_name` | Name of the team |

1321 

1322#### TeammateIdle decision control

1323 

1324TeammateIdle hooks support two ways to control teammate behavior:

1325 

1326* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.

1327* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.

1328 

1329This example checks that a build artifact exists before allowing a teammate to go idle:

1330 

1331```bash theme={null}

1332#!/bin/bash

1333 

1334if [ ! -f "./dist/output.js" ]; then

1335 echo "Build artifact missing. Run the build before stopping." >&2

1336 exit 2

1337fi

1338 

1339exit 0

1340```

1341 

1342### TaskCompleted

1343 

1344Runs when a task is being marked as completed. This fires in two situations: when any agent explicitly marks a task as completed through the TaskUpdate tool, or when an [agent team](/en/agent-teams) teammate finishes its turn with in-progress tasks. Use this to enforce completion criteria like passing tests or lint checks before a task can close.

1345 

1346When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks do not support matchers and fire on every occurrence.

1347 

1348#### TaskCompleted input

1349 

1350In addition to the [common input fields](#common-input-fields), TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.

1351 

1352```json theme={null}

1353{

1354 "session_id": "abc123",

1355 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1356 "cwd": "/Users/...",

1357 "permission_mode": "default",

1358 "hook_event_name": "TaskCompleted",

1359 "task_id": "task-001",

1360 "task_subject": "Implement user authentication",

1361 "task_description": "Add login and signup endpoints",

1362 "teammate_name": "implementer",

1363 "team_name": "my-project"

1364}

1365```

1366 

1367| Field | Description |

1368| :----------------- | :------------------------------------------------------ |

1369| `task_id` | Identifier of the task being completed |

1370| `task_subject` | Title of the task |

1371| `task_description` | Detailed description of the task. May be absent |

1372| `teammate_name` | Name of the teammate completing the task. May be absent |

1373| `team_name` | Name of the team. May be absent |

1374 

1375#### TaskCompleted decision control

1376 

1377TaskCompleted hooks support two ways to control task completion:

1378 

1379* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.

1380* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.

1381 

1382This example runs tests and blocks task completion if they fail:

1383 

1384```bash theme={null}

1385#!/bin/bash

1386INPUT=$(cat)

1387TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

1388 

1389# Run the test suite

1390if ! npm test 2>&1; then

1391 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2

1392 exit 2

1393fi

1394 

1395exit 0

1396```

1397 

1398### ConfigChange

1399 

1400Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.

1401 

1402ConfigChange hooks fire for changes to settings files, managed policy settings, and skill files. The `source` field in the input tells you which type of configuration changed, and the optional `file_path` field provides the path to the changed file.

1403 

1404The matcher filters on the configuration source:

1405 

1406| Matcher | When it fires |

1407| :----------------- | :---------------------------------------- |

1408| `user_settings` | `~/.claude/settings.json` changes |

1409| `project_settings` | `.claude/settings.json` changes |

1410| `local_settings` | `.claude/settings.local.json` changes |

1411| `policy_settings` | Managed policy settings change |

1412| `skills` | A skill file in `.claude/skills/` changes |

1413 

1414This example logs all configuration changes for security auditing:

1415 

1416```json theme={null}

1417{

1418 "hooks": {

1419 "ConfigChange": [

1420 {

1421 "hooks": [

1422 {

1423 "type": "command",

1424 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"

1425 }

1426 ]

1427 }

1428 ]

1429 }

1430}

1431```

1432 

1433#### ConfigChange input

1434 

1435In addition to the [common input fields](#common-input-fields), ConfigChange hooks receive `source` and optionally `file_path`. The `source` field indicates which configuration type changed, and `file_path` provides the path to the specific file that was modified.

1436 

1437```json theme={null}

1438{

1439 "session_id": "abc123",

1440 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1441 "cwd": "/Users/...",

1442 "permission_mode": "default",

1443 "hook_event_name": "ConfigChange",

1444 "source": "project_settings",

1445 "file_path": "/Users/.../my-project/.claude/settings.json"

1446}

1447```

1448 

1449#### ConfigChange decision control

1450 

1451ConfigChange hooks can block configuration changes from taking effect. Use exit code 2 or a JSON `decision` to prevent the change. When blocked, the new settings are not applied to the running session.

1452 

1453| Field | Description |

1454| :--------- | :--------------------------------------------------------------------------------------- |

1455| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |

1456| `reason` | Explanation shown to the user when `decision` is `"block"` |

1457 

1458```json theme={null}

1459{

1460 "decision": "block",

1461 "reason": "Configuration changes to project settings require admin approval"

1462}

1463```

1464 

1465`policy_settings` changes cannot be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.

1466 

1467### WorktreeCreate

1468 

1469When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](/en/sub-agents#choose-the-subagent-scope), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial.

1470 

1471The hook must print the absolute path to the created worktree directory on stdout. Claude Code uses this path as the working directory for the isolated session.

1472 

1473This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:

1474 

1475```json theme={null}

1476{

1477 "hooks": {

1478 "WorktreeCreate": [

1479 {

1480 "hooks": [

1481 {

1482 "type": "command",

1483 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"

1484 }

1485 ]

1486 }

1487 ]

1488 }

1489}

1490```

1491 

1492The hook reads the worktree `name` from the JSON input on stdin, checks out a fresh copy into a new directory, and prints the directory path. The `echo` on the last line is what Claude Code reads as the worktree path. Redirect any other output to stderr so it doesn't interfere with the path.

1493 

1494#### WorktreeCreate input

1495 

1496In addition to the [common input fields](#common-input-fields), WorktreeCreate hooks receive the `name` field. This is a slug identifier for the new worktree, either specified by the user or auto-generated (for example, `bold-oak-a3f2`).

689 1497 

690```json theme={null}1498```json theme={null}

691{1499{

692 "session_id": "abc123",1500 "session_id": "abc123",

693 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1501 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

694 "cwd": "/Users/...",1502 "cwd": "/Users/...",

695 "permission_mode": "default",1503 "hook_event_name": "WorktreeCreate",

696 "hook_event_name": "UserPromptSubmit",1504 "name": "feature-auth"

697 "prompt": "Write a function to calculate the factorial of a number"

698}1505}

699```1506```

700 1507 

701### Stop Input1508#### WorktreeCreate output

1509 

1510The hook must print the absolute path to the created worktree directory on stdout. If the hook fails or produces no output, worktree creation fails with an error.

1511 

1512WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. Only `type: "command"` hooks are supported.

702 1513 

703`stop_hook_active` is true when Claude Code is already continuing as a result of1514### WorktreeRemove

704a stop hook. Check this value or process the transcript to prevent Claude Code1515 

705from running indefinitely.1516The cleanup counterpart to [WorktreeCreate](#worktreecreate). This hook fires when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. For git-based worktrees, Claude handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk.

1517 

1518Claude Code passes the path that WorktreeCreate printed on stdout as `worktree_path` in the hook input. This example reads that path and removes the directory:

706 1519 

707```json theme={null}1520```json theme={null}

708{1521{

709 "session_id": "abc123",1522 "hooks": {

710 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1523 "WorktreeRemove": [

711 "cwd": "/Users/...",1524 {

712 "permission_mode": "default",1525 "hooks": [

713 "hook_event_name": "Stop",1526 {

714 "stop_hook_active": true1527 "type": "command",

1528 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"

1529 }

1530 ]

1531 }

1532 ]

1533 }

715}1534}

716```1535```

717 1536 

718### SubagentStop Input1537#### WorktreeRemove input

719 1538 

720Triggered when a subagent finishes. The `transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder.1539In addition to the [common input fields](#common-input-fields), WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed.

721 1540 

722```json theme={null}1541```json theme={null}

723{1542{

724 "session_id": "abc123",1543 "session_id": "abc123",

725 "transcript_path": "~/.claude/projects/.../abc123.jsonl",1544 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

726 "cwd": "/Users/...",1545 "cwd": "/Users/...",

727 "permission_mode": "default",1546 "hook_event_name": "WorktreeRemove",

728 "hook_event_name": "SubagentStop",1547 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"

729 "stop_hook_active": false,

730 "agent_id": "def456",

731 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl"

732}1548}

733```1549```

734 1550 

735### PreCompact Input1551WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only. Only `type: "command"` hooks are supported.

1552 

1553### PreCompact

1554 

1555Runs before Claude Code is about to run a compact operation.

1556 

1557The matcher value indicates whether compaction was triggered manually or automatically:

736 1558 

737For `manual`, `custom_instructions` comes from what the user passes into1559| Matcher | When it fires |

738`/compact`. For `auto`, `custom_instructions` is empty.1560| :------- | :------------------------------------------- |

1561| `manual` | `/compact` |

1562| `auto` | Auto-compact when the context window is full |

1563 

1564#### PreCompact input

1565 

1566In addition to the [common input fields](#common-input-fields), PreCompact hooks receive `trigger` and `custom_instructions`. For `manual`, `custom_instructions` contains what the user passes into `/compact`. For `auto`, `custom_instructions` is empty.

739 1567 

740```json theme={null}1568```json theme={null}

741{1569{

742 "session_id": "abc123",1570 "session_id": "abc123",

743 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1571 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1572 "cwd": "/Users/...",

744 "permission_mode": "default",1573 "permission_mode": "default",

745 "hook_event_name": "PreCompact",1574 "hook_event_name": "PreCompact",

746 "trigger": "manual",1575 "trigger": "manual",


748}1577}

749```1578```

750 1579 

751### Setup Input1580### PostCompact

752 1581 

753```json theme={null}1582Runs after Claude Code completes a compact operation. Use this event to react to the new compacted state, for example to log the generated summary or update external state.

754{1583 

755 "session_id": "abc123",1584The same matcher values apply as for `PreCompact`:

756 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

757 "cwd": "/Users/...",

758 "permission_mode": "default",

759 "hook_event_name": "Setup",

760 "trigger": "init"

761}

762```

763 1585 

764The `trigger` field will be either `"init"` (from `--init` or `--init-only`) or `"maintenance"` (from `--maintenance`).1586| Matcher | When it fires |

1587| :------- | :------------------------------------------------- |

1588| `manual` | After `/compact` |

1589| `auto` | After auto-compact when the context window is full |

765 1590 

766### SessionStart Input1591#### PostCompact input

1592 

1593In addition to the [common input fields](#common-input-fields), PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation.

767 1594 

768```json theme={null}1595```json theme={null}

769{1596{

770 "session_id": "abc123",1597 "session_id": "abc123",

771 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1598 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

772 "cwd": "/Users/...",1599 "cwd": "/Users/...",

773 "permission_mode": "default",1600 "permission_mode": "default",

774 "hook_event_name": "SessionStart",1601 "hook_event_name": "PostCompact",

775 "source": "startup",1602 "trigger": "manual",

776 "model": "claude-sonnet-4-20250514"1603 "compact_summary": "Summary of the compacted conversation..."

777}1604}

778```1605```

779 1606 

780The `source` field indicates how the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction. The `model` field contains the model identifier when available. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name.1607PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.

781 1608 

782### SubagentStart Input1609### SessionEnd

783 1610 

784```json theme={null}1611Runs when a Claude Code session ends. Useful for cleanup tasks, logging session

785{1612statistics, or saving session state. Supports matchers to filter by exit reason.

786 "session_id": "abc123",1613 

787 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1614The `reason` field in the hook input indicates why the session ended:

788 "cwd": "/Users/...",

789 "permission_mode": "default",

790 "hook_event_name": "SubagentStart",

791 "agent_id": "agent-abc123",

792 "agent_type": "Explore"

793}

794```

795 1615 

796Triggered when a subagent is spawned. The `agent_id` field contains the unique identifier for the subagent, and `agent_type` contains the agent name (built-in agents like `"Bash"`, `"Explore"`, `"Plan"`, or custom agent names).1616| Reason | Description |

1617| :---------------------------- | :----------------------------------------- |

1618| `clear` | Session cleared with `/clear` command |

1619| `logout` | User logged out |

1620| `prompt_input_exit` | User exited while prompt input was visible |

1621| `bypass_permissions_disabled` | Bypass permissions mode was disabled |

1622| `other` | Other exit reasons |

797 1623 

798### SessionEnd Input1624#### SessionEnd input

1625 

1626In addition to the [common input fields](#common-input-fields), SessionEnd hooks receive a `reason` field indicating why the session ended. See the [reason table](#sessionend) above for all values.

799 1627 

800```json theme={null}1628```json theme={null}

801{1629{

802 "session_id": "abc123",1630 "session_id": "abc123",

803 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1631 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

804 "cwd": "/Users/...",1632 "cwd": "/Users/...",

805 "permission_mode": "default",1633 "permission_mode": "default",

806 "hook_event_name": "SessionEnd",1634 "hook_event_name": "SessionEnd",

807 "reason": "exit"1635 "reason": "other"

808}1636}

809```1637```

810 1638 

811## Hook Output1639SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.

812 

813There are two mutually exclusive ways for hooks to return output back to Claude Code. The output

814communicates whether to block and any feedback that should be shown to Claude

815and the user.

816 

817### Simple: Exit Code

818 

819Hooks communicate status through exit codes, stdout, and stderr:

820 1640 

821* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode1641SessionEnd hooks have a default timeout of 1.5 seconds. This applies to both session exit and `/clear`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.

822 (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is

823 added to the context. JSON output in `stdout` is parsed for structured control

824 (see [Advanced: JSON Output](#advanced-json-output)).

825* **Exit code 2**: Blocking error. Only `stderr` is used as the error message

826 and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout`

827 is **not** processed for exit code 2. See per-hook-event behavior below.

828* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with

829 format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty,

830 it shows `No stderr output`. Execution continues.

831 1642 

832<Warning>1643```bash theme={null}

833 Reminder: Claude Code does not see stdout if the exit code is 0, except for1644CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude

834 the `UserPromptSubmit` hook where stdout is injected as context.1645```

835</Warning>

836 

837#### Exit Code 2 Behavior

838 1646 

839| Hook Event | Behavior |1647### Elicitation

840| ------------------- | ------------------------------------------------------------------ |

841| `PreToolUse` | Blocks the tool call, shows stderr to Claude |

842| `PermissionRequest` | Denies the permission, shows stderr to Claude |

843| `PostToolUse` | Shows stderr to Claude (tool already ran) |

844| `Notification` | N/A, shows stderr to user only |

845| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |

846| `Stop` | Blocks stoppage, shows stderr to Claude |

847| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |

848| `PreCompact` | N/A, shows stderr to user only |

849| `Setup` | N/A, shows stderr to user only |

850| `SessionStart` | N/A, shows stderr to user only |

851| `SessionEnd` | N/A, shows stderr to user only |

852 1648 

853### Advanced: JSON Output1649Runs when an MCP server requests user input mid-task. By default, Claude Code shows an interactive dialog for the user to respond. Hooks can intercept this request and respond programmatically, skipping the dialog entirely.

854 1650 

855Hooks can return structured JSON in `stdout` for more sophisticated control.1651The matcher field matches against the MCP server name.

856 1652 

857<Warning>1653#### Elicitation input

858 JSON output is only processed when the hook exits with code 0. If your hook

859 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`

860 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).

861</Warning>

862 1654 

863#### Common JSON Fields1655In addition to the [common input fields](#common-input-fields), Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields.

864 1656 

865All hook types can include these optional fields:1657For form-mode elicitation (the most common case):

866 1658 

867```json theme={null}1659```json theme={null}

868{1660{

869 "continue": true, // Whether Claude should continue after hook execution (default: true)1661 "session_id": "abc123",

870 "stopReason": "string", // Message shown when continue is false1662 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

871 1663 "cwd": "/Users/...",

872 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1664 "permission_mode": "default",

873 "systemMessage": "string" // Optional warning message shown to the user1665 "hook_event_name": "Elicitation",

1666 "mcp_server_name": "my-mcp-server",

1667 "message": "Please provide your credentials",

1668 "mode": "form",

1669 "requested_schema": {

1670 "type": "object",

1671 "properties": {

1672 "username": { "type": "string", "title": "Username" }

1673 }

1674 }

874}1675}

875```1676```

876 1677 

877If `continue` is false, Claude stops processing after the hooks run.1678For URL-mode elicitation (browser-based authentication):

878 

879* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which

880 only blocks a specific tool call and provides automatic feedback to Claude.

881* For `PostToolUse`, this is different from `"decision": "block"`, which

882 provides automated feedback to Claude.

883* For `UserPromptSubmit`, this prevents the prompt from being processed.

884* For `Stop` and `SubagentStop`, this takes precedence over any

885 `"decision": "block"` output.

886* In all cases, `"continue" = false` takes precedence over any

887 `"decision": "block"` output.

888 

889`stopReason` accompanies `continue` with a reason shown to the user, not shown

890to Claude.

891 

892#### `PreToolUse` Decision Control

893 

894`PreToolUse` hooks can control whether a tool call proceeds.

895 

896* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown

897 to the user but not to Claude.

898* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is

899 shown to Claude.

900* `"ask"` asks the user to confirm the tool call in the UI.

901 `permissionDecisionReason` is shown to the user but not to Claude.

902 

903Additionally, hooks can modify tool inputs before execution using `updatedInput`:

904 1679 

905* `updatedInput` modifies the tool's input parameters before the tool executes1680```json theme={null}

906* Combine with `"permissionDecision": "allow"` to modify the input and auto-approve the tool call1681{

907* Combine with `"permissionDecision": "ask"` to modify the input and show it to the user for confirmation1682 "session_id": "abc123",

1683 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1684 "cwd": "/Users/...",

1685 "permission_mode": "default",

1686 "hook_event_name": "Elicitation",

1687 "mcp_server_name": "my-mcp-server",

1688 "message": "Please authenticate",

1689 "mode": "url",

1690 "url": "https://auth.example.com/login"

1691}

1692```

908 1693 

909Hooks can also provide context to Claude using `additionalContext`:1694#### Elicitation output

910 1695 

911* `"hookSpecificOutput.additionalContext"` adds a string to Claude's context before the tool executes.1696To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:

912 1697 

913```json theme={null}1698```json theme={null}

914{1699{

915 "hookSpecificOutput": {1700 "hookSpecificOutput": {

916 "hookEventName": "PreToolUse",1701 "hookEventName": "Elicitation",

917 "permissionDecision": "allow",1702 "action": "accept",

918 "permissionDecisionReason": "My reason here",1703 "content": {

919 "updatedInput": {1704 "username": "alice"

920 "field_to_modify": "new value"1705 }

921 },

922 "additionalContext": "Current environment: production. Proceed with caution."

923 }1706 }

924}1707}

925```1708```

926 1709 

927<Note>1710| Field | Values | Description |

928 The `decision` and `reason` fields are deprecated for PreToolUse hooks.1711| :-------- | :---------------------------- | :--------------------------------------------------------------- |

929 Use `hookSpecificOutput.permissionDecision` and1712| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |

930 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields1713| `content` | object | Form field values to submit. Only used when `action` is `accept` |

931 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.1714 

932</Note>1715Exit code 2 denies the elicitation and shows stderr to the user.

1716 

1717### ElicitationResult

933 1718 

934#### `PermissionRequest` Decision Control1719Runs after a user responds to an MCP elicitation. Hooks can observe, modify, or block the response before it is sent back to the MCP server.

935 1720 

936`PermissionRequest` hooks can allow or deny permission requests shown to the user.1721The matcher field matches against the MCP server name.

937 1722 

938* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes.1723#### ElicitationResult input

939* For `"behavior": "deny"` you can also optionally pass in a `"message"` string that tells the model why the permission was denied, and a boolean `"interrupt"` which will stop Claude.1724 

1725In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.

940 1726 

941```json theme={null}1727```json theme={null}

942{1728{

943 "hookSpecificOutput": {1729 "session_id": "abc123",

944 "hookEventName": "PermissionRequest",1730 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

945 "decision": {1731 "cwd": "/Users/...",

946 "behavior": "allow",1732 "permission_mode": "default",

947 "updatedInput": {1733 "hook_event_name": "ElicitationResult",

948 "command": "npm run lint"1734 "mcp_server_name": "my-mcp-server",

949 }1735 "action": "accept",

950 }1736 "content": { "username": "alice" },

951 }1737 "mode": "form",

1738 "elicitation_id": "elicit-123"

952}1739}

953```1740```

954 1741 

955#### `PostToolUse` Decision Control1742#### ElicitationResult output

956 1743 

957`PostToolUse` hooks can provide feedback to Claude after tool execution.1744To override the user's response, return a JSON object with `hookSpecificOutput`:

958 

959* `"block"` automatically prompts Claude with `reason`.

960* `undefined` does nothing. `reason` is ignored.

961* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.

962 1745 

963```json theme={null}1746```json theme={null}

964{1747{

965 "decision": "block" | undefined,

966 "reason": "Explanation for decision",

967 "hookSpecificOutput": {1748 "hookSpecificOutput": {

968 "hookEventName": "PostToolUse",1749 "hookEventName": "ElicitationResult",

969 "additionalContext": "Additional information for Claude"1750 "action": "decline",

1751 "content": {}

970 }1752 }

971}1753}

972```1754```

973 1755 

974#### `UserPromptSubmit` Decision Control1756| Field | Values | Description |

1757| :-------- | :---------------------------- | :--------------------------------------------------------------------- |

1758| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |

1759| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |

975 1760 

976`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1761Exit code 2 blocks the response, changing the effective action to `decline`.

977 1762 

978**Adding context (exit code 0):**1763## Prompt-based hooks

979There are two ways to add context to the conversation:

980 1764 

9811. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1765In addition to command and HTTP hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type.

982 as context. This is the easiest way to inject information.

983 1766 

9842. **JSON with `additionalContext`** (structured): Use the JSON format below for1767Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):

985 more control. The `additionalContext` field is added as context.

986 1768 

987Both methods work with exit code 0. Plain stdout is shown as hook output in1769* `PermissionRequest`

988the transcript; `additionalContext` is added more discretely.1770* `PostToolUse`

1771* `PostToolUseFailure`

1772* `PreToolUse`

1773* `Stop`

1774* `SubagentStop`

1775* `TaskCompleted`

1776* `UserPromptSubmit`

989 1777 

990**Blocking prompts:**1778Events that only support `type: "command"` hooks:

991 1779 

992* `"decision": "block"` prevents the prompt from being processed. The submitted1780* `ConfigChange`

993 prompt is erased from context. `"reason"` is shown to the user but not added1781* `Elicitation`

994 to context.1782* `ElicitationResult`

995* `"decision": undefined` (or omitted) allows the prompt to proceed normally.1783* `InstructionsLoaded`

1784* `Notification`

1785* `PostCompact`

1786* `PreCompact`

1787* `SessionEnd`

1788* `SessionStart`

1789* `SubagentStart`

1790* `TeammateIdle`

1791* `WorktreeCreate`

1792* `WorktreeRemove`

996 1793 

997```json theme={null}1794### How prompt-based hooks work

998{

999 "decision": "block" | undefined,

1000 "reason": "Explanation for decision",

1001 "hookSpecificOutput": {

1002 "hookEventName": "UserPromptSubmit",

1003 "additionalContext": "My additional context here"

1004 }

1005}

1006```

1007 1795 

1008<Note>1796Instead of executing a Bash command, prompt-based hooks:

1009 The JSON format isn't required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to

1010 block prompts or want more structured control.

1011</Note>

1012 1797 

1013#### `Stop`/`SubagentStop` Decision Control17981. Send the hook input and your prompt to a Claude model, Haiku by default

17992. The LLM responds with structured JSON containing a decision

18003. Claude Code processes the decision automatically

1014 1801 

1015`Stop` and `SubagentStop` hooks can control whether Claude must continue.1802### Prompt hook configuration

1016 1803 

1017* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1804Set `type` to `"prompt"` and provide a `prompt` string instead of a `command`. Use the `$ARGUMENTS` placeholder to inject the hook's JSON input data into your prompt text. Claude Code sends the combined prompt and input to a fast Claude model, which returns a JSON decision.

1018 to know how to proceed.1805 

1019* `undefined` allows Claude to stop. `reason` is ignored.1806This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:

1020 1807 

1021```json theme={null}1808```json theme={null}

1022{1809{

1023 "decision": "block" | undefined,1810 "hooks": {

1024 "reason": "Must be provided when Claude is blocked from stopping"1811 "Stop": [

1812 {

1813 "hooks": [

1814 {

1815 "type": "prompt",

1816 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."

1817 }

1818 ]

1819 }

1820 ]

1821 }

1025}1822}

1026```1823```

1027 1824 

1028#### `Setup` Decision Control1825| Field | Required | Description |

1826| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1827| `type` | yes | Must be `"prompt"` |

1828| `prompt` | yes | The prompt text to send to the LLM. Use `$ARGUMENTS` as a placeholder for the hook input JSON. If `$ARGUMENTS` is not present, input JSON is appended to the prompt |

1829| `model` | no | Model to use for evaluation. Defaults to a fast model |

1830| `timeout` | no | Timeout in seconds. Default: 30 |

1029 1831 

1030`Setup` hooks allow you to load context and configure the environment during repository initialization or maintenance.1832### Response schema

1031 1833 

1032* `"hookSpecificOutput.additionalContext"` adds the string to the context.1834The LLM must respond with JSON containing:

1033* Multiple hooks' `additionalContext` values are concatenated.

1034* Setup hooks have access to `CLAUDE_ENV_FILE` for persisting environment variables.

1035 1835 

1036```json theme={null}1836```json theme={null}

1037{1837{

1038 "hookSpecificOutput": {1838 "ok": true | false,

1039 "hookEventName": "Setup",1839 "reason": "Explanation for the decision"

1040 "additionalContext": "Repository initialized with custom configuration"

1041 }

1042}1840}

1043```1841```

1044 1842 

1045#### `SessionStart` Decision Control1843| Field | Description |

1844| :------- | :--------------------------------------------------------- |

1845| `ok` | `true` allows the action, `false` prevents it |

1846| `reason` | Required when `ok` is `false`. Explanation shown to Claude |

1046 1847 

1047`SessionStart` hooks allow you to load in context at the start of a session.1848### Example: Multi-criteria Stop hook

1048 1849 

1049* `"hookSpecificOutput.additionalContext"` adds the string to the context.1850This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction. `SubagentStop` hooks use the same format to evaluate whether a [subagent](/en/sub-agents) should stop:

1050* Multiple hooks' `additionalContext` values are concatenated.

1051 1851 

1052```json theme={null}1852```json theme={null}

1053{1853{

1054 "hookSpecificOutput": {1854 "hooks": {

1055 "hookEventName": "SessionStart",1855 "Stop": [

1056 "additionalContext": "My additional context here"1856 {

1857 "hooks": [

1858 {

1859 "type": "prompt",

1860 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.",

1861 "timeout": 30

1862 }

1863 ]

1864 }

1865 ]

1057 }1866 }

1058}1867}

1059```1868```

1060 1869 

1061#### `SessionEnd` Decision Control1870## Agent-based hooks

1062 

1063`SessionEnd` hooks run when a session ends. They cannot block session termination

1064but can perform cleanup tasks.

1065 

1066#### Exit Code Example: Bash Command Validation

1067 

1068```python theme={null}

1069#!/usr/bin/env python3

1070import json

1071import re

1072import sys

1073 

1074# Define validation rules as a list of (regex pattern, message) tuples

1075VALIDATION_RULES = [

1076 (

1077 r"\bgrep\b(?!.*\|)",

1078 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",

1079 ),

1080 (

1081 r"\bfind\s+\S+\s+-name\b",

1082 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",

1083 ),

1084]

1085 

1086 

1087def validate_command(command: str) -> list[str]:

1088 issues = []

1089 for pattern, message in VALIDATION_RULES:

1090 if re.search(pattern, command):

1091 issues.append(message)

1092 return issues

1093 

1094 

1095try:

1096 input_data = json.load(sys.stdin)

1097except json.JSONDecodeError as e:

1098 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

1099 sys.exit(1)

1100 

1101tool_name = input_data.get("tool_name", "")

1102tool_input = input_data.get("tool_input", {})

1103command = tool_input.get("command", "")

1104 

1105if tool_name != "Bash" or not command:

1106 sys.exit(1)

1107 

1108# Validate the command

1109issues = validate_command(command)

1110 

1111if issues:

1112 for message in issues:

1113 print(f"• {message}", file=sys.stderr)

1114 # Exit code 2 blocks tool call and shows stderr to Claude

1115 sys.exit(2)

1116```

1117 1871 

1118#### JSON Output Example: UserPromptSubmit to Add Context and Validation1872Agent-based hooks (`type: "agent"`) are like prompt-based hooks but with multi-turn tool access. Instead of a single LLM call, an agent hook spawns a subagent that can read files, search code, and inspect the codebase to verify conditions. Agent hooks support the same events as prompt-based hooks.

1119 1873 

1120<Note>1874### How agent hooks work

1121 For `UserPromptSubmit` hooks, you can inject context using either method:

1122 1875 

1123 * **Plain text stdout** with exit code 0: Simplest approach, prints text1876When an agent hook fires:

1124 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,

1125 or `additionalContext` for structured context injection

1126 1877 

1127 Remember: Exit code 2 only uses `stderr` for the error message. To block using18781. Claude Code spawns a subagent with your prompt and the hook's JSON input

1128 JSON (with a custom reason), use `"decision": "block"` with exit code 0.18792. The subagent can use tools like Read, Grep, and Glob to investigate

1129</Note>18803. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision

18814. Claude Code processes the decision the same way as a prompt hook

1130 1882 

1131```python theme={null}1883Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.

1132#!/usr/bin/env python3

1133import json

1134import sys

1135import re

1136import datetime

1137 

1138# Load input from stdin

1139try:

1140 input_data = json.load(sys.stdin)

1141except json.JSONDecodeError as e:

1142 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

1143 sys.exit(1)

1144 

1145prompt = input_data.get("prompt", "")

1146 

1147# Check for sensitive patterns

1148sensitive_patterns = [

1149 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),

1150]

1151 

1152for pattern, message in sensitive_patterns:

1153 if re.search(pattern, prompt):

1154 # Use JSON output to block with a specific reason

1155 output = {

1156 "decision": "block",

1157 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."

1158 }

1159 print(json.dumps(output))

1160 sys.exit(0)

1161 1884 

1162# Add current time to context1885### Agent hook configuration

1163context = f"Current time: {datetime.datetime.now()}"

1164print(context)

1165 1886 

1166"""1887Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as [prompt hooks](#prompt-hook-configuration), with a longer default timeout:

1167The following is also equivalent:

1168print(json.dumps({

1169 "hookSpecificOutput": {

1170 "hookEventName": "UserPromptSubmit",

1171 "additionalContext": context,

1172 },

1173}))

1174"""

1175 1888 

1176# Allow the prompt to proceed with the additional context1889| Field | Required | Description |

1177sys.exit(0)1890| :-------- | :------- | :------------------------------------------------------------------------------------------ |

1178```1891| `type` | yes | Must be `"agent"` |

1892| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

1893| `model` | no | Model to use. Defaults to a fast model |

1894| `timeout` | no | Timeout in seconds. Default: 60 |

1179 1895 

1180#### JSON Output Example: PreToolUse with Approval1896The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.

1181 

1182```python theme={null}

1183#!/usr/bin/env python3

1184import json

1185import sys

1186 

1187# Load input from stdin

1188try:

1189 input_data = json.load(sys.stdin)

1190except json.JSONDecodeError as e:

1191 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

1192 sys.exit(1)

1193 

1194tool_name = input_data.get("tool_name", "")

1195tool_input = input_data.get("tool_input", {})

1196 

1197# Example: Auto-approve file reads for documentation files

1198if tool_name == "Read":

1199 file_path = tool_input.get("file_path", "")

1200 if file_path.endswith((".md", ".mdx", ".txt", ".json")):

1201 # Use JSON output to auto-approve the tool call

1202 output = {

1203 "decision": "approve",

1204 "reason": "Documentation file auto-approved",

1205 "suppressOutput": True # Don't show in verbose mode

1206 }

1207 print(json.dumps(output))

1208 sys.exit(0)

1209 

1210# For other cases, let the normal permission flow proceed

1211sys.exit(0)

1212```

1213 1897 

1214## Working with MCP Tools1898This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:

1215 1899 

1216Claude Code hooks work seamlessly with1900```json theme={null}

1217[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers1901{

1218provide tools, they appear with a special naming pattern that you can match in1902 "hooks": {

1219your hooks.1903 "Stop": [

1904 {

1905 "hooks": [

1906 {

1907 "type": "agent",

1908 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

1909 "timeout": 120

1910 }

1911 ]

1912 }

1913 ]

1914 }

1915}

1916```

1220 1917 

1221### MCP Tool Naming1918## Run hooks in the background

1222 1919 

1223MCP tools follow the pattern `mcp__<server>__<tool>`, for example:1920By default, hooks block Claude's execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks cannot block or control Claude's behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed.

1224 1921 

1225* `mcp__memory__create_entities` - Memory server's create entities tool1922### Configure an async hook

1226* `mcp__filesystem__read_file` - Filesystem server's read file tool

1227* `mcp__github__search_repositories` - GitHub server's search tool

1228 1923 

1229### Configuring Hooks for MCP Tools1924Add `"async": true` to a command hook's configuration to run it in the background without blocking Claude. This field is only available on `type: "command"` hooks.

1230 1925 

1231You can target specific MCP tools or entire MCP servers:1926This hook runs a test script after every `Write` tool call. Claude continues working immediately while `run-tests.sh` executes for up to 120 seconds. When the script finishes, its output is delivered on the next conversation turn:

1232 1927 

1233```json theme={null}1928```json theme={null}

1234{1929{

1235 "hooks": {1930 "hooks": {

1236 "PreToolUse": [1931 "PostToolUse": [

1237 {

1238 "matcher": "mcp__memory__.*",

1239 "hooks": [

1240 {

1241 "type": "command",

1242 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

1243 }

1244 ]

1245 },

1246 {1932 {

1247 "matcher": "mcp__.*__write.*",1933 "matcher": "Write",

1248 "hooks": [1934 "hooks": [

1249 {1935 {

1250 "type": "command",1936 "type": "command",

1251 "command": "/home/user/scripts/validate-mcp-write.py"1937 "command": "/path/to/run-tests.sh",

1938 "async": true,

1939 "timeout": 120

1252 }1940 }

1253 ]1941 ]

1254 }1942 }


1257}1945}

1258```1946```

1259 1947 

1260## Examples1948The `timeout` field sets the maximum time in seconds for the background process. If not specified, async hooks use the same 10-minute default as sync hooks.

1261 

1262<Tip>

1263 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide.

1264</Tip>

1265 1949 

1266## Security Considerations1950### How async hooks execute

1267 1951 

1268### Disclaimer1952When an async hook fires, Claude Code starts the hook process and immediately continues without waiting for it to finish. The hook receives the same JSON input via stdin as a synchronous hook.

1269 1953 

1270**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on1954After the background process exits, if the hook produced a JSON response with a `systemMessage` or `additionalContext` field, that content is delivered to Claude as context on the next conversation turn.

1271your system automatically. By using hooks, you acknowledge that:

1272 1955 

1273* You are solely responsible for the commands you configure1956Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.

1274* Hooks can modify, delete, or access any files your user account can access

1275* Malicious or poorly written hooks can cause data loss or system damage

1276* Anthropic provides no warranty and assumes no liability for any damages

1277 resulting from hook usage

1278* You should thoroughly test hooks in a safe environment before production use

1279 1957 

1280Always review and understand any hook commands before adding them to your1958### Example: run tests after file changes

1281configuration.

1282 1959 

1283### Security Best Practices1960This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`:

1284 1961 

1285Here are some key practices for writing more secure hooks:1962```bash theme={null}

1963#!/bin/bash

1964# run-tests-async.sh

1286 1965 

12871. **Validate and sanitize inputs** - Never trust input data blindly1966# Read hook input from stdin

12882. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1967INPUT=$(cat)

12893. **Block path traversal** - Check for `..` in file paths1968FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

12904. **Use absolute paths** - Specify full paths for scripts (use

1291 "\$CLAUDE\_PROJECT\_DIR" for the project path)

12925. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.

1293 1969 

1294### Configuration Safety1970# Only run tests for source files

1971if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then

1972 exit 0

1973fi

1295 1974 

1296Direct edits to hooks in settings files don't take effect immediately. Claude1975# Run tests and report results via systemMessage

1297Code:1976RESULT=$(npm test 2>&1)

1977EXIT_CODE=$?

1298 1978 

12991. Captures a snapshot of hooks at startup1979if [ $EXIT_CODE -eq 0 ]; then

13002. Uses this snapshot throughout the session1980 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"

13013. Warns if hooks are modified externally1981else

13024. Requires review in `/hooks` menu for changes to apply1982 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"

1983fi

1984```

1303 1985 

1304This prevents malicious hook modifications from affecting your current session.1986Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:

1305 1987 

1306## Hook Execution Details1988```json theme={null}

1989{

1990 "hooks": {

1991 "PostToolUse": [

1992 {

1993 "matcher": "Write|Edit",

1994 "hooks": [

1995 {

1996 "type": "command",

1997 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",

1998 "async": true,

1999 "timeout": 300

2000 }

2001 ]

2002 }

2003 ]

2004 }

2005}

2006```

1307 2007 

1308* **Timeout**: 60-second execution limit by default, configurable per command.2008### Limitations

1309 * A timeout for an individual command does not affect the other commands.

1310* **Parallelization**: All matching hooks run in parallel

1311* **Deduplication**: Multiple identical hook commands are deduplicated automatically

1312* **Environment**: Runs in current directory with Claude Code's environment

1313 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the

1314 absolute path to the project root directory (where Claude Code was started)

1315 * The `CLAUDE_CODE_REMOTE` environment variable indicates whether the hook is running in a remote (web) environment (`"true"`) or local CLI environment (not set or empty). Use this to run different logic based on execution context.

1316* **Input**: JSON via stdin

1317* **Output**:

1318 * PreToolUse/PermissionRequest/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)

1319 * Notification/SessionEnd: Logged to debug only (`--debug`)

1320 * UserPromptSubmit/SessionStart/Setup: stdout added as context for Claude

1321 2009 

1322## Debugging2010Async hooks have several constraints compared to synchronous hooks:

1323 2011 

1324### Basic Troubleshooting2012* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.

2013* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.

2014* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.

2015* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.

1325 2016 

1326If your hooks aren't working:2017## Security considerations

1327 2018 

13281. **Check configuration** - Run `/hooks` to see if your hook is registered2019### Disclaimer

13292. **Verify syntax** - Ensure your JSON settings are valid

13303. **Test commands** - Run hook commands manually first

13314. **Check permissions** - Make sure scripts are executable

13325. **Review logs** - Use `claude --debug` to see hook execution details

1333 2020 

1334Common issues:2021Command hooks run with your system user's full permissions.

1335 2022 

1336* **Quotes not escaped** - Use `\"` inside JSON strings2023<Warning>

1337* **Wrong matcher** - Check tool names match exactly (case-sensitive)2024 Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration.

1338* **Command not found** - Use full paths for scripts2025</Warning>

1339 2026 

1340### Advanced Debugging2027### Security best practices

1341 2028 

1342For complex hook issues:2029Keep these practices in mind when writing hooks:

1343 2030 

13441. **Inspect hook execution** - Use `claude --debug` to see detailed hook2031* **Validate and sanitize inputs**: never trust input data blindly

1345 execution2032* **Always quote shell variables**: use `"$VAR"` not `$VAR`

13462. **Validate JSON schemas** - Test hook input/output with external tools2033* **Block path traversal**: check for `..` in file paths

13473. **Check environment variables** - Verify Claude Code's environment is correct2034* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root

13484. **Test edge cases** - Try hooks with unusual file paths or inputs2035* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.

13495. **Monitor system resources** - Check for resource exhaustion during hook

1350 execution

13516. **Use structured logging** - Implement logging in your hook scripts

1352 2036 

1353### Debug Output Example2037## Debug hooks

1354 2038 

1355Use `claude --debug` to see hook execution details:2039Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output. Toggle verbose mode with `Ctrl+O` to see hook progress in the transcript.

1356 2040 

1357```2041```text theme={null}

1358[DEBUG] Executing hooks for PostToolUse:Write2042[DEBUG] Executing hooks for PostToolUse:Write

1359[DEBUG] Getting matching hook commands for PostToolUse with query: Write2043[DEBUG] Getting matching hook commands for PostToolUse with query: Write

1360[DEBUG] Found 1 hook matchers in settings2044[DEBUG] Found 1 hook matchers in settings

1361[DEBUG] Matched 1 hooks for query "Write"2045[DEBUG] Matched 1 hooks for query "Write"

1362[DEBUG] Found 1 hook commands to execute2046[DEBUG] Found 1 hook commands to execute

1363[DEBUG] Executing hook command: <Your command> with timeout 60000ms2047[DEBUG] Executing hook command: <Your command> with timeout 600000ms

1364[DEBUG] Hook command completed with status 0: <Your stdout>2048[DEBUG] Hook command completed with status 0: <Your stdout>

1365```2049```

1366 2050 

1367Progress messages appear in verbose mode (ctrl+o) showing:2051For troubleshooting common issues like hooks not firing, infinite Stop hook loops, or configuration errors, see [Limitations and troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) in the guide.

1368 

1369* Which hook is running

1370* Command being executed

1371* Success/failure status

1372* Output or error messages

1373 

1374 

1375 

1376> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

hooks-guide.md +612 −204

Details

1# Get started with Claude Code hooks1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Learn how to customize and extend Claude Code's behavior by registering shell commands5# Automate workflows with hooks

4 6 

5Claude Code hooks are user-defined shell commands that execute at various points7> Run shell commands automatically when Claude Code edits files, finishes tasks, or needs input. Format code, send notifications, validate commands, and enforce project rules.

6in Claude Code's lifecycle. Hooks provide deterministic control over Claude8 

7Code's behavior, ensuring certain actions always happen rather than relying on9Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide deterministic control over Claude Code's behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools.

8the LLM to choose to run them.10 

11For decisions that require judgment rather than deterministic rules, you can also use [prompt-based hooks](#prompt-based-hooks) or [agent-based hooks](#agent-based-hooks) that use a Claude model to evaluate conditions.

12 

13For other ways to extend Claude Code, see [skills](/en/skills) for giving Claude additional instructions and executable commands, [subagents](/en/sub-agents) for running tasks in isolated contexts, and [plugins](/en/plugins) for packaging extensions to share across projects.

9 14 

10<Tip>15<Tip>

11 For reference documentation on hooks, see [Hooks reference](/en/hooks).16 This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](/en/hooks).

12</Tip>17</Tip>

13 18 

14Example use cases for hooks include:19## Set up your first hook

15 20 

16* **Notifications**: Customize how you get notified when Claude Code is awaiting21To create a hook, add a `hooks` block to a [settings file](#configure-hook-location). This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.

17 your input or permission to run something.

18* **Automatic formatting**: Run `prettier` on .ts files, `gofmt` on .go files,

19 etc. after every file edit.

20* **Logging**: Track and count all executed commands for compliance or

21 debugging.

22* **Feedback**: Provide automated feedback when Claude Code produces code that

23 does not follow your codebase conventions.

24* **Custom permissions**: Block modifications to production files or sensitive

25 directories.

26 22 

27By encoding these rules as hooks rather than prompting instructions, you turn23<Steps>

28suggestions into app-level code that executes every time it is expected to run.24 <Step title="Add the hook to your settings">

25 Open `~/.claude/settings.json` and add a `Notification` hook. The example below uses `osascript` for macOS; see [Get notified when Claude needs input](#get-notified-when-claude-needs-input) for Linux and Windows commands.

29 26 

30<Warning>27 ```json theme={null}

31 You must consider the security implication of hooks as you add them, because hooks run automatically during the agent loop with your current environment's credentials.28 {

32 For example, malicious hooks code can exfiltrate your data. Always review your hooks implementation before registering them.29 "hooks": {

30 "Notification": [

31 {

32 "matcher": "",

33 "hooks": [

34 {

35 "type": "command",

36 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

37 }

38 ]

39 }

40 ]

41 }

42 }

43 ```

33 44 

34 For full security best practices, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.45 If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than replacing the whole object. You can also ask Claude to write the hook for you by describing what you want in the CLI.

35</Warning>46 </Step>

36 47 

37## Hook Events Overview48 <Step title="Verify the configuration">

49 Type `/hooks` to open the hooks browser. You'll see a list of all available hook events, with a count next to each event that has hooks configured. Select `Notification` to confirm your new hook appears in the list. Selecting the hook shows its details: the event, matcher, type, source file, and command.

50 </Step>

38 51 

39Claude Code provides several hook events that run at different points in the52 <Step title="Test the hook">

40workflow:53 Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.

54 </Step>

55</Steps>

41 56 

42* **PreToolUse**: Runs before tool calls (can block them)57<Tip>

43* **PermissionRequest**: Runs when a permission dialog is shown (can allow or deny)58 The `/hooks` menu is read-only. To add, modify, or remove hooks, edit your settings JSON directly or ask Claude to make the change.

44* **PostToolUse**: Runs after tool calls complete59</Tip>

45* **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it

46* **Notification**: Runs when Claude Code sends notifications

47* **Stop**: Runs when Claude Code finishes responding

48* **SubagentStop**: Runs when subagent tasks complete

49* **PreCompact**: Runs before Claude Code is about to run a compact operation

50* **Setup**: Runs when Claude Code is invoked with `--init`, `--init-only`, or `--maintenance` flags

51* **SessionStart**: Runs when Claude Code starts a new session or resumes an existing session

52* **SessionEnd**: Runs when Claude Code session ends

53 60 

54Each event receives different data and can control Claude's behavior in61## What you can automate

55different ways.

56 62 

57## Quickstart63Hooks let you run code at key points in Claude Code's lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](/en/hooks#hook-lifecycle).

58 64 

59In this quickstart, you'll add a hook that logs the shell commands that Claude65Each example includes a ready-to-use configuration block that you add to a [settings file](#configure-hook-location). The most common patterns:

60Code runs.

61 66 

62### Prerequisites67* [Get notified when Claude needs input](#get-notified-when-claude-needs-input)

68* [Auto-format code after edits](#auto-format-code-after-edits)

69* [Block edits to protected files](#block-edits-to-protected-files)

70* [Re-inject context after compaction](#re-inject-context-after-compaction)

71* [Audit configuration changes](#audit-configuration-changes)

72* [Auto-approve specific permission prompts](#auto-approve-specific-permission-prompts)

63 73 

64Install `jq` for JSON processing in the command line.74### Get notified when Claude needs input

65 75 

66### Step 1: Open hooks configuration76Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal.

67 77 

68Run the `/hooks` command and select78This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform's native notification command. Add this to `~/.claude/settings.json`:

69the `PreToolUse` hook event.

70 79 

71`PreToolUse` hooks run before tool calls and can block them while providing80<Tabs>

72Claude feedback on what to do differently.81 <Tab title="macOS">

82 ```json theme={null}

83 {

84 "hooks": {

85 "Notification": [

86 {

87 "matcher": "",

88 "hooks": [

89 {

90 "type": "command",

91 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

92 }

93 ]

94 }

95 ]

96 }

97 }

98 ```

99 </Tab>

73 100 

74### Step 2: Add a matcher101 <Tab title="Linux">

102 ```json theme={null}

103 {

104 "hooks": {

105 "Notification": [

106 {

107 "matcher": "",

108 "hooks": [

109 {

110 "type": "command",

111 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

112 }

113 ]

114 }

115 ]

116 }

117 }

118 ```

119 </Tab>

75 120 

76Select `+ Add new matcher…` to run your hook only on Bash tool calls.121 <Tab title="Windows (PowerShell)">

122 ```json theme={null}

123 {

124 "hooks": {

125 "Notification": [

126 {

127 "matcher": "",

128 "hooks": [

129 {

130 "type": "command",

131 "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""

132 }

133 ]

134 }

135 ]

136 }

137 }

138 ```

139 </Tab>

140</Tabs>

77 141 

78Type `Bash` for the matcher.142### Auto-format code after edits

79 143 

80<Note>You can use `*` to match all tools.</Note>144Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

81 145 

82### Step 3: Add the hook146This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.github.io/jq/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:

83 147 

84Select `+ Add new hook…` and enter this command:148```json theme={null}

149{

150 "hooks": {

151 "PostToolUse": [

152 {

153 "matcher": "Edit|Write",

154 "hooks": [

155 {

156 "type": "command",

157 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"

158 }

159 ]

160 }

161 ]

162 }

163}

164```

85 165 

86```bash theme={null}166<Note>

87jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt167 The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or see [`jq` downloads](https://jqlang.github.io/jq/download/).

168</Note>

169 

170### Block edits to protected files

171 

172Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach.

173 

174This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit.

175 

176<Steps>

177 <Step title="Create the hook script">

178 Save this to `.claude/hooks/protect-files.sh`:

179 

180 ```bash theme={null}

181 #!/bin/bash

182 # protect-files.sh

183 

184 INPUT=$(cat)

185 FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

186 

187 PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

188 

189 for pattern in "${PROTECTED_PATTERNS[@]}"; do

190 if [[ "$FILE_PATH" == *"$pattern"* ]]; then

191 echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2

192 exit 2

193 fi

194 done

195 

196 exit 0

197 ```

198 </Step>

199 

200 <Step title="Make the script executable (macOS/Linux)">

201 Hook scripts must be executable for Claude Code to run them:

202 

203 ```bash theme={null}

204 chmod +x .claude/hooks/protect-files.sh

205 ```

206 </Step>

207 

208 <Step title="Register the hook">

209 Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call:

210 

211 ```json theme={null}

212 {

213 "hooks": {

214 "PreToolUse": [

215 {

216 "matcher": "Edit|Write",

217 "hooks": [

218 {

219 "type": "command",

220 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"

221 }

222 ]

223 }

224 ]

225 }

226 }

227 ```

228 </Step>

229</Steps>

230 

231### Re-inject context after compaction

232 

233When Claude's context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction.

234 

235Any text your command writes to stdout is added to Claude's context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:

236 

237```json theme={null}

238{

239 "hooks": {

240 "SessionStart": [

241 {

242 "matcher": "compact",

243 "hooks": [

244 {

245 "type": "command",

246 "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"

247 }

248 ]

249 }

250 ]

251 }

252}

88```253```

89 254 

90### Step 4: Save your configuration255You can replace the `echo` with any command that produces dynamic output, like `git log --oneline -5` to show recent commits. For injecting context on every session start, consider using [CLAUDE.md](/en/memory) instead. For environment variables, see [`CLAUDE_ENV_FILE`](/en/hooks#persist-environment-variables) in the reference.

91 256 

92For storage location, select `User settings` since you're logging to your home257### Audit configuration changes

93directory. This hook will then apply to all projects, not just your current

94project.

95 258 

96Then press `Esc` until you return to the REPL. Your hook is now registered.259Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications.

97 260 

98### Step 5: Verify your hook261This example appends each change to an audit log. Add this to `~/.claude/settings.json`:

99 262 

100Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:263```json theme={null}

264{

265 "hooks": {

266 "ConfigChange": [

267 {

268 "matcher": "",

269 "hooks": [

270 {

271 "type": "command",

272 "command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"

273 }

274 ]

275 }

276 ]

277 }

278}

279```

280 

281The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](/en/hooks#configchange) for the full input schema.

282 

283### Auto-approve specific permission prompts

284 

285Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren't prompted every time a plan is ready.

286 

287Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to show a permission dialog, and returning `"behavior": "allow"` answers it on your behalf.

288 

289The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:

101 290 

102```json theme={null}291```json theme={null}

103{292{

104 "hooks": {293 "hooks": {

105 "PreToolUse": [294 "PermissionRequest": [

106 {295 {

107 "matcher": "Bash",296 "matcher": "ExitPlanMode",

108 "hooks": [297 "hooks": [

109 {298 {

110 "type": "command",299 "type": "command",

111 "command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"300 "command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"

112 }301 }

113 ]302 ]

114 }303 }


117}306}

118```307```

119 308 

120### Step 6: Test your hook309When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows "Allowed by PermissionRequest hook" where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can.

121 310 

122Ask Claude to run a simple command like `ls` and check your log file:311To set a specific permission mode instead, your hook's output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.

123 312 

124```bash theme={null}313To switch the session to `acceptEdits`, your hook writes this JSON to stdout:

125cat ~/.claude/bash-command-log.txt314 

315```json theme={null}

316{

317 "hookSpecificOutput": {

318 "hookEventName": "PermissionRequest",

319 "decision": {

320 "behavior": "allow",

321 "updatedPermissions": [

322 { "type": "setMode", "mode": "acceptEdits", "destination": "session" }

323 ]

324 }

325 }

326}

126```327```

127 328 

128You should see entries like:329Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every permission prompt, including file writes and shell commands. See the [PermissionRequest reference](/en/hooks#permissionrequest-decision-control) for the full set of decision fields.

330 

331## How hooks work

332 

333Hook events fire at specific lifecycle points in Claude Code. When an event fires, all matching hooks run in parallel, and identical hook commands are automatically deduplicated. The table below shows each event and when it triggers:

334 

335| Event | When it fires |

336| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |

337| `SessionStart` | When a session begins or resumes |

338| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

339| `PreToolUse` | Before a tool call executes. Can block it |

340| `PermissionRequest` | When a permission dialog appears |

341| `PostToolUse` | After a tool call succeeds |

342| `PostToolUseFailure` | After a tool call fails |

343| `Notification` | When Claude Code sends a notification |

344| `SubagentStart` | When a subagent is spawned |

345| `SubagentStop` | When a subagent finishes |

346| `Stop` | When Claude finishes responding |

347| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

348| `TaskCompleted` | When a task is being marked as completed |

349| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

350| `ConfigChange` | When a configuration file changes during a session |

351| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

352| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

353| `PreCompact` | Before context compaction |

354| `PostCompact` | After context compaction completes |

355| `Elicitation` | When an MCP server requests user input during a tool call |

356| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

357| `SessionEnd` | When a session terminates |

358 

359Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:

360 

361* `"type": "http"`: POST event data to a URL. See [HTTP hooks](#http-hooks).

362* `"type": "prompt"`: single-turn LLM evaluation. See [Prompt-based hooks](#prompt-based-hooks).

363* `"type": "agent"`: multi-turn verification with tool access. See [Agent-based hooks](#agent-based-hooks).

129 364 

365### Read input and return output

366 

367Hooks communicate with Claude Code through stdin, stdout, stderr, and exit codes. When an event fires, Claude Code passes event-specific data as JSON to your script's stdin. Your script reads that data, does its work, and tells Claude Code what to do next via the exit code.

368 

369#### Hook input

370 

371Every event includes common fields like `session_id` and `cwd`, but each event type adds different data. For example, when Claude runs a Bash command, a `PreToolUse` hook receives something like this on stdin:

372 

373```json theme={null}

374{

375 "session_id": "abc123", // unique ID for this session

376 "cwd": "/Users/sarah/myproject", // working directory when the event fired

377 "hook_event_name": "PreToolUse", // which event triggered this hook

378 "tool_name": "Bash", // the tool Claude is about to use

379 "tool_input": { // the arguments Claude passed to the tool

380 "command": "npm test" // for Bash, this is the shell command

381 }

382}

130```383```

131ls - Lists files and directories384 

385Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, clear, compact), and so on. See [Common input fields](/en/hooks#common-input-fields) in the reference for shared fields, and each event's section for event-specific schemas.

386 

387#### Hook output

388 

389Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command:

390 

391```bash theme={null}

392#!/bin/bash

393INPUT=$(cat)

394COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')

395 

396if echo "$COMMAND" | grep -q "drop table"; then

397 echo "Blocked: dropping tables is not allowed" >&2 # stderr becomes Claude's feedback

398 exit 2 # exit 2 = block the action

399fi

400 

401exit 0 # exit 0 = let it proceed

132```402```

133 403 

134## More Examples404The exit code determines what happens next:

405 

406* **Exit 0**: the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude's context.

407* **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.

408* **Any other exit code**: the action proceeds. Stderr is logged but not shown to Claude. Toggle verbose mode with `Ctrl+O` to see these messages in the transcript.

409 

410#### Structured JSON output

411 

412Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead.

135 413 

136<Note>414<Note>

137 For a complete example implementation, see the [bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py) in our public codebase.415 Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don't mix them: Claude Code ignores JSON when you exit 2.

138</Note>416</Note>

139 417 

140### Code Formatting Hook418For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:

419 

420```json theme={null}

421{

422 "hookSpecificOutput": {

423 "hookEventName": "PreToolUse",

424 "permissionDecision": "deny",

425 "permissionDecisionReason": "Use rg instead of grep for better performance"

426 }

427}

428```

429 

430Claude Code reads `permissionDecision` and cancels the tool call, then feeds `permissionDecisionReason` back to Claude as feedback. These three options are specific to `PreToolUse`:

431 

432* `"allow"`: proceed without showing a permission prompt

433* `"deny"`: cancel the tool call and send the reason to Claude

434* `"ask"`: show the permission prompt to the user as normal

435 

436Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](/en/hooks#decision-control) in the reference for a full breakdown by event.

141 437 

142Automatically format TypeScript files after editing:438For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude's context. Prompt-based hooks (`type: "prompt"`) handle output differently: see [Prompt-based hooks](#prompt-based-hooks).

439 

440### Filter hooks with matchers

441 

442Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook:

143 443 

144```json theme={null}444```json theme={null}

145{445{


147 "PostToolUse": [447 "PostToolUse": [

148 {448 {

149 "matcher": "Edit|Write",449 "matcher": "Edit|Write",

450 "hooks": [

451 { "type": "command", "command": "prettier --write ..." }

452 ]

453 }

454 ]

455 }

456}

457```

458 

459The `"Edit|Write"` matcher is a regex pattern that matches the tool name. The hook only fires when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool.

460 

461Each event type matches on a specific field. Matchers support exact strings and regex patterns:

462 

463| Event | What the matcher filters | Example matcher values |

464| :---------------------------------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |

465| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

466| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

467| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

468| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

469| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

470| `PreCompact` | what triggered compaction | `manual`, `auto` |

471| `SubagentStop` | agent type | same values as `SubagentStart` |

472| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

473| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |

474 

475A few more examples showing matchers on different event types:

476 

477<Tabs>

478 <Tab title="Log every Bash command">

479 Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file:

480 

481 ```json theme={null}

482 {

483 "hooks": {

484 "PostToolUse": [

485 {

486 "matcher": "Bash",

150 "hooks": [487 "hooks": [

151 {488 {

152 "type": "command",489 "type": "command",

153 "command": "jq -r '.tool_input.file_path' | { read file_path; if echo \"$file_path\" | grep -q '\\.ts$'; then npx prettier --write \"$file_path\"; fi; }"490 "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"

154 }491 }

155 ]492 ]

156 }493 }

157 ]494 ]

158 }495 }

159}496 }

160```497 ```

498 </Tab>

499 

500 <Tab title="Match MCP tools">

501 MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](/en/hooks#match-mcp-tools) in the reference for the full list of examples.

502 

503 The command below extracts the tool name from the hook's JSON input with `jq` and writes it to stderr, where it shows up in verbose mode (`Ctrl+O`):

504 

505 ```json theme={null}

506 {

507 "hooks": {

508 "PreToolUse": [

509 {

510 "matcher": "mcp__github__.*",

511 "hooks": [

512 {

513 "type": "command",

514 "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2"

515 }

516 ]

517 }

518 ]

519 }

520 }

521 ```

522 </Tab>

523 

524 <Tab title="Clean up on session end">

525 The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits:

526 

527 ```json theme={null}

528 {

529 "hooks": {

530 "SessionEnd": [

531 {

532 "matcher": "clear",

533 "hooks": [

534 {

535 "type": "command",

536 "command": "rm -f /tmp/claude-scratch-*.txt"

537 }

538 ]

539 }

540 ]

541 }

542 }

543 ```

544 </Tab>

545</Tabs>

546 

547For full matcher syntax, see the [Hooks reference](/en/hooks#configuration).

548 

549### Configure hook location

550 

551Where you add a hook determines its scope:

161 552 

162### Markdown Formatting Hook553| Location | Scope | Shareable |

554| :--------------------------------------------------------- | :--------------------------------- | :--------------------------------- |

555| `~/.claude/settings.json` | All your projects | No, local to your machine |

556| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

557| `.claude/settings.local.json` | Single project | No, gitignored |

558| Managed policy settings | Organization-wide | Yes, admin-controlled |

559| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

560| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file |

163 561 

164Automatically fix missing language tags and formatting issues in markdown files:562Run [`/hooks`](/en/hooks#the-hooks-menu) in Claude Code to browse all configured hooks grouped by event. To disable all hooks at once, set `"disableAllHooks": true` in your settings file.

563 

564If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.

565 

566## Prompt-based hooks

567 

568For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook's input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability.

569 

570The model's only job is to return a yes/no decision as JSON:

571 

572* `"ok": true`: the action proceeds

573* `"ok": false`: the action is blocked. The model's `"reason"` is fed back to Claude so it can adjust.

574 

575This example uses a `Stop` hook to ask the model whether all requested tasks are complete. If the model returns `"ok": false`, Claude keeps working and uses the `reason` as its next instruction:

165 576 

166```json theme={null}577```json theme={null}

167{578{

168 "hooks": {579 "hooks": {

169 "PostToolUse": [580 "Stop": [

170 {581 {

171 "matcher": "Edit|Write",

172 "hooks": [582 "hooks": [

173 {583 {

174 "type": "command",584 "type": "prompt",

175 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"585 "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."

176 }586 }

177 ]587 ]

178 }588 }


181}591}

182```592```

183 593 

184Create `.claude/hooks/markdown_formatter.py` with this content:594For full configuration options, see [Prompt-based hooks](/en/hooks#prompt-based-hooks) in the reference.

185 

186````python theme={null}

187#!/usr/bin/env python3

188"""

189Markdown formatter for Claude Code output.

190Fixes missing language tags and spacing issues while preserving code content.

191"""

192import json

193import sys

194import re

195import os

196 

197def detect_language(code):

198 """Best-effort language detection from code content."""

199 s = code.strip()

200

201 # JSON detection

202 if re.search(r'^\s*[{\[]', s):

203 try:

204 json.loads(s)

205 return 'json'

206 except:

207 pass

208

209 # Python detection

210 if re.search(r'^\s*def\s+\w+\s*\(', s, re.M) or \

211 re.search(r'^\s*(import|from)\s+\w+', s, re.M):

212 return 'python'

213

214 # JavaScript detection

215 if re.search(r'\b(function\s+\w+\s*\(|const\s+\w+\s*=)', s) or \

216 re.search(r'=>|console\.(log|error)', s):

217 return 'javascript'

218

219 # Bash detection

220 if re.search(r'^#!.*\b(bash|sh)\b', s, re.M) or \

221 re.search(r'\b(if|then|fi|for|in|do|done)\b', s):

222 return 'bash'

223

224 # SQL detection

225 if re.search(r'\b(SELECT|INSERT|UPDATE|DELETE|CREATE)\s+', s, re.I):

226 return 'sql'

227

228 return 'text'

229 

230def format_markdown(content):

231 """Format markdown content with language detection."""

232 # Fix unlabeled code fences

233 def add_lang_to_fence(match):

234 indent, info, body, closing = match.groups()

235 if not info.strip():

236 lang = detect_language(body)

237 return f"{indent}```{lang}\n{body}{closing}\n"

238 return match.group(0)

239

240 fence_pattern = r'(?ms)^([ \t]{0,3})```([^\n]*)\n(.*?)(\n\1```)\s*$'

241 content = re.sub(fence_pattern, add_lang_to_fence, content)

242

243 # Fix excessive blank lines (only outside code fences)

244 content = re.sub(r'\n{3,}', '\n\n', content)

245

246 return content.rstrip() + '\n'

247 

248# Main execution

249try:

250 input_data = json.load(sys.stdin)

251 file_path = input_data.get('tool_input', {}).get('file_path', '')

252

253 if not file_path.endswith(('.md', '.mdx')):

254 sys.exit(0) # Not a markdown file

255

256 if os.path.exists(file_path):

257 with open(file_path, 'r', encoding='utf-8') as f:

258 content = f.read()

259

260 formatted = format_markdown(content)

261

262 if formatted != content:

263 with open(file_path, 'w', encoding='utf-8') as f:

264 f.write(formatted)

265 print(f"✓ Fixed markdown formatting in {file_path}")

266

267except Exception as e:

268 print(f"Error formatting markdown: {e}", file=sys.stderr)

269 sys.exit(1)

270````

271 

272Make the script executable:

273 595 

274```bash theme={null}596## Agent-based hooks

275chmod +x .claude/hooks/markdown_formatter.py

276```

277 

278This hook automatically:

279 597 

280* Detects programming languages in unlabeled code blocks598When verification requires inspecting files or running commands, use `type: "agent"` hooks. Unlike prompt hooks which make a single LLM call, agent hooks spawn a subagent that can read files, search code, and use other tools to verify conditions before returning a decision.

281* Adds appropriate language tags for syntax highlighting

282* Fixes excessive blank lines while preserving code content

283* Only processes markdown files (`.md`, `.mdx`)

284 599 

285### Custom Notification Hook600Agent hooks use the same `"ok"` / `"reason"` response format as prompt hooks, but with a longer default timeout of 60 seconds and up to 50 tool-use turns.

286 601 

287Get desktop notifications when Claude needs input:602This example verifies that tests pass before allowing Claude to stop:

288 603 

289```json theme={null}604```json theme={null}

290{605{

291 "hooks": {606 "hooks": {

292 "Notification": [607 "Stop": [

293 {608 {

294 "matcher": "",

295 "hooks": [609 "hooks": [

296 {610 {

297 "type": "command",611 "type": "agent",

298 "command": "notify-send 'Claude Code' 'Awaiting your input'"612 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

613 "timeout": 120

299 }614 }

300 ]615 ]

301 }616 }


304}619}

305```620```

306 621 

307### File Protection Hook622Use prompt hooks when the hook input data alone is enough to make a decision. Use agent hooks when you need to verify something against the actual state of the codebase.

623 

624For full configuration options, see [Agent-based hooks](/en/hooks#agent-based-hooks) in the reference.

625 

626## HTTP hooks

627 

628Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format.

308 629 

309Block edits to sensitive files:630HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team.

631 

632This example posts every tool use to a local logging service:

310 633 

311```json theme={null}634```json theme={null}

312{635{

313 "hooks": {636 "hooks": {

314 "PreToolUse": [637 "PostToolUse": [

315 {638 {

316 "matcher": "Edit|Write",

317 "hooks": [639 "hooks": [

318 {640 {

319 "type": "command",641 "type": "http",

320 "command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""642 "url": "http://localhost:8080/hooks/tool-use",

643 "headers": {

644 "Authorization": "Bearer $MY_TOKEN"

645 },

646 "allowedEnvVars": ["MY_TOKEN"]

321 }647 }

322 ]648 ]

323 }649 }


326}652}

327```653```

328 654 

329## Learn more655The endpoint should return a JSON response body using the same [output format](/en/hooks#json-output) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone cannot block actions.

656 

657Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty.

658 

659For full configuration options and response handling, see [HTTP hooks](/en/hooks#http-hook-fields) in the reference.

660 

661## Limitations and troubleshooting

662 

663### Limitations

664 

665* Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger commands or tool calls directly. HTTP hooks communicate through the response body instead.

666* Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).

667* `PostToolUse` hooks cannot undo actions since the tool has already executed.

668* `PermissionRequest` hooks do not fire in [non-interactive mode](/en/headless) (`-p`). Use `PreToolUse` hooks for automated permission decisions.

669* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts.

670 

671### Hook not firing

672 

673The hook is configured but never executes.

674 

675* Run `/hooks` and confirm the hook appears under the correct event

676* Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)

677* Verify you're triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)

678* If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead

679 

680### Hook error in output

681 

682You see a message like "PreToolUse hook error: ..." in the transcript.

683 

684* Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON:

685 ```bash theme={null}

686 echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh

687 echo $? # Check the exit code

688 ```

689* If you see "command not found", use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts

690* If you see "jq: command not found", install `jq` or use Python/Node.js for JSON parsing

691* If the script isn't running at all, make it executable: `chmod +x ./my-hook.sh`

692 

693### `/hooks` shows no hooks configured

694 

695You edited a settings file but the hooks don't appear in the menu.

330 696 

331* For reference documentation on hooks, see [Hooks reference](/en/hooks).697* File edits are normally picked up automatically. If they haven't appeared after a few seconds, the file watcher may have missed the change: restart your session to force a reload.

332* For comprehensive security best practices and safety guidelines, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.698* Verify your JSON is valid (trailing commas and comments are not allowed)

333* For troubleshooting steps and debugging techniques, see [Debugging](/en/hooks#debugging) in the hooks reference699* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks

334 documentation.

335 700 

701### Stop hook runs forever

336 702 

703Claude keeps working in an infinite loop instead of stopping.

704 

705Your Stop hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it's `true`:

706 

707```bash theme={null}

708#!/bin/bash

709INPUT=$(cat)

710if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then

711 exit 0 # Allow Claude to stop

712fi

713# ... rest of your hook logic

714```

715 

716### JSON validation failed

717 

718Claude Code shows a JSON parsing error even though your hook script outputs valid JSON.

719 

720When Claude Code runs a hook, it spawns a shell that sources your profile (`~/.zshrc` or `~/.bashrc`). If your profile contains unconditional `echo` statements, that output gets prepended to your hook's JSON:

721 

722```text theme={null}

723Shell ready on arm64

724{"decision": "block", "reason": "Not allowed"}

725```

726 

727Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells:

728 

729```bash theme={null}

730# In ~/.zshrc or ~/.bashrc

731if [[ $- == *i* ]]; then

732 echo "Shell ready"

733fi

734```

735 

736The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.

737 

738### Debug techniques

739 

740Toggle verbose mode with `Ctrl+O` to see hook output in the transcript, or run `claude --debug` for full execution details including which hooks matched and their exit codes.

741 

742## Learn more

337 743 

338> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt744* [Hooks reference](/en/hooks): full event schemas, JSON output format, async hooks, and MCP tool hooks

745* [Security considerations](/en/hooks#security-considerations): review before deploying hooks in shared or production environments

746* [Bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py): complete reference implementation

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# How Claude Code works5# How Claude Code works

2 6 

3> Understand the agentic loop, built-in tools, and how Claude Code interacts with your project.7> Understand the agentic loop, built-in tools, and how Claude Code interacts with your project.


10 14 

11When you give Claude a task, it works through three phases: **gather context**, **take action**, and **verify results**. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work.15When you give Claude a task, it works through three phases: **gather context**, **take action**, and **verify results**. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work.

12 16 

13<img src="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=e30acfc80d6ff01ec877dd19c7af58b2" alt="The agentic loop: Your prompt leads to Claude gathering context, taking action, verifying results, and repeating until task complete. You can interrupt at any point." data-og-width="720" width="720" data-og-height="280" height="280" data-path="images/agentic-loop.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=280&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=8620f6ebce761a1e8bbf7f0a0255cc15 280w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=560&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=7b46b5ff4454aa4a03725eee625b39a0 560w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=840&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=7fa0397bc37d147e3bf3bb6296c6477f 840w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=1100&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=73b2a7040c4c93821c4d5bbee9f4a2d4 1100w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=1650&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=17703cbeb6f59b40a00ab24f56d5f8f9 1650w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=2500&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=20dedb60b95d45a1bd60a0cccaf3e1ff 2500w" />17<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/agentic-loop.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=5f1827dec8539f38adee90ead3a85a38" alt="The agentic loop: Your prompt leads to Claude gathering context, taking action, verifying results, and repeating until task complete. You can interrupt at any point." width="720" height="280" data-path="images/agentic-loop.svg" />

14 18 

15The loop adapts to what you ask. A question about your codebase might only need context gathering. A bug fix cycles through all three phases repeatedly. A refactor might involve extensive verification. Claude decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way.19The loop adapts to what you ask. A question about your codebase might only need context gathering. A bug fix cycles through all three phases repeatedly. A refactor might involve extensive verification. Claude decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way.

16 20 


30 34 

31Tools are what make Claude Code agentic. Without tools, Claude can only respond with text. With tools, Claude can act: read your code, edit files, run commands, search the web, and interact with external services. Each tool use returns information that feeds back into the loop, informing Claude's next decision.35Tools are what make Claude Code agentic. Without tools, Claude can only respond with text. With tools, Claude can act: read your code, edit files, run commands, search the web, and interact with external services. Each tool use returns information that feeds back into the loop, informing Claude's next decision.

32 36 

33The built-in tools generally fall into four categories, each representing a different kind of agency.37The built-in tools generally fall into five categories, each representing a different kind of agency.

34 38 

35| Category | What Claude can do |39| Category | What Claude can do |

36| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |40| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |


40| **Web** | Search the web, fetch documentation, look up error messages |44| **Web** | Search the web, fetch documentation, look up error messages |

41| **Code intelligence** | See type errors and warnings after edits, jump to definitions, find references (requires [code intelligence plugins](/en/discover-plugins#code-intelligence)) |45| **Code intelligence** | See type errors and warnings after edits, jump to definitions, find references (requires [code intelligence plugins](/en/discover-plugins#code-intelligence)) |

42 46 

43These are the primary capabilities. Claude also has tools for spawning subagents, asking you questions, and other orchestration tasks. See [Tools available to Claude](/en/settings#tools-available-to-claude) for the complete list.47These are the primary capabilities. Claude also has tools for spawning subagents, asking you questions, and other orchestration tasks. See [Tools available to Claude](/en/tools-reference) for the complete list.

44 48 

45Claude chooses which tools to use based on your prompt and what it learns along the way. When you say "fix the failing tests," Claude might:49Claude chooses which tools to use based on your prompt and what it learns along the way. When you say "fix the failing tests," Claude might:

46 50 


57 61 

58## What Claude can access62## What Claude can access

59 63 

60This guide focuses on the terminal. Claude Code also runs in [VS Code, JetBrains IDEs, and other environments](/en/ide-integrations).64This guide focuses on the terminal. Claude Code also runs in [VS Code](/en/vs-code), [JetBrains IDEs](/en/jetbrains), and other environments.

61 65 

62When you run `claude` in a directory, Claude Code gains access to:66When you run `claude` in a directory, Claude Code gains access to:

63 67 


65* **Your terminal.** Any command you could run: build tools, git, package managers, system utilities, scripts. If you can do it from the command line, Claude can too.69* **Your terminal.** Any command you could run: build tools, git, package managers, system utilities, scripts. If you can do it from the command line, Claude can too.

66* **Your git state.** Current branch, uncommitted changes, and recent commit history.70* **Your git state.** Current branch, uncommitted changes, and recent commit history.

67* **Your [CLAUDE.md](/en/memory).** A markdown file where you store project-specific instructions, conventions, and context that Claude should know every session.71* **Your [CLAUDE.md](/en/memory).** A markdown file where you store project-specific instructions, conventions, and context that Claude should know every session.

72* **[Auto memory](/en/memory#auto-memory).** Learnings Claude saves automatically as you work, like project patterns and your preferences. The first 200 lines of MEMORY.md are loaded at the start of each session.

68* **Extensions you configure.** [MCP servers](/en/mcp) for external services, [skills](/en/skills) for workflows, [subagents](/en/sub-agents) for delegated work, and [Claude in Chrome](/en/chrome) for browser interaction.73* **Extensions you configure.** [MCP servers](/en/mcp) for external services, [skills](/en/skills) for workflows, [subagents](/en/sub-agents) for delegated work, and [Claude in Chrome](/en/chrome) for browser interaction.

69 74 

70Because Claude sees your whole project, it can work across it. When you ask Claude to "fix the authentication bug," it searches for relevant files, reads multiple files to understand context, makes coordinated edits across them, runs tests to verify the fix, and commits the changes if you ask. This is different from inline code assistants that only see the current file.75Because Claude sees your whole project, it can work across it. When you ask Claude to "fix the authentication bug," it searches for relevant files, reads multiple files to understand context, makes coordinated edits across them, runs tests to verify the fix, and commits the changes if you ask. This is different from inline code assistants that only see the current file.

71 76 

77## Environments and interfaces

78 

79The agentic loop, tools, and capabilities described above are the same everywhere you use Claude Code. What changes is where the code executes and how you interact with it.

80 

81### Execution environments

82 

83Claude Code runs in three environments, each with different tradeoffs for where your code executes.

84 

85| Environment | Where code runs | Use case |

86| ------------------ | --------------------------------------- | ---------------------------------------------------------- |

87| **Local** | Your machine | Default. Full access to your files, tools, and environment |

88| **Cloud** | Anthropic-managed VMs | Offload tasks, work on repos you don't have locally |

89| **Remote Control** | Your machine, controlled from a browser | Use the web UI while keeping everything local |

90 

91### Interfaces

92 

93You can access Claude Code through the terminal, the [desktop app](/en/desktop), [IDE extensions](/en/ide-integrations), [claude.ai/code](https://claude.ai/code), [Remote Control](/en/remote-control), [Slack](/en/slack), and [CI/CD pipelines](/en/github-actions). The interface determines how you see and interact with Claude, but the underlying agentic loop is identical. See [Use Claude Code everywhere](/en/overview#use-claude-code-everywhere) for the full list.

94 

72## Work with sessions95## Work with sessions

73 96 

74Claude Code saves your conversation locally as you work. Each message, tool use, and result is stored, which enables [rewinding](#undo-changes-with-checkpoints), [resuming, and forking](#resume-or-fork-sessions) sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed.97Claude Code saves your conversation locally as you work. Each message, tool use, and result is stored, which enables [rewinding](#undo-changes-with-checkpoints), [resuming, and forking](#resume-or-fork-sessions) sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed.

75 98 

76**Sessions are ephemeral.** Unlike claude.ai, Claude Code has no persistent memory between sessions. Each new session starts fresh. Claude doesn't "learn" your preferences over time or remember what you worked on last week. If you want Claude to know something across sessions, put it in your [CLAUDE.md](/en/memory).99**Sessions are independent.** Each new session starts with a fresh context window, without the conversation history from previous sessions. Claude can persist learnings across sessions using [auto memory](/en/memory#auto-memory), and you can add your own persistent instructions in [CLAUDE.md](/en/memory).

77 100 

78### Work across branches101### Work across branches

79 102 


87 110 

88When you resume a session with `claude --continue` or `claude --resume`, you pick up where you left off using the same session ID. New messages append to the existing conversation. Your full conversation history is restored, but session-scoped permissions are not. You'll need to re-approve those.111When you resume a session with `claude --continue` or `claude --resume`, you pick up where you left off using the same session ID. New messages append to the existing conversation. Your full conversation history is restored, but session-scoped permissions are not. You'll need to re-approve those.

89 112 

90<img src="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=f671b603cc856119c95475b9084ebfef" alt="Session continuity: resume continues the same session, fork creates a new branch with a new ID." data-og-width="560" width="560" data-og-height="280" height="280" data-path="images/session-continuity.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=280&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=bddf1f33d419a27d7427acdf06058804 280w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=560&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=417478eb9b86003b8eebaac058a8618a 560w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=840&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=1d89d26e2c0487f067d187c3fa5f7170 840w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=1100&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=8ea739a1f7860e4edbbcf74d444e37b2 1100w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=1650&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=9cb5095d6a8920f04c3b78d31a69c809 1650w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=2500&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=d67e1744e4878813d20c6c3f39d9459d 2500w" />113<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/session-continuity.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=fa41d12bfb57579cabfeece907151d30" alt="Session continuity: resume continues the same session, fork creates a new branch with a new ID." width="560" height="280" data-path="images/session-continuity.svg" />

91 114 

92To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:115To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:

93 116 


139* **Auto-accept edits**: Claude edits files without asking, still asks for commands162* **Auto-accept edits**: Claude edits files without asking, still asks for commands

140* **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution163* **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution

141 164 

142You can also allow specific commands in `.claude/settings.json` so Claude doesn't ask each time. This is useful for trusted commands like `npm test` or `git status`. Settings can be scoped from organization-wide policies down to personal preferences. See [Permissions](/en/iam) for details.165You can also allow specific commands in `.claude/settings.json` so Claude doesn't ask each time. This is useful for trusted commands like `npm test` or `git status`. Settings can be scoped from organization-wide policies down to personal preferences. See [Permissions](/en/permissions) for details.

143 166 

144***167***

145 168 


161 184 

162Claude Code is conversational. You don't need perfect prompts. Start with what you want, then refine:185Claude Code is conversational. You don't need perfect prompts. Start with what you want, then refine:

163 186 

187```text theme={null}

188Fix the login bug

164```189```

165> Fix the login bug

166 

167[Claude investigates, tries something]

168 190 

169> That's not quite right. The issue is in the session handling.191\[Claude investigates, tries something]

170 192 

171[Claude adjusts approach]193```text theme={null}

194That's not quite right. The issue is in the session handling.

172```195```

173 196 

197\[Claude adjusts approach]

198 

174When the first attempt isn't right, you don't start over. You iterate.199When the first attempt isn't right, you don't start over. You iterate.

175 200 

176#### Interrupt and steer201#### Interrupt and steer


181 206 

182The more precise your initial prompt, the fewer corrections you'll need. Reference specific files, mention constraints, and point to example patterns.207The more precise your initial prompt, the fewer corrections you'll need. Reference specific files, mention constraints, and point to example patterns.

183 208 

184```209```text theme={null}

185> The checkout flow is broken for users with expired cards.210The checkout flow is broken for users with expired cards.

186> Check src/payments/ for the issue, especially token refresh.211Check src/payments/ for the issue, especially token refresh.

187> Write a failing test first, then fix it.212Write a failing test first, then fix it.

188```213```

189 214 

190Vague prompts like "fix the login bug" work, but you'll spend more time steering. Specific prompts like the above often succeed on the first attempt.215Vague prompts work, but you'll spend more time steering. Specific prompts like the one above often succeed on the first attempt.

191 216 

192### Give Claude something to verify against217### Give Claude something to verify against

193 218 

194Claude performs better when it can check its own work. Include test cases, paste screenshots of expected UI, or define the output you want.219Claude performs better when it can check its own work. Include test cases, paste screenshots of expected UI, or define the output you want.

195 220 

196```221```text theme={null}

197> Implement validateEmail. Test cases: 'user@example.com' → true,222Implement validateEmail. Test cases: 'user@example.com' → true,

198> 'invalid' → false, 'user@.com' → false. Run the tests after.223'invalid' → false, 'user@.com' → false. Run the tests after.

199```224```

200 225 

201For visual work, paste a screenshot of the design and ask Claude to compare its implementation against it.226For visual work, paste a screenshot of the design and ask Claude to compare its implementation against it.


204 229 

205For complex problems, separate research from coding. Use plan mode (`Shift+Tab` twice) to analyze the codebase first:230For complex problems, separate research from coding. Use plan mode (`Shift+Tab` twice) to analyze the codebase first:

206 231 

207```232```text theme={null}

208> Read src/auth/ and understand how we handle sessions.233Read src/auth/ and understand how we handle sessions.

209> Then create a plan for adding OAuth support.234Then create a plan for adding OAuth support.

210```235```

211 236 

212Review the plan, refine it through conversation, then let Claude implement. This two-phase approach produces better results than jumping straight to code.237Review the plan, refine it through conversation, then let Claude implement. This two-phase approach produces better results than jumping straight to code.


215 240 

216Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details:241Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details:

217 242 

218```243```text theme={null}

219> The checkout flow is broken for users with expired cards.244The checkout flow is broken for users with expired cards.

220> The relevant code is in src/payments/. Can you investigate and fix it?245The relevant code is in src/payments/. Can you investigate and fix it?

221```246```

222 247 

223You don't need to specify which files to read or what commands to run. Claude figures that out.248You don't need to specify which files to read or what commands to run. Claude figures that out.


233 Step-by-step guides for typical tasks258 Step-by-step guides for typical tasks

234 </Card>259 </Card>

235</CardGroup>260</CardGroup>

236 

237 

238 

239> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

iam.md +0 −238 deleted

File DeletedView Diff

1# Identity and Access Management

2 

3> Learn how to configure user authentication, authorization, and access controls for Claude Code in your organization.

4 

5## Authentication methods

6 

7Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of these ways:

8 

9* [Claude for Teams or Enterprise](/en/setup#for-teams-and-organizations) (recommended)

10* [Claude Console with team billing](/en/setup#for-teams-and-organizations)

11* [Amazon Bedrock](/en/amazon-bedrock)

12* [Google Vertex AI](/en/google-vertex-ai)

13* [Microsoft Foundry](/en/microsoft-foundry)

14 

15### Claude for Teams or Enterprise (recommended)

16 

17[Claude for Teams](https://claude.com/pricing#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales) provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management.

18 

19* **Claude for Teams**: Self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams.

20* **Claude for Enterprise**: Adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.

21 

22**To set up Claude Code access:**

23 

241. Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales)

252. Invite team members from the admin dashboard

263. Team members install Claude Code and log in with their Claude.ai accounts

27 

28### Claude Console authentication

29 

30For organizations that prefer API-based billing, you can set up access through the Claude Console.

31 

32**To set up Claude Code access for your team via Claude Console:**

33 

341. Use your existing Claude Console account or create a new Claude Console account

352. You can add users through either method below:

36 * Bulk invite users from within the Console (Console -> Settings -> Members -> Invite)

37 * [Set up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso)

383. When inviting users, they need one of the following roles:

39 * "Claude Code" role means users can only create Claude Code API keys

40 * "Developer" role means users can create any kind of API key

414. Each invited user needs to complete these steps:

42 * Accept the Console invite

43 * [Check system requirements](/en/setup#system-requirements)

44 * [Install Claude Code](/en/setup#installation)

45 * Login with Console account credentials

46 

47### Cloud provider authentication

48 

49**To set up Claude Code access for your team via Bedrock, Vertex, or Azure:**

50 

511. Follow the [Bedrock docs](/en/amazon-bedrock), [Vertex docs](/en/google-vertex-ai), or [Microsoft Foundry docs](/en/microsoft-foundry)

522. Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/en/settings).

533. Users can [install Claude Code](/en/setup#installation)

54 

55## Access control and permissions

56 

57We support fine-grained permissions so that you're able to specify exactly what the agent is allowed to do (e.g. run tests, run linter) and what it is not allowed to do (e.g. update cloud infrastructure). These permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.

58 

59### Permission system

60 

61Claude Code uses a tiered permission system to balance power and safety:

62 

63| Tool Type | Example | Approval Required | "Yes, don't ask again" Behavior |

64| :---------------- | :--------------- | :---------------- | :-------------------------------------------- |

65| Read-only | File reads, Grep | No | N/A |

66| Bash Commands | Shell execution | Yes | Permanently per project directory and command |

67| File Modification | Edit/write files | Yes | Until session end |

68 

69### Configuring permissions

70 

71You can view & manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.

72 

73* **Allow** rules let Claude Code use the specified tool without manual approval.

74* **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool.

75* **Deny** rules prevent Claude Code from using the specified tool.

76 

77Rules are evaluated in order: **deny → ask → allow**. The first matching rule wins, so deny rules always take precedence.

78 

79* **Additional directories** extend Claude's file access to directories beyond the initial working directory.

80* **Default mode** controls Claude's permission behavior when encountering new requests.

81 

82Permission rules use the format: `Tool` or `Tool(optional-specifier)`

83 

84A rule that is just the tool name matches any use of that tool. For example, adding `Bash` to the allow list allows Claude Code to use the Bash tool without requiring user approval. Note that `Bash(*)` does **not** match all Bash commands. Use `Bash` without parentheses to match all uses.

85 

86<Note>

87 For a quick reference on permission rule syntax including wildcards, see [Permission rule syntax](/en/settings#permission-rule-syntax) in the settings documentation.

88</Note>

89 

90#### Permission modes

91 

92Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/settings#settings-files):

93 

94| Mode | Description |

95| :------------------ | :------------------------------------------------------------------------------------------------------------------------ |

96| `default` | Standard behavior - prompts for permission on first use of each tool |

97| `acceptEdits` | Automatically accepts file edit permissions for the session |

98| `plan` | Plan Mode - Claude can analyze but not modify files or execute commands |

99| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or [`permissions.allow`](/en/settings#permission-settings) rules |

100| `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) |

101 

102#### Working directories

103 

104By default, Claude has access to files in the directory where it was launched. You can extend this access:

105 

106* **During startup**: Use `--add-dir <path>` CLI argument

107* **During session**: Use `/add-dir` command

108* **Persistent configuration**: Add to `additionalDirectories` in [settings files](/en/settings#settings-files)

109 

110Files in additional directories follow the same permission rules as the original working directory - they become readable without prompts, and file editing permissions follow the current permission mode.

111 

112#### Tool-specific permission rules

113 

114Some tools support more fine-grained permission controls:

115 

116**Bash**

117 

118Bash permission rules support both prefix matching with `:*` and wildcard matching with `*`:

119 

120* `Bash(npm run build)` Matches the exact Bash command `npm run build`

121* `Bash(npm run test:*)` Matches Bash commands starting with `npm run test`

122* `Bash(npm *)` Matches any command starting with `npm ` (e.g., `npm install`, `npm run build`)

123* `Bash(* install)` Matches any command ending with ` install` (e.g., `npm install`, `yarn install`)

124* `Bash(git * main)` Matches commands like `git checkout main`, `git merge main`

125 

126The key difference between `:*` and `*`: the `:*` suffix enforces a word boundary, requiring the prefix to be followed by a space or end-of-string. For example, `Bash(ls:*)` matches `ls -la` but not `lsof`. In contrast, `Bash(ls*)` with a bare `*` matches both `ls -la` and `lsof` because `*` has no word boundary constraint.

127 

128<Tip>

129 Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd:*)` won't give it permission to run the command `safe-cmd && other-cmd`

130</Tip>

131 

132<Warning>

133 Important limitations of Bash permission patterns:

134 

135 1. The `:*` wildcard only works at the end of a pattern for prefix matching

136 2. The `*` wildcard can appear at any position and matches any sequence of characters

137 3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in many ways:

138 * Options before URL: `curl -X GET http://github.com/...` won't match

139 * Different protocol: `curl https://github.com/...` won't match

140 * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)

141 * Variables: `URL=http://github.com && curl $URL` won't match

142 * Extra spaces: `curl http://github.com` won't match

143 

144 For more reliable URL filtering, consider:

145 

146 * **Restrict Bash network tools**: Use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains

147 * **Use PreToolUse hooks**: Implement a hook that validates URLs in Bash commands and blocks disallowed domains

148 * Instructing Claude Code about your allowed curl patterns via CLAUDE.md

149 

150 Note that using WebFetch alone does not prevent network access. If Bash is allowed, Claude can still use `curl`, `wget`, or other tools to reach any URL.

151</Warning>

152 

153**Read & Edit**

154 

155`Edit` rules apply to all built-in tools that edit files. Claude will make a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep and Glob.

156 

157Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

158 

159| Pattern | Meaning | Example | Matches |

160| ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- |

161| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

162| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

163| `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `<settings file path>/src/**/*.ts` |

164| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

165 

166<Warning>

167 A pattern like `/Users/alice/file` is NOT an absolute path - it's relative to your settings file! Use `//Users/alice/file` for absolute paths.

168</Warning>

169 

170* `Edit(/docs/**)` - Edits in `<project>/docs/` (NOT `/docs/`!)

171* `Read(~/.zshrc)` - Reads your home directory's `.zshrc`

172* `Edit(//tmp/scratch.txt)` - Edits the absolute path `/tmp/scratch.txt`

173* `Read(src/**)` - Reads from `<current-directory>/src/`

174 

175<Note>

176 In gitignore patterns, `*` matches files in a single directory while `**` matches recursively across directories. To allow all file access, use just the tool name without parentheses: `Read`, `Edit`, or `Write`.

177</Note>

178 

179**WebFetch**

180 

181* `WebFetch(domain:example.com)` Matches fetch requests to example.com

182 

183**MCP**

184 

185* `mcp__puppeteer` Matches any tool provided by the `puppeteer` server (name configured in Claude Code)

186* `mcp__puppeteer__*` Wildcard syntax that also matches all tools from the `puppeteer` server

187* `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server

188 

189**Task (Subagents)**

190 

191Use `Task(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use:

192 

193* `Task(Explore)` Matches the Explore subagent

194* `Task(Plan)` Matches the Plan subagent

195* `Task(Verify)` Matches the Verify subagent

196 

197Add these rules to the `deny` array in your [settings](/en/settings#permission-settings) or use the `--disallowedTools` CLI flag to disable specific agents. For example, to disable the Explore agent:

198 

199```json theme={null}

200{

201 "permissions": {

202 "deny": ["Task(Explore)"]

203 }

204}

205```

206 

207### Additional permission control with hooks

208 

209[Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system runs, and the hook output can determine whether to approve or deny the tool call in place of the permission system.

210 

211### Managed settings

212 

213For organizations that need centralized control over Claude Code configuration, administrators can deploy `managed-settings.json` files to [system directories](/en/settings#settings-files). These policy files follow the same format as regular settings files and cannot be overridden by user or project settings.

214 

215### Settings precedence

216 

217When multiple settings sources exist, they are applied in the following order (highest to lowest precedence):

218 

2191. Managed settings (`managed-settings.json`)

2202. Command line arguments

2213. Local project settings (`.claude/settings.local.json`)

2224. Shared project settings (`.claude/settings.json`)

2235. User settings (`~/.claude/settings.json`)

224 

225This hierarchy ensures that organizational policies are always enforced while still allowing flexibility at the project and user levels where appropriate.

226 

227## Credential management

228 

229Claude Code securely manages your authentication credentials:

230 

231* **Storage location**: On macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain.

232* **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.

233* **Custom credential scripts**: The [`apiKeyHelper`](/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.

234* **Refresh intervals**: By default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.

235 

236 

237 

238> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Interactive mode5# Interactive mode

2 6 

3> Complete reference for keyboard shortcuts, input modes, and interactive features in Claude Code sessions.7> Complete reference for keyboard shortcuts, input modes, and interactive features in Claude Code sessions.


9 13 

10 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal:14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal:

11 15 

12 * **iTerm2**: Settings → Profiles → Keys → Set Left/Right Option key to "Esc+"16 * **iTerm2**: settings → Profiles → Keys → set Left/Right Option key to "Esc+"

13 * **Terminal.app**: Settings → Profiles → Keyboard → Check "Use Option as Meta Key"17 * **Terminal.app**: settings → Profiles → Keyboard → check "Use Option as Meta Key"

14 * **VS Code**: Settings → Profiles → Keys → Set Left/Right Option key to "Esc+"18 * **VS Code**: settings → Profiles → Keys → set Left/Right Option key to "Esc+"

15 19 

16 See [Terminal configuration](/en/terminal-config) for details.20 See [Terminal configuration](/en/terminal-config) for details.

17</Note>21</Note>


19### General controls23### General controls

20 24 

21| Shortcut | Description | Context |25| Shortcut | Description | Context |

22| :------------------------------------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------- |26| :------------------------------------------------ | :------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------- |

23| `Ctrl+C` | Cancel current input or generation | Standard interrupt |27| `Ctrl+C` | Cancel current input or generation | Standard interrupt |

28| `Ctrl+F` | Kill all background agents. Press twice within 3 seconds to confirm | Background agent control |

24| `Ctrl+D` | Exit Claude Code session | EOF signal |29| `Ctrl+D` | Exit Claude Code session | EOF signal |

25| `Ctrl+G` | Open in default text editor | Edit your prompt or custom response in your default text editor |30| `Ctrl+G` | Open in default text editor | Edit your prompt or custom response in your default text editor |

26| `Ctrl+L` | Clear terminal screen | Keeps conversation history |31| `Ctrl+L` | Clear terminal screen | Keeps conversation history |


28| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |33| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |

29| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file |34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file |

30| `Ctrl+B` | Background running tasks | Backgrounds bash commands and agents. Tmux users press twice |35| `Ctrl+B` | Background running tasks | Backgrounds bash commands and agents. Tmux users press twice |

36| `Ctrl+T` | Toggle task list | Show or hide the [task list](#task-list) in the terminal status area |

31| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |37| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |

32| `Up/Down arrows` | Navigate command history | Recall previous inputs |38| `Up/Down arrows` | Navigate command history | Recall previous inputs |

33| `Esc` + `Esc` | Rewind the code/conversation | Restore the code and/or conversation to a previous point |39| `Esc` + `Esc` | Rewind or summarize | Restore code and/or conversation to a previous point, or summarize from a selected message |

34| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode |40| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode. |

35| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |41| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |

36| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Run `/terminal-setup` first to enable this shortcut |42| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Run `/terminal-setup` first to enable this shortcut |

37 43 


80 86 

81## Built-in commands87## Built-in commands

82 88 

83Built-in commands are shortcuts for common actions. The table below covers commonly used commands but not all available options. Type `/` in Claude Code to see the full list, or type `/` followed by any letters to filter.89Type `/` in Claude Code to see all available commands, or type `/` followed by any letters to filter. The `/` menu shows both built-in commands and [bundled skills](/en/skills#bundled-skills) like `/simplify`. Not all commands are visible to every user since some depend on your platform or plan.

84 90 

85To create your own commands you can invoke with `/`, see [skills](/en/skills).91See the [commands reference](/en/commands) for the full list of built-in commands. To create your own commands, see [skills](/en/skills).

86 

87| Command | Purpose |

88| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------- |

89| `/clear` | Clear conversation history |

90| `/compact [instructions]` | Compact conversation with optional focus instructions |

91| `/config` | Open the Settings interface (Config tab) |

92| `/context` | Visualize current context usage as a colored grid |

93| `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details. |

94| `/doctor` | Checks the health of your Claude Code installation |

95| `/exit` | Exit the REPL |

96| `/export [filename]` | Export the current conversation to a file or clipboard |

97| `/help` | Get usage help |

98| `/init` | Initialize project with `CLAUDE.md` guide |

99| `/mcp` | Manage MCP server connections and OAuth authentication |

100| `/memory` | Edit `CLAUDE.md` memory files |

101| `/model` | Select or change the AI model |

102| `/permissions` | View or update [permissions](/en/iam#configuring-permissions) |

103| `/plan` | Enter plan mode directly from the prompt |

104| `/rename <name>` | Rename the current session for easier identification |

105| `/resume [session]` | Resume a conversation by ID or name, or open the session picker |

106| `/rewind` | Rewind the conversation and/or code |

107| `/stats` | Visualize daily usage, session history, streaks, and model preferences |

108| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |

109| `/statusline` | Set up Claude Code's status line UI |

110| `/tasks` | List and manage background tasks |

111| `/teleport` | Resume a remote session from claude.ai (subscribers only) |

112| `/theme` | Change the color theme |

113| `/todos` | List current TODO items |

114| `/usage` | For subscription plans only: show plan usage limits and rate limit status |

115 

116### MCP prompts

117 

118MCP servers can expose prompts that appear as commands. These use the format `/mcp__<server>__<prompt>` and are dynamically discovered from connected servers. See [MCP prompts](/en/mcp#use-mcp-prompts-as-commands) for details.

119 92 

120## Vim editor mode93## Vim editor mode

121 94 


153| `;` | Repeat last f/F/t/T motion |126| `;` | Repeat last f/F/t/T motion |

154| `,` | Repeat last f/F/t/T motion in reverse |127| `,` | Repeat last f/F/t/T motion in reverse |

155 128 

129<Note>

130 In vim normal mode, if the cursor is at the beginning or end of input and cannot move further, the arrow keys navigate command history instead.

131</Note>

132 

156### Editing (NORMAL mode)133### Editing (NORMAL mode)

157 134 

158| Command | Action |135| Command | Action |


191 168 

192Claude Code maintains command history for the current session:169Claude Code maintains command history for the current session:

193 170 

194* History is stored per working directory171* Input history is stored per working directory

195* Cleared with `/clear` command172* Input history resets when you run `/clear` to start a new session. The previous session's conversation is preserved and can be resumed.

196* Use Up/Down arrows to navigate (see keyboard shortcuts above)173* Use Up/Down arrows to navigate (see keyboard shortcuts above)

197* **Note**: History expansion (`!`) is disabled by default174* **Note**: history expansion (`!`) is disabled by default

198 175 

199### Reverse search with Ctrl+R176### Reverse search with Ctrl+R

200 177 

201Press `Ctrl+R` to interactively search through your command history:178Press `Ctrl+R` to interactively search through your command history:

202 179 

2031. **Start search**: Press `Ctrl+R` to activate reverse history search1801. **Start search**: press `Ctrl+R` to activate reverse history search

2042. **Type query**: Enter text to search for in previous commands - the search term will be highlighted in matching results1812. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results

2053. **Navigate matches**: Press `Ctrl+R` again to cycle through older matches1823. **Navigate matches**: press `Ctrl+R` again to cycle through older matches

2064. **Accept match**:1834. **Accept match**:

207 * Press `Tab` or `Esc` to accept the current match and continue editing184 * Press `Tab` or `Esc` to accept the current match and continue editing

208 * Press `Enter` to accept and execute the command immediately185 * Press `Enter` to accept and execute the command immediately


210 * Press `Ctrl+C` to cancel and restore your original input187 * Press `Ctrl+C` to cancel and restore your original input

211 * Press `Backspace` on empty search to cancel188 * Press `Backspace` on empty search to cancel

212 189 

213The search displays matching commands with the search term highlighted, making it easy to find and reuse previous inputs.190The search displays matching commands with the search term highlighted, so you can find and reuse previous inputs.

214 191 

215## Background bash commands192## Background bash commands

216 193 


231* Background tasks have unique IDs for tracking and output retrieval208* Background tasks have unique IDs for tracking and output retrieval

232* Background tasks are automatically cleaned up when Claude Code exits209* Background tasks are automatically cleaned up when Claude Code exits

233 210 

234To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables) for details.211To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars) for details.

235 212 

236**Common backgrounded commands:**213**Common backgrounded commands:**

237 214 


258* Supports the same `Ctrl+B` backgrounding for long-running commands235* Supports the same `Ctrl+B` backgrounding for long-running commands

259* Does not require Claude to interpret or approve the command236* Does not require Claude to interpret or approve the command

260* Supports history-based autocomplete: type a partial command and press **Tab** to complete from previous `!` commands in the current project237* Supports history-based autocomplete: type a partial command and press **Tab** to complete from previous `!` commands in the current project

238* Exit with `Escape`, `Backspace`, or `Ctrl+U` on an empty prompt

261 239 

262This is useful for quick shell operations while maintaining conversation context.240This is useful for quick shell operations while maintaining conversation context.

263 241 

242## Prompt suggestions

243 

244When you first open a session, a grayed-out example command appears in the prompt input to help you get started. Claude Code picks this from your project's git history, so it reflects files you've been working on recently.

245 

246After Claude responds, suggestions continue to appear based on your conversation history, such as a follow-up step from a multi-part request or a natural continuation of your workflow.

247 

248* Press **Tab** to accept the suggestion, or press **Enter** to accept and submit

249* Start typing to dismiss it

250 

251The suggestion runs as a background request that reuses the parent conversation's prompt cache, so the additional cost is minimal. Claude Code skips suggestion generation when the cache is cold to avoid unnecessary cost.

252 

253Suggestions are automatically skipped after the first turn of a conversation, in non-interactive mode, and in plan mode.

254 

255To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:

256 

257```bash theme={null}

258export CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false

259```

260 

261## Side questions with /btw

262 

263Use `/btw` to ask a quick question about your current work without adding to the conversation history. This is useful when you want a fast answer but don't want to clutter the main context or derail Claude from a long-running task.

264 

265```

266/btw what was the name of that config file again?

267```

268 

269Side questions have full visibility into the current conversation, so you can ask about code Claude has already read, decisions it made earlier, or anything else from the session. The question and answer are ephemeral: they appear in a dismissible overlay and never enter the conversation history.

270 

271* **Available while Claude is working**: you can run `/btw` even while Claude is processing a response. The side question runs independently and does not interrupt the main turn.

272* **No tool access**: side questions answer only from what is already in context. Claude cannot read files, run commands, or search when answering a side question.

273* **Single response**: there are no follow-up turns. If you need a back-and-forth, use a normal prompt instead.

274* **Low cost**: the side question reuses the parent conversation's prompt cache, so the additional cost is minimal.

275 

276Press **Space**, **Enter**, or **Escape** to dismiss the answer and return to the prompt.

277 

278`/btw` is the inverse of a [subagent](/en/sub-agents): it sees your full conversation but has no tools, while a subagent has full tools but starts with an empty context. Use `/btw` to ask about what Claude already knows from this session; use a subagent to go find out something new.

279 

264## Task list280## Task list

265 281 

266When working on complex, multi-step work, Claude creates a task list to track progress. Tasks appear in the status area of your terminal with indicators showing what's pending, in progress, or complete.282When working on complex, multi-step work, Claude creates a task list to track progress. Tasks appear in the status area of your terminal with indicators showing what's pending, in progress, or complete.


270* Tasks persist across context compactions, helping Claude stay organized on larger projects286* Tasks persist across context compactions, helping Claude stay organized on larger projects

271* To share a task list across sessions, set `CLAUDE_CODE_TASK_LIST_ID` to use a named directory in `~/.claude/tasks/`: `CLAUDE_CODE_TASK_LIST_ID=my-project claude`287* To share a task list across sessions, set `CLAUDE_CODE_TASK_LIST_ID` to use a named directory in `~/.claude/tasks/`: `CLAUDE_CODE_TASK_LIST_ID=my-project claude`

272 288 

289## PR review status

290 

291When working on a branch with an open pull request, Claude Code displays a clickable PR link in the footer (for example, "PR #446"). The link has a colored underline indicating the review state:

292 

293* Green: approved

294* Yellow: pending review

295* Red: changes requested

296* Gray: draft

297* Purple: merged

298 

299`Cmd+click` (Mac) or `Ctrl+click` (Windows/Linux) the link to open the pull request in your browser. The status updates automatically every 60 seconds.

300 

301<Note>

302 PR status requires the `gh` CLI to be installed and authenticated (`gh auth login`).

303</Note>

304 

273## See also305## See also

274 306 

275* [Skills](/en/skills) - Custom prompts and workflows307* [Skills](/en/skills) - Custom prompts and workflows


277* [CLI reference](/en/cli-reference) - Command-line flags and options309* [CLI reference](/en/cli-reference) - Command-line flags and options

278* [Settings](/en/settings) - Configuration options310* [Settings](/en/settings) - Configuration options

279* [Memory management](/en/memory) - Managing CLAUDE.md files311* [Memory management](/en/memory) - Managing CLAUDE.md files

280 

281 

282 

283> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

jetbrains.md +8 −5

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# JetBrains IDEs5# JetBrains IDEs

2 6 

3> Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more7> Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more


47 51 

48```bash theme={null}52```bash theme={null}

49claude53claude

50> /ide54```

55 

56```text theme={null}

57/ide

51```58```

52 59 

53If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root.60If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root.


146* Being aware of which files Claude Code has access to modify153* Being aware of which files Claude Code has access to modify

147 154 

148For additional help, see our [troubleshooting guide](/en/troubleshooting).155For additional help, see our [troubleshooting guide](/en/troubleshooting).

149 

150 

151 

152> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

keybindings.md +385 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Customize keyboard shortcuts

6 

7> Customize keyboard shortcuts in Claude Code with a keybindings configuration file.

8 

9<Note>

10 Customizable keyboard shortcuts require Claude Code v2.1.18 or later. Check your version with `claude --version`.

11</Note>

12 

13Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`.

14 

15## Configuration file

16 

17The keybindings configuration file is an object with a `bindings` array. Each block specifies a context and a map of keystrokes to actions.

18 

19<Note>Changes to the keybindings file are automatically detected and applied without restarting Claude Code.</Note>

20 

21| Field | Description |

22| :--------- | :------------------------------------------------- |

23| `$schema` | Optional JSON Schema URL for editor autocompletion |

24| `$docs` | Optional documentation URL |

25| `bindings` | Array of binding blocks by context |

26 

27This example binds `Ctrl+E` to open an external editor in the chat context, and unbinds `Ctrl+U`:

28 

29```json theme={null}

30{

31 "$schema": "https://www.schemastore.org/claude-code-keybindings.json",

32 "$docs": "https://code.claude.com/docs/en/keybindings",

33 "bindings": [

34 {

35 "context": "Chat",

36 "bindings": {

37 "ctrl+e": "chat:externalEditor",

38 "ctrl+u": null

39 }

40 }

41 ]

42}

43```

44 

45## Contexts

46 

47Each binding block specifies a **context** where the bindings apply:

48 

49| Context | Description |

50| :---------------- | :----------------------------------------------- |

51| `Global` | Applies everywhere in the app |

52| `Chat` | Main chat input area |

53| `Autocomplete` | Autocomplete menu is open |

54| `Settings` | Settings menu (escape-only dismiss) |

55| `Confirmation` | Permission and confirmation dialogs |

56| `Tabs` | Tab navigation components |

57| `Help` | Help menu is visible |

58| `Transcript` | Transcript viewer |

59| `HistorySearch` | History search mode (Ctrl+R) |

60| `Task` | Background task is running |

61| `ThemePicker` | Theme picker dialog |

62| `Attachments` | Image/attachment bar navigation |

63| `Footer` | Footer indicator navigation (tasks, teams, diff) |

64| `MessageSelector` | Rewind and summarize dialog message selection |

65| `DiffDialog` | Diff viewer navigation |

66| `ModelPicker` | Model picker effort level |

67| `Select` | Generic select/list components |

68| `Plugin` | Plugin dialog (browse, discover, manage) |

69 

70## Available actions

71 

72Actions follow a `namespace:action` format, such as `chat:submit` to send a message or `app:toggleTodos` to show the task list. Each context has specific actions available.

73 

74### App actions

75 

76Actions available in the `Global` context:

77 

78| Action | Default | Description |

79| :--------------------- | :------ | :-------------------------- |

80| `app:interrupt` | Ctrl+C | Cancel current operation |

81| `app:exit` | Ctrl+D | Exit Claude Code |

82| `app:toggleTodos` | Ctrl+T | Toggle task list visibility |

83| `app:toggleTranscript` | Ctrl+O | Toggle verbose transcript |

84 

85### History actions

86 

87Actions for navigating command history:

88 

89| Action | Default | Description |

90| :----------------- | :------ | :-------------------- |

91| `history:search` | Ctrl+R | Open history search |

92| `history:previous` | Up | Previous history item |

93| `history:next` | Down | Next history item |

94 

95### Chat actions

96 

97Actions available in the `Chat` context:

98 

99| Action | Default | Description |

100| :-------------------- | :------------------------ | :----------------------- |

101| `chat:cancel` | Escape | Cancel current input |

102| `chat:cycleMode` | Shift+Tab\* | Cycle permission modes |

103| `chat:modelPicker` | Cmd+P / Meta+P | Open model picker |

104| `chat:thinkingToggle` | Cmd+T / Meta+T | Toggle extended thinking |

105| `chat:submit` | Enter | Submit message |

106| `chat:undo` | Ctrl+\_ | Undo last action |

107| `chat:externalEditor` | Ctrl+G | Open in external editor |

108| `chat:stash` | Ctrl+S | Stash current prompt |

109| `chat:imagePaste` | Ctrl+V (Alt+V on Windows) | Paste image |

110 

111\*On Windows without VT mode (Node \<24.2.0/\<22.17.0, Bun \<1.2.23), defaults to Meta+M.

112 

113### Autocomplete actions

114 

115Actions available in the `Autocomplete` context:

116 

117| Action | Default | Description |

118| :---------------------- | :------ | :------------------ |

119| `autocomplete:accept` | Tab | Accept suggestion |

120| `autocomplete:dismiss` | Escape | Dismiss menu |

121| `autocomplete:previous` | Up | Previous suggestion |

122| `autocomplete:next` | Down | Next suggestion |

123 

124### Confirmation actions

125 

126Actions available in the `Confirmation` context:

127 

128| Action | Default | Description |

129| :-------------------------- | :-------- | :---------------------------- |

130| `confirm:yes` | Y, Enter | Confirm action |

131| `confirm:no` | N, Escape | Decline action |

132| `confirm:previous` | Up | Previous option |

133| `confirm:next` | Down | Next option |

134| `confirm:nextField` | Tab | Next field |

135| `confirm:previousField` | (unbound) | Previous field |

136| `confirm:cycleMode` | Shift+Tab | Cycle permission modes |

137| `confirm:toggleExplanation` | Ctrl+E | Toggle permission explanation |

138 

139### Permission actions

140 

141Actions available in the `Confirmation` context for permission dialogs:

142 

143| Action | Default | Description |

144| :----------------------- | :------ | :--------------------------- |

145| `permission:toggleDebug` | Ctrl+D | Toggle permission debug info |

146 

147### Transcript actions

148 

149Actions available in the `Transcript` context:

150 

151| Action | Default | Description |

152| :------------------------- | :------------- | :---------------------- |

153| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |

154| `transcript:exit` | Ctrl+C, Escape | Exit transcript view |

155 

156### History search actions

157 

158Actions available in the `HistorySearch` context:

159 

160| Action | Default | Description |

161| :---------------------- | :---------- | :----------------------- |

162| `historySearch:next` | Ctrl+R | Next match |

163| `historySearch:accept` | Escape, Tab | Accept selection |

164| `historySearch:cancel` | Ctrl+C | Cancel search |

165| `historySearch:execute` | Enter | Execute selected command |

166 

167### Task actions

168 

169Actions available in the `Task` context:

170 

171| Action | Default | Description |

172| :---------------- | :------ | :---------------------- |

173| `task:background` | Ctrl+B | Background current task |

174 

175### Theme actions

176 

177Actions available in the `ThemePicker` context:

178 

179| Action | Default | Description |

180| :------------------------------- | :------ | :------------------------- |

181| `theme:toggleSyntaxHighlighting` | Ctrl+T | Toggle syntax highlighting |

182 

183### Help actions

184 

185Actions available in the `Help` context:

186 

187| Action | Default | Description |

188| :------------- | :------ | :-------------- |

189| `help:dismiss` | Escape | Close help menu |

190 

191### Tabs actions

192 

193Actions available in the `Tabs` context:

194 

195| Action | Default | Description |

196| :-------------- | :-------------- | :----------- |

197| `tabs:next` | Tab, Right | Next tab |

198| `tabs:previous` | Shift+Tab, Left | Previous tab |

199 

200### Attachments actions

201 

202Actions available in the `Attachments` context:

203 

204| Action | Default | Description |

205| :--------------------- | :---------------- | :------------------------- |

206| `attachments:next` | Right | Next attachment |

207| `attachments:previous` | Left | Previous attachment |

208| `attachments:remove` | Backspace, Delete | Remove selected attachment |

209| `attachments:exit` | Down, Escape | Exit attachment bar |

210 

211### Footer actions

212 

213Actions available in the `Footer` context:

214 

215| Action | Default | Description |

216| :---------------------- | :------ | :------------------------ |

217| `footer:next` | Right | Next footer item |

218| `footer:previous` | Left | Previous footer item |

219| `footer:openSelected` | Enter | Open selected footer item |

220| `footer:clearSelection` | Escape | Clear footer selection |

221 

222### Message selector actions

223 

224Actions available in the `MessageSelector` context:

225 

226| Action | Default | Description |

227| :----------------------- | :---------------------------------------- | :---------------- |

228| `messageSelector:up` | Up, K, Ctrl+P | Move up in list |

229| `messageSelector:down` | Down, J, Ctrl+N | Move down in list |

230| `messageSelector:top` | Ctrl+Up, Shift+Up, Meta+Up, Shift+K | Jump to top |

231| `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | Jump to bottom |

232| `messageSelector:select` | Enter | Select message |

233 

234### Diff actions

235 

236Actions available in the `DiffDialog` context:

237 

238| Action | Default | Description |

239| :-------------------- | :----------------- | :--------------------- |

240| `diff:dismiss` | Escape | Close diff viewer |

241| `diff:previousSource` | Left | Previous diff source |

242| `diff:nextSource` | Right | Next diff source |

243| `diff:previousFile` | Up | Previous file in diff |

244| `diff:nextFile` | Down | Next file in diff |

245| `diff:viewDetails` | Enter | View diff details |

246| `diff:back` | (context-specific) | Go back in diff viewer |

247 

248### Model picker actions

249 

250Actions available in the `ModelPicker` context:

251 

252| Action | Default | Description |

253| :--------------------------- | :------ | :-------------------- |

254| `modelPicker:decreaseEffort` | Left | Decrease effort level |

255| `modelPicker:increaseEffort` | Right | Increase effort level |

256 

257### Select actions

258 

259Actions available in the `Select` context:

260 

261| Action | Default | Description |

262| :---------------- | :-------------- | :--------------- |

263| `select:next` | Down, J, Ctrl+N | Next option |

264| `select:previous` | Up, K, Ctrl+P | Previous option |

265| `select:accept` | Enter | Accept selection |

266| `select:cancel` | Escape | Cancel selection |

267 

268### Plugin actions

269 

270Actions available in the `Plugin` context:

271 

272| Action | Default | Description |

273| :--------------- | :------ | :----------------------- |

274| `plugin:toggle` | Space | Toggle plugin selection |

275| `plugin:install` | I | Install selected plugins |

276 

277### Settings actions

278 

279Actions available in the `Settings` context:

280 

281| Action | Default | Description |

282| :---------------- | :------ | :---------------------------------- |

283| `settings:search` | / | Enter search mode |

284| `settings:retry` | R | Retry loading usage data (on error) |

285 

286## Keystroke syntax

287 

288### Modifiers

289 

290Use modifier keys with the `+` separator:

291 

292* `ctrl` or `control` - Control key

293* `alt`, `opt`, or `option` - Alt/Option key

294* `shift` - Shift key

295* `meta`, `cmd`, or `command` - Meta/Command key

296 

297For example:

298 

299```text theme={null}

300ctrl+k Single key with modifier

301shift+tab Shift + Tab

302meta+p Command/Meta + P

303ctrl+shift+c Multiple modifiers

304```

305 

306### Uppercase letters

307 

308A standalone uppercase letter implies Shift. For example, `K` is equivalent to `shift+k`. This is useful for vim-style bindings where uppercase and lowercase keys have different meanings.

309 

310Uppercase letters with modifiers (e.g., `ctrl+K`) are treated as stylistic and do **not** imply Shift — `ctrl+K` is the same as `ctrl+k`.

311 

312### Chords

313 

314Chords are sequences of keystrokes separated by spaces:

315 

316```text theme={null}

317ctrl+k ctrl+s Press Ctrl+K, release, then Ctrl+S

318```

319 

320### Special keys

321 

322* `escape` or `esc` - Escape key

323* `enter` or `return` - Enter key

324* `tab` - Tab key

325* `space` - Space bar

326* `up`, `down`, `left`, `right` - Arrow keys

327* `backspace`, `delete` - Delete keys

328 

329## Unbind default shortcuts

330 

331Set an action to `null` to unbind a default shortcut:

332 

333```json theme={null}

334{

335 "bindings": [

336 {

337 "context": "Chat",

338 "bindings": {

339 "ctrl+s": null

340 }

341 }

342 ]

343}

344```

345 

346## Reserved shortcuts

347 

348These shortcuts cannot be rebound:

349 

350| Shortcut | Reason |

351| :------- | :------------------------- |

352| Ctrl+C | Hardcoded interrupt/cancel |

353| Ctrl+D | Hardcoded exit |

354 

355## Terminal conflicts

356 

357Some shortcuts may conflict with terminal multiplexers:

358 

359| Shortcut | Conflict |

360| :------- | :-------------------------------- |

361| Ctrl+B | tmux prefix (press twice to send) |

362| Ctrl+A | GNU screen prefix |

363| Ctrl+Z | Unix process suspend (SIGTSTP) |

364 

365## Vim mode interaction

366 

367When vim mode is enabled (`/vim`), keybindings and vim mode operate independently:

368 

369* **Vim mode** handles input at the text input level (cursor movement, modes, motions)

370* **Keybindings** handle actions at the component level (toggle todos, submit, etc.)

371* The Escape key in vim mode switches INSERT to NORMAL mode; it does not trigger `chat:cancel`

372* Most Ctrl+key shortcuts pass through vim mode to the keybinding system

373* In vim NORMAL mode, `?` shows the help menu (vim behavior)

374 

375## Validation

376 

377Claude Code validates your keybindings and shows warnings for:

378 

379* Parse errors (invalid JSON or structure)

380* Invalid context names

381* Reserved shortcut conflicts

382* Terminal multiplexer conflicts

383* Duplicate bindings in the same context

384 

385Run `/doctor` to see any keybinding warnings.

llm-gateway.md +4 −4

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# LLM gateway configuration5# LLM gateway configuration

2 6 

3> Learn how to configure Claude Code to work with LLM gateway solutions. Covers gateway requirements, authentication configuration, model selection, and provider-specific endpoint setup.7> Learn how to configure Claude Code to work with LLM gateway solutions. Covers gateway requirements, authentication configuration, model selection, and provider-specific endpoint setup.


168* [Claude Code settings](/en/settings)172* [Claude Code settings](/en/settings)

169* [Enterprise network configuration](/en/network-config)173* [Enterprise network configuration](/en/network-config)

170* [Third-party integrations overview](/en/third-party-integrations)174* [Third-party integrations overview](/en/third-party-integrations)

171 

172 

173 

174> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

mcp.md +237 −48

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Connect Claude Code to tools via MCP5# Connect Claude Code to tools via MCP

2 6 

3> Learn how to connect Claude Code to your tools with the Model Context Protocol.7> Learn how to connect Claude Code to your tools with the Model Context Protocol.


186 190 

187**Plugin MCP features**:191**Plugin MCP features**:

188 192 

189* **Automatic lifecycle**: Servers start when plugin enables, but you must restart Claude Code to apply MCP server changes (enabling or disabling)193* **Automatic lifecycle**: At session startup, servers for enabled plugins connect automatically. If you enable or disable a plugin during a session, run `/reload-plugins` to connect or disconnect its MCP servers

190* **Environment variables**: Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths194* **Environment variables**: Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths

191* **User environment access**: Access to same environment variables as manually configured servers195* **User environment access**: Access to same environment variables as manually configured servers

192* **Multiple transport types**: Support stdio, SSE, and HTTP transports (transport support may vary by server)196* **Multiple transport types**: Support stdio, SSE, and HTTP transports (transport support may vary by server)


323{/* ### Example: Automate browser testing with Playwright327{/* ### Example: Automate browser testing with Playwright

324 328 

325 ```bash329 ```bash

326 # 1. Add the Playwright MCP server

327 claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest330 claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest

331 ```

328 332 

329 # 2. Write and run browser tests333 Then write and run browser tests:

330 > "Test if the login flow works with test@example.com"334 

331 > "Take a screenshot of the checkout page on mobile"335 ```text

332 > "Verify that the search feature returns results"336 Test if the login flow works with test@example.com

337 ```

338 ```text

339 Take a screenshot of the checkout page on mobile

340 ```

341 ```text

342 Verify that the search feature returns results

333 ``` */}343 ``` */}

334 344 

335### Example: Monitor errors with Sentry345### Example: Monitor errors with Sentry

336 346 

337```bash theme={null}347```bash theme={null}

338# 1. Add the Sentry MCP server

339claude mcp add --transport http sentry https://mcp.sentry.dev/mcp348claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

349```

340 350 

341# 2. Use /mcp to authenticate with your Sentry account351Authenticate with your Sentry account:

342> /mcp

343 352 

344# 3. Debug production issues353```text theme={null}

345> "What are the most common errors in the last 24 hours?"354/mcp

346> "Show me the stack trace for error ID abc123"355```

347> "Which deployment introduced these new errors?"356 

357Then debug production issues:

358 

359```text theme={null}

360What are the most common errors in the last 24 hours?

361```

362 

363```text theme={null}

364Show me the stack trace for error ID abc123

365```

366 

367```text theme={null}

368Which deployment introduced these new errors?

348```369```

349 370 

350### Example: Connect to GitHub for code reviews371### Example: Connect to GitHub for code reviews

351 372 

352```bash theme={null}373```bash theme={null}

353# 1. Add the GitHub MCP server

354claude mcp add --transport http github https://api.githubcopilot.com/mcp/374claude mcp add --transport http github https://api.githubcopilot.com/mcp/

375```

355 376 

356# 2. In Claude Code, authenticate if needed377Authenticate if needed by selecting "Authenticate" for GitHub:

357> /mcp

358# Select "Authenticate" for GitHub

359 378 

360# 3. Now you can ask Claude to work with GitHub379```text theme={null}

361> "Review PR #456 and suggest improvements"380/mcp

362> "Create a new issue for the bug we just found"381```

363> "Show me all open PRs assigned to me"382 

383Then work with GitHub:

384 

385```text theme={null}

386Review PR #456 and suggest improvements

387```

388 

389```text theme={null}

390Create a new issue for the bug we just found

391```

392 

393```text theme={null}

394Show me all open PRs assigned to me

364```395```

365 396 

366### Example: Query your PostgreSQL database397### Example: Query your PostgreSQL database

367 398 

368```bash theme={null}399```bash theme={null}

369# 1. Add the database server with your connection string

370claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \400claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \

371 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"401 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"

402```

403 

404Then query your database naturally:

405 

406```text theme={null}

407What's our total revenue this month?

408```

409 

410```text theme={null}

411Show me the schema for the orders table

412```

372 413 

373# 2. Query your database naturally414```text theme={null}

374> "What's our total revenue this month?"415Find customers who haven't made a purchase in 90 days

375> "Show me the schema for the orders table"

376> "Find customers who haven't made a purchase in 90 days"

377```416```

378 417 

379## Authenticate with remote MCP servers418## Authenticate with remote MCP servers


392 <Step title="Use the /mcp command within Claude Code">431 <Step title="Use the /mcp command within Claude Code">

393 In Claude code, use the command:432 In Claude code, use the command:

394 433 

395 ```434 ```text theme={null}

396 > /mcp435 /mcp

397 ```436 ```

398 437 

399 Then follow the steps in your browser to login.438 Then follow the steps in your browser to login.


405 444 

406 * Authentication tokens are stored securely and refreshed automatically445 * Authentication tokens are stored securely and refreshed automatically

407 * Use "Clear authentication" in the `/mcp` menu to revoke access446 * Use "Clear authentication" in the `/mcp` menu to revoke access

408 * If your browser doesn't open automatically, copy the provided URL447 * If your browser doesn't open automatically, copy the provided URL and open it manually

448 * If the browser redirect fails with a connection error after authenticating, paste the full callback URL from your browser's address bar into the URL prompt that appears in Claude Code

409 * OAuth authentication works with HTTP servers449 * OAuth authentication works with HTTP servers

410</Tip>450</Tip>

411 451 

452### Use a fixed OAuth callback port

453 

454Some MCP servers require a specific redirect URI registered in advance. By default, Claude Code picks a random available port for the OAuth callback. Use `--callback-port` to fix the port so it matches a pre-registered redirect URI of the form `http://localhost:PORT/callback`.

455 

456You can use `--callback-port` on its own (with dynamic client registration) or together with `--client-id` (with pre-configured credentials).

457 

458```bash theme={null}

459# Fixed callback port with dynamic client registration

460claude mcp add --transport http \

461 --callback-port 8080 \

462 my-server https://mcp.example.com/mcp

463```

464 

465### Use pre-configured OAuth credentials

466 

467Some MCP servers don't support automatic OAuth setup. If you see an error like "Incompatible auth server: does not support dynamic client registration," the server requires pre-configured credentials. Register an OAuth app through the server's developer portal first, then provide the credentials when adding the server.

468 

469<Steps>

470 <Step title="Register an OAuth app with the server">

471 Create an app through the server's developer portal and note your client ID and client secret.

472 

473 Many servers also require a redirect URI. If so, choose a port and register a redirect URI in the format `http://localhost:PORT/callback`. Use that same port with `--callback-port` in the next step.

474 </Step>

475 

476 <Step title="Add the server with your credentials">

477 Choose one of the following methods. The port used for `--callback-port` can be any available port. It just needs to match the redirect URI you registered in the previous step.

478 

479 <Tabs>

480 <Tab title="claude mcp add">

481 Use `--client-id` to pass your app's client ID. The `--client-secret` flag prompts for the secret with masked input:

482 

483 ```bash theme={null}

484 claude mcp add --transport http \

485 --client-id your-client-id --client-secret --callback-port 8080 \

486 my-server https://mcp.example.com/mcp

487 ```

488 </Tab>

489 

490 <Tab title="claude mcp add-json">

491 Include the `oauth` object in the JSON config and pass `--client-secret` as a separate flag:

492 

493 ```bash theme={null}

494 claude mcp add-json my-server \

495 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \

496 --client-secret

497 ```

498 </Tab>

499 

500 <Tab title="claude mcp add-json (callback port only)">

501 Use `--callback-port` without a client ID to fix the port while using dynamic client registration:

502 

503 ```bash theme={null}

504 claude mcp add-json my-server \

505 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"callbackPort":8080}}'

506 ```

507 </Tab>

508 

509 <Tab title="CI / env var">

510 Set the secret via environment variable to skip the interactive prompt:

511 

512 ```bash theme={null}

513 MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \

514 --client-id your-client-id --client-secret --callback-port 8080 \

515 my-server https://mcp.example.com/mcp

516 ```

517 </Tab>

518 </Tabs>

519 </Step>

520 

521 <Step title="Authenticate in Claude Code">

522 Run `/mcp` in Claude Code and follow the browser login flow.

523 </Step>

524</Steps>

525 

526<Tip>

527 Tips:

528 

529 * The client secret is stored securely in your system keychain (macOS) or a credentials file, not in your config

530 * If the server uses a public OAuth client with no secret, use only `--client-id` without `--client-secret`

531 * `--callback-port` can be used with or without `--client-id`

532 * These flags only apply to HTTP and SSE transports. They have no effect on stdio servers

533 * Use `claude mcp get <name>` to verify that OAuth credentials are configured for a server

534</Tip>

535 

536### Override OAuth metadata discovery

537 

538If your MCP server returns errors on the standard OAuth metadata endpoint (`/.well-known/oauth-authorization-server`) but exposes a working OIDC endpoint, you can tell Claude Code to fetch OAuth metadata directly from a URL you specify, bypassing the standard discovery chain.

539 

540Set `authServerMetadataUrl` in the `oauth` object of your server's config in `.mcp.json`:

541 

542```json theme={null}

543{

544 "mcpServers": {

545 "my-server": {

546 "type": "http",

547 "url": "https://mcp.example.com/mcp",

548 "oauth": {

549 "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration"

550 }

551 }

552 }

553}

554```

555 

556The URL must use `https://`. This option requires Claude Code v2.1.64 or later.

557 

412## Add MCP servers from JSON configuration558## Add MCP servers from JSON configuration

413 559 

414If you have a JSON configuration for an MCP server, you can add it directly:560If you have a JSON configuration for an MCP server, you can add it directly:


424 570 

425 # Example: Adding a stdio server with JSON configuration571 # Example: Adding a stdio server with JSON configuration

426 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'572 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'

573 

574 # Example: Adding an HTTP server with pre-configured OAuth credentials

575 claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret

427 ```576 ```

428 </Step>577 </Step>

429 578 


475 * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)624 * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)

476</Tip>625</Tip>

477 626 

627## Use MCP servers from Claude.ai

628 

629If you've logged into Claude Code with a [Claude.ai](https://claude.ai) account, MCP servers you've added in Claude.ai are automatically available in Claude Code:

630 

631<Steps>

632 <Step title="Configure MCP servers in Claude.ai">

633 Add servers at [claude.ai/settings/connectors](https://claude.ai/settings/connectors). On Team and Enterprise plans, only admins can add servers.

634 </Step>

635 

636 <Step title="Authenticate the MCP server">

637 Complete any required authentication steps in Claude.ai.

638 </Step>

639 

640 <Step title="View and manage servers in Claude Code">

641 In Claude Code, use the command:

642 

643 ```text theme={null}

644 /mcp

645 ```

646 

647 Claude.ai servers appear in the list with indicators showing they come from Claude.ai.

648 </Step>

649</Steps>

650 

651To disable claude.ai MCP servers in Claude Code, set the `ENABLE_CLAUDEAI_MCP_SERVERS` environment variable to `false`:

652 

653```bash theme={null}

654ENABLE_CLAUDEAI_MCP_SERVERS=false claude

655```

656 

478## Use Claude Code as an MCP server657## Use Claude Code as an MCP server

479 658 

480You can use Claude Code itself as an MCP server that other applications can connect to:659You can use Claude Code itself as an MCP server that other applications can connect to:


560 If you frequently encounter output warnings with specific MCP servers, consider increasing the limit or configuring the server to paginate or filter its responses.739 If you frequently encounter output warnings with specific MCP servers, consider increasing the limit or configuring the server to paginate or filter its responses.

561</Warning>740</Warning>

562 741 

742## Respond to MCP elicitation requests

743 

744MCP servers can request structured input from you mid-task using elicitation. When a server needs information it can't get on its own, Claude Code displays an interactive dialog and passes your response back to the server. No configuration is required on your side: elicitation dialogs appear automatically when a server requests them.

745 

746Servers can request input in two ways:

747 

748* **Form mode**: Claude Code shows a dialog with form fields defined by the server (for example, a username and password prompt). Fill in the fields and submit.

749* **URL mode**: Claude Code opens a browser URL for authentication or approval. Complete the flow in the browser, then confirm in the CLI.

750 

751To auto-respond to elicitation requests without showing a dialog, use the [`Elicitation` hook](/en/hooks#elicitation).

752 

753If you're building an MCP server that uses elicitation, see the [MCP elicitation specification](https://modelcontextprotocol.io/docs/learn/client-concepts#elicitation) for protocol details and schema examples.

754 

563## Use MCP resources755## Use MCP resources

564 756 

565MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files.757MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files.


574 <Step title="Reference a specific resource">766 <Step title="Reference a specific resource">

575 Use the format `@server:protocol://resource/path` to reference a resource:767 Use the format `@server:protocol://resource/path` to reference a resource:

576 768 

577 ```769 ```text theme={null}

578 > Can you analyze @github:issue://123 and suggest a fix?770 Can you analyze @github:issue://123 and suggest a fix?

579 ```771 ```

580 772 

581 ```773 ```text theme={null}

582 > Please review the API documentation at @docs:file://api/authentication774 Please review the API documentation at @docs:file://api/authentication

583 ```775 ```

584 </Step>776 </Step>

585 777 

586 <Step title="Multiple resource references">778 <Step title="Multiple resource references">

587 You can reference multiple resources in a single prompt:779 You can reference multiple resources in a single prompt:

588 780 

589 ```781 ```text theme={null}

590 > Compare @postgres:schema://users with @docs:file://database/user-model782 Compare @postgres:schema://users with @docs:file://database/user-model

591 ```783 ```

592 </Step>784 </Step>

593</Steps>785</Steps>


626 818 

627### Configure tool search819### Configure tool search

628 820 

629Tool search runs in auto mode by default, meaning it activates only when your MCP tool definitions exceed the context threshold. If you have few tools, they load normally without tool search. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.821Tool search is enabled by default: MCP tools are deferred and discovered on demand. When `ANTHROPIC_BASE_URL` points to a non-first-party host, tool search is disabled by default because most proxies do not forward `tool_reference` blocks. Set `ENABLE_TOOL_SEARCH` explicitly if your proxy does. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.

630 822 

631Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:823Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:

632 824 

633| Value | Behavior |825| Value | Behavior |

634| :--------- | :--------------------------------------------------------------------------------- |826| :--------- | :--------------------------------------------------------------------------------- |

635| `auto` | Activates when MCP tools exceed 10% of context (default) |827| (unset) | Enabled by default. Disabled when `ANTHROPIC_BASE_URL` is a non-first-party host |

828| `true` | Always enabled, including for non-first-party `ANTHROPIC_BASE_URL` |

829| `auto` | Activates when MCP tools exceed 10% of context |

636| `auto:<N>` | Activates at custom threshold, where `<N>` is a percentage (e.g., `auto:5` for 5%) |830| `auto:<N>` | Activates at custom threshold, where `<N>` is a percentage (e.g., `auto:5` for 5%) |

637| `true` | Always enabled |

638| `false` | Disabled, all MCP tools loaded upfront |831| `false` | Disabled, all MCP tools loaded upfront |

639 832 

640```bash theme={null}833```bash theme={null}


669 </Step>862 </Step>

670 863 

671 <Step title="Execute a prompt without arguments">864 <Step title="Execute a prompt without arguments">

672 ```865 ```text theme={null}

673 > /mcp__github__list_prs866 /mcp__github__list_prs

674 ```867 ```

675 </Step>868 </Step>

676 869 

677 <Step title="Execute a prompt with arguments">870 <Step title="Execute a prompt with arguments">

678 Many prompts accept arguments. Pass them space-separated after the command:871 Many prompts accept arguments. Pass them space-separated after the command:

679 872 

680 ```873 ```text theme={null}

681 > /mcp__github__pr_review 456874 /mcp__github__pr_review 456

682 ```875 ```

683 876 

684 ```877 ```text theme={null}

685 > /mcp__jira__create_issue "Bug in login flow" high878 /mcp__jira__create_issue "Bug in login flow" high

686 ```879 ```

687 </Step>880 </Step>

688</Steps>881</Steps>


923<Note>1116<Note>

924 **When using `managed-mcp.json`**: Users cannot add MCP servers through `claude mcp add` or configuration files. The `allowedMcpServers` and `deniedMcpServers` settings still apply to filter which managed servers are actually loaded.1117 **When using `managed-mcp.json`**: Users cannot add MCP servers through `claude mcp add` or configuration files. The `allowedMcpServers` and `deniedMcpServers` settings still apply to filter which managed servers are actually loaded.

925</Note>1118</Note>

926 

927 

928 

929> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

memory.md +244 −109

Details

1# Manage Claude's memory1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.5# How Claude remembers your project

4 6 

5Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow.7> Give Claude persistent instructions with CLAUDE.md files, and let Claude accumulate learnings automatically with auto memory.

6 8 

7## Determine memory type9Each Claude Code session begins with a fresh context window. Two mechanisms carry knowledge across sessions:

8 10 

9Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose:11* **CLAUDE.md files**: instructions you write to give Claude persistent context

12* **Auto memory**: notes Claude writes itself based on your corrections and preferences

10 13 

11| Memory Type | Location | Purpose | Use Case Examples | Shared With |14This page covers how to:

12| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |

13| **Managed policy** | • macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />• Linux: `/etc/claude-code/CLAUDE.md`<br />• Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |

14| **Project memory** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |

15| **Project rules** | `./.claude/rules/*.md` | Modular, topic-specific project instructions | Language-specific guidelines, testing conventions, API standards | Team members via source control |

16| **User memory** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |

17| **Project memory (local)** | `./CLAUDE.local.md` | Personal project-specific preferences | Your sandbox URLs, preferred test data | Just you (current project) |

18 15 

19All 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.16* [Write and organize CLAUDE.md files](#claudemd-files)

17* [Scope rules to specific file types](#organize-rules-with-clauderules) with `.claude/rules/`

18* [Configure auto memory](#auto-memory) so Claude takes notes automatically

19* [Troubleshoot](#troubleshoot-memory-issues) when instructions aren't being followed

20 20 

21<Note>21## CLAUDE.md vs auto memory

22 CLAUDE.local.md files are automatically added to .gitignore, making them ideal for private project-specific preferences that shouldn't be checked into version control.

23</Note>

24 22 

25## CLAUDE.md imports23Claude Code has two complementary memory systems. Both are loaded at the start of every conversation. Claude treats them as context, not enforced configuration. The more specific and concise your instructions, the more consistently Claude follows them.

26 24 

27CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files:25| | CLAUDE.md files | Auto memory |

26| :------------------- | :------------------------------------------------ | :--------------------------------------------------------------- |

27| **Who writes it** | You | Claude |

28| **What it contains** | Instructions and rules | Learnings and patterns |

29| **Scope** | Project, user, or org | Per working tree |

30| **Loaded into** | Every session | Every session (first 200 lines) |

31| **Use for** | Coding standards, workflows, project architecture | Build commands, debugging insights, preferences Claude discovers |

28 32 

29```33Use CLAUDE.md files when you want to guide Claude's behavior. Auto memory lets Claude learn from your corrections without manual effort.

34 

35Subagents can also maintain their own auto memory. See [subagent configuration](/en/sub-agents#enable-persistent-memory) for details.

36 

37## CLAUDE.md files

38 

39CLAUDE.md files are markdown files that give Claude persistent instructions for a project, your personal workflow, or your entire organization. You write these files in plain text; Claude reads them at the start of every session.

40 

41### Choose where to put CLAUDE.md files

42 

43CLAUDE.md files can live in several locations, each with a different scope. More specific locations take precedence over broader ones.

44 

45| Scope | Location | Purpose | Use case examples | Shared with |

46| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |

47| **Managed policy** | • macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />• Linux and WSL: `/etc/claude-code/CLAUDE.md`<br />• Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |

48| **Project instructions** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |

49| **User instructions** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |

50 

51CLAUDE.md files in the directory hierarchy above the working directory are loaded in full at launch. CLAUDE.md files in subdirectories load on demand when Claude reads files in those directories. See [How CLAUDE.md files load](#how-claudemd-files-load) for the full resolution order.

52 

53For large projects, you can break instructions into topic-specific files using [project rules](#organize-rules-with-clauderules). Rules let you scope instructions to specific file types or subdirectories.

54 

55### Set up a project CLAUDE.md

56 

57A project CLAUDE.md can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`. Create this file and add instructions that apply to anyone working on the project: build and test commands, coding standards, architectural decisions, naming conventions, and common workflows. These instructions are shared with your team through version control, so focus on project-level standards rather than personal preferences.

58 

59<Tip>

60 Run `/init` to generate a starting CLAUDE.md automatically. Claude analyzes your codebase and creates a file with build commands, test instructions, and project conventions it discovers. If a CLAUDE.md already exists, `/init` suggests improvements rather than overwriting it. Refine from there with instructions Claude wouldn't discover on its own.

61</Tip>

62 

63### Write effective instructions

64 

65CLAUDE.md files are loaded into the context window at the start of every session, consuming tokens alongside your conversation. Because they're context rather than enforced configuration, how you write instructions affects how reliably Claude follows them. Specific, concise, well-structured instructions work best.

66 

67**Size**: target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence. If your instructions are growing large, split them using [imports](#import-additional-files) or [`.claude/rules/`](#organize-rules-with-clauderules) files.

68 

69**Structure**: use markdown headers and bullets to group related instructions. Claude scans structure the same way readers do: organized sections are easier to follow than dense paragraphs.

70 

71**Specificity**: write instructions that are concrete enough to verify. For example:

72 

73* "Use 2-space indentation" instead of "Format code properly"

74* "Run `npm test` before committing" instead of "Test your changes"

75* "API handlers live in `src/api/handlers/`" instead of "Keep files organized"

76 

77**Consistency**: if two rules contradict each other, Claude may pick one arbitrarily. Review your CLAUDE.md files, nested CLAUDE.md files in subdirectories, and [`.claude/rules/`](#organize-rules-with-clauderules) periodically to remove outdated or conflicting instructions. In monorepos, use [`claudeMdExcludes`](#exclude-specific-claudemd-files) to skip CLAUDE.md files from other teams that aren't relevant to your work.

78 

79### Import additional files

80 

81CLAUDE.md files can import additional files using `@path/to/import` syntax. Imported files are expanded and loaded into context at launch alongside the CLAUDE.md that references them.

82 

83Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. Imported files can recursively import other files, with a maximum depth of five hops.

84 

85To pull in a README, package.json, and a workflow guide, reference them with `@` syntax anywhere in your CLAUDE.md:

86 

87```text theme={null}

30See @README for project overview and @package.json for available npm commands for this project.88See @README for project overview and @package.json for available npm commands for this project.

31 89 

32# Additional Instructions90# Additional Instructions

33- git workflow @docs/git-instructions.md91- git workflow @docs/git-instructions.md

34```92```

35 93 

36Both relative and absolute paths are allowed. In particular, importing files in user's home dir is a convenient way for your team members to provide individual instructions that are not checked into the repository. Imports are an alternative to CLAUDE.local.md that work better across multiple git worktrees.94For personal preferences you don't want to check in, import a file from your home directory. The import goes in the shared CLAUDE.md, but the file it points to stays on your machine:

37 95 

38```96```text theme={null}

39# Individual Preferences97# Individual Preferences

40- @~/.claude/my-project-instructions.md98- @~/.claude/my-project-instructions.md

41```99```

42 100 

43To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.101<Warning>

102 The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the files. If you decline, the imports stay disabled and the dialog does not appear again.

103</Warning>

44 104 

45```105For a more structured approach to organizing instructions, see [`.claude/rules/`](#organize-rules-with-clauderules).

46This code span will not be treated as an import: `@anthropic-ai/claude-code`

47```

48 106 

49Imported files can recursively import additional files, with a max-depth of 5 hops. You can see what memory files are loaded by running `/memory` command.107### How CLAUDE.md files load

50 108 

51## How Claude looks up memories109Claude Code reads CLAUDE.md files by walking up the directory tree from your current working directory, checking each directory along the way. This means if you run Claude Code in `foo/bar/`, it loads instructions from both `foo/bar/CLAUDE.md` and `foo/CLAUDE.md`.

52 110 

53Claude Code reads memories recursively: starting in the cwd, Claude Code recurses up to (but not including) the root directory */* and reads any CLAUDE.md or CLAUDE.local.md files it finds. This is especially convenient when working in large repositories where you run Claude Code in *foo/bar/*, and have memories in both *foo/CLAUDE.md* and *foo/bar/CLAUDE.md*.111Claude also discovers CLAUDE.md files in subdirectories under your current working directory. Instead of loading them at launch, they are included when Claude reads files in those subdirectories.

54 112 

55Claude will also discover CLAUDE.md nested in subtrees under your current working directory. Instead of loading them at launch, they are only included when Claude reads files in those subtrees.113If you work in a large monorepo where other teams' CLAUDE.md files get picked up, use [`claudeMdExcludes`](#exclude-specific-claudemd-files) to skip them.

56 114 

57## Directly edit memories with `/memory`115#### Load from additional directories

58 116 

59Use the `/memory` command during a session to open any memory file in your system editor for more extensive additions or organization.117The `--add-dir` flag gives Claude access to additional directories outside your main working directory. By default, CLAUDE.md files from these directories are not loaded.

60 118 

61## Set up project memory119To also load CLAUDE.md files from additional directories, including `CLAUDE.md`, `.claude/CLAUDE.md`, and `.claude/rules/*.md`, set the `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable:

62 120 

63Suppose you want to set up a CLAUDE.md file to store important project information, conventions, and frequently used commands. Project memory can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`.121```bash theme={null}

64 122CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config

65Bootstrap a CLAUDE.md for your codebase with the following command:

66 

67```

68> /init

69```123```

70 124 

71<Tip>125### Organize rules with `.claude/rules/`

72 Tips:

73 

74 * Include frequently used commands (build, test, lint) to avoid repeated searches

75 * Document code style preferences and naming conventions

76 * Add important architectural patterns specific to your project

77 * CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences.

78</Tip>

79 126 

80## Modular rules with `.claude/rules/`127For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This keeps instructions modular and easier for teams to maintain. Rules can also be [scoped to specific file paths](#path-specific-rules), so they only load into context when Claude works with matching files, reducing noise and saving context space.

81 128 

82For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This allows teams to maintain focused, well-organized rule files instead of one large CLAUDE.md.129<Note>

130 Rules load into context every session or when matching files are opened. For task-specific instructions that don't need to be in context all the time, use [skills](/en/skills) instead, which only load when you invoke them or when Claude determines they're relevant to your prompt.

131</Note>

83 132 

84### Basic structure133#### Set up rules

85 134 

86Place markdown files in your project's `.claude/rules/` directory:135Place markdown files in your project's `.claude/rules/` directory. Each file should cover one topic, with a descriptive filename like `testing.md` or `api-design.md`. All `.md` files are discovered recursively, so you can organize rules into subdirectories like `frontend/` or `backend/`:

87 136 

88```137```text theme={null}

89your-project/138your-project/

90├── .claude/139├── .claude/

91│ ├── CLAUDE.md # Main project instructions140│ ├── CLAUDE.md # Main project instructions


95│ └── security.md # Security requirements144│ └── security.md # Security requirements

96```145```

97 146 

98All `.md` files in `.claude/rules/` are automatically loaded as project memory, with the same priority as `.claude/CLAUDE.md`.147Rules without [`paths` frontmatter](#path-specific-rules) are loaded at launch with the same priority as `.claude/CLAUDE.md`.

99 148 

100### Path-specific rules149#### Path-specific rules

101 150 

102Rules can be scoped to specific files using YAML frontmatter with the `paths` field. These conditional rules only apply when Claude is working with files matching the specified patterns.151Rules can be scoped to specific files using YAML frontmatter with the `paths` field. These conditional rules only apply when Claude is working with files matching the specified patterns.

103 152 


114- Include OpenAPI documentation comments163- Include OpenAPI documentation comments

115```164```

116 165 

117Rules without a `paths` field are loaded unconditionally and apply to all files.166Rules without a `paths` field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use.

118 

119### Glob patterns

120 167 

121The `paths` field supports standard glob patterns:168Use glob patterns in the `paths` field to match files by extension, directory, or any combination:

122 169 

123| Pattern | Matches |170| Pattern | Matches |

124| ---------------------- | ---------------------------------------- |171| ---------------------- | ---------------------------------------- |


127| `*.md` | Markdown files in the project root |174| `*.md` | Markdown files in the project root |

128| `src/components/*.tsx` | React components in a specific directory |175| `src/components/*.tsx` | React components in a specific directory |

129 176 

130You can specify multiple patterns:177You can specify multiple patterns and use brace expansion to match multiple extensions in one pattern:

131 178 

132```markdown theme={null}179```markdown theme={null}

133---180---

134paths:181paths:

135 - "src/**/*.ts"182 - "src/**/*.{ts,tsx}"

136 - "lib/**/*.ts"183 - "lib/**/*.ts"

137 - "tests/**/*.test.ts"184 - "tests/**/*.test.ts"

138---185---

139```186```

140 187 

141Brace expansion is supported for matching multiple extensions or directories:188#### Share rules across projects with symlinks

142 189 

143```markdown theme={null}190The `.claude/rules/` directory supports symlinks, so you can maintain a shared set of rules and link them into multiple projects. Symlinks are resolved and loaded normally, and circular symlinks are detected and handled gracefully.

144paths:

145 - "src/**/*.{ts,tsx}"

146 - "{src,lib}/**/*.ts"

147 191 

148# TypeScript/React Rules192This example links both a shared directory and an individual file:

149```

150 193 

151This expands `src/**/*.{ts,tsx}` to match both `.ts` and `.tsx` files.194```bash theme={null}

195ln -s ~/shared-claude-rules .claude/rules/shared

196ln -s ~/company-standards/security.md .claude/rules/security.md

197```

152 198 

153### Subdirectories199#### User-level rules

154 200 

155Rules can be organized into subdirectories for better structure:201Personal rules in `~/.claude/rules/` apply to every project on your machine. Use them for preferences that aren't project-specific:

156 202 

203```text theme={null}

204~/.claude/rules/

205├── preferences.md # Your personal coding preferences

206└── workflows.md # Your preferred workflows

157```207```

158.claude/rules/208 

159├── frontend/209User-level rules are loaded before project rules, giving project rules higher priority.

160│ ├── react.md210 

161│ └── styles.md211### Manage CLAUDE.md for large teams

162├── backend/212 

163│ ├── api.md213For organizations deploying Claude Code across teams, you can centralize instructions and control which CLAUDE.md files are loaded.

164│ └── database.md214 

165└── general.md215#### Deploy organization-wide CLAUDE.md

216 

217Organizations can deploy a centrally managed CLAUDE.md that applies to all users on a machine. This file cannot be excluded by individual settings.

218 

219<Steps>

220 <Step title="Create the file at the managed policy location">

221 * macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`

222 * Linux and WSL: `/etc/claude-code/CLAUDE.md`

223 * Windows: `C:\Program Files\ClaudeCode\CLAUDE.md`

224 </Step>

225 

226 <Step title="Deploy with your configuration management system">

227 Use MDM, Group Policy, Ansible, or similar tools to distribute the file across developer machines. See [managed settings](/en/permissions#managed-settings) for other organization-wide configuration options.

228 </Step>

229</Steps>

230 

231#### Exclude specific CLAUDE.md files

232 

233In large monorepos, ancestor CLAUDE.md files may contain instructions that aren't relevant to your work. The `claudeMdExcludes` setting lets you skip specific files by path or glob pattern.

234 

235This example excludes a top-level CLAUDE.md and a rules directory from a parent folder. Add it to `.claude/settings.local.json` so the exclusion stays local to your machine:

236 

237```json theme={null}

238{

239 "claudeMdExcludes": [

240 "**/monorepo/CLAUDE.md",

241 "/home/user/monorepo/other-team/.claude/rules/**"

242 ]

243}

166```244```

167 245 

168All `.md` files are discovered recursively.246Patterns are matched against absolute file paths using glob syntax. You can configure `claudeMdExcludes` at any [settings layer](/en/settings#settings-files): user, project, local, or managed policy. Arrays merge across layers.

169 247 

170### Symlinks248Managed policy CLAUDE.md files cannot be excluded. This ensures organization-wide instructions always apply regardless of individual settings.

171 249 

172The `.claude/rules/` directory supports symlinks, allowing you to share common rules across multiple projects:250## Auto memory

173 251 

174```bash theme={null}252Auto memory lets Claude accumulate knowledge across sessions without you writing anything. Claude saves notes for itself as it works: build commands, debugging insights, architecture notes, code style preferences, and workflow habits. Claude doesn't save something every session. It decides what's worth remembering based on whether the information would be useful in a future conversation.

175# Symlink a shared rules directory

176ln -s ~/shared-claude-rules .claude/rules/shared

177 253 

178# Symlink individual rule files254<Note>

179ln -s ~/company-standards/security.md .claude/rules/security.md255 Auto memory requires Claude Code v2.1.59 or later. Check your version with `claude --version`.

256</Note>

257 

258### Enable or disable auto memory

259 

260Auto memory is on by default. To toggle it, open `/memory` in a session and use the auto memory toggle, or set `autoMemoryEnabled` in your project settings:

261 

262```json theme={null}

263{

264 "autoMemoryEnabled": false

265}

180```266```

181 267 

182Symlinks are resolved and their contents are loaded normally. Circular symlinks are detected and handled gracefully.268To disable auto memory via environment variable, set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`.

183 269 

184### User-level rules270### Storage location

185 271 

186You can create personal rules that apply to all your projects in `~/.claude/rules/`:272Each project gets its own memory directory at `~/.claude/projects/<project>/memory/`. The `<project>` path is derived from the git repository, so all worktrees and subdirectories within the same repo share one auto memory directory. Outside a git repo, the project root is used instead.

187 273 

274To store auto memory in a different location, set `autoMemoryDirectory` in your user or local settings:

275 

276```json theme={null}

277{

278 "autoMemoryDirectory": "~/my-custom-memory-dir"

279}

188```280```

189~/.claude/rules/281 

190├── preferences.md # Your personal coding preferences282This setting is accepted from policy, local, and user settings. It is not accepted from project settings (`.claude/settings.json`) to prevent a shared project from redirecting auto memory writes to sensitive locations.

191└── workflows.md # Your preferred workflows283 

284The directory contains a `MEMORY.md` entrypoint and optional topic files:

285 

286```text theme={null}

287~/.claude/projects/<project>/memory/

288├── MEMORY.md # Concise index, loaded into every session

289├── debugging.md # Detailed notes on debugging patterns

290├── api-conventions.md # API design decisions

291└── ... # Any other topic files Claude creates

192```292```

193 293 

194User-level rules are loaded before project rules, giving project rules higher priority.294`MEMORY.md` acts as an index of the memory directory. Claude reads and writes files in this directory throughout your session, using `MEMORY.md` to keep track of what's stored where.

195 295 

196<Tip>296Auto memory is machine-local. All worktrees and subdirectories within the same git repository share one auto memory directory. Files are not shared across machines or cloud environments.

197 Best practices for `.claude/rules/`:

198 297 

199 * **Keep rules focused**: Each file should cover one topic (e.g., `testing.md`, `api-design.md`)298### How it works

200 * **Use descriptive filenames**: The filename should indicate what the rules cover

201 * **Use conditional rules sparingly**: Only add `paths` frontmatter when rules truly apply to specific file types

202 * **Organize with subdirectories**: Group related rules (e.g., `frontend/`, `backend/`)

203</Tip>

204 299 

205## Organization-level memory management300The first 200 lines of `MEMORY.md` are loaded at the start of every conversation. Content beyond line 200 is not loaded at session start. Claude keeps `MEMORY.md` concise by moving detailed notes into separate topic files.

206 301 

207Organizations can deploy centrally managed CLAUDE.md files that apply to all users.302This 200-line limit applies only to `MEMORY.md`. CLAUDE.md files are loaded in full regardless of length, though shorter files produce better adherence.

208 303 

209To set up organization-level memory management:304Topic files like `debugging.md` or `patterns.md` are not loaded at startup. Claude reads them on demand using its standard file tools when it needs the information.

210 305 

2111. Create the managed memory file at the **Managed policy** location shown in the [memory types table above](#determine-memory-type).306Claude reads and writes memory files during your session. When you see "Writing memory" or "Recalled memory" in the Claude Code interface, Claude is actively updating or reading from `~/.claude/projects/<project>/memory/`.

212 307 

2132. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines.308### Audit and edit your memory

214 309 

215## Memory best practices310Auto memory files are plain markdown you can edit or delete at any time. Run [`/memory`](#view-and-edit-with-memory) to browse and open memory files from within a session.

216 311 

217* **Be specific**: "Use 2-space indentation" is better than "Format code properly".312## View and edit with `/memory`

218* **Use structure to organize**: Format each individual memory as a bullet point and group related memories under descriptive markdown headings.

219* **Review periodically**: Update memories as your project evolves to ensure Claude is always using the most up to date information and context.

220 313 

314The `/memory` command lists all CLAUDE.md and rules files loaded in your current session, lets you toggle auto memory on or off, and provides a link to open the auto memory folder. Select any file to open it in your editor.

221 315 

316When you ask Claude to remember something, like "always use pnpm, not npm" or "remember that the API tests require a local Redis instance," Claude saves it to auto memory. To add instructions to CLAUDE.md instead, ask Claude directly, like "add this to CLAUDE.md," or edit the file yourself via `/memory`.

317 

318## Troubleshoot memory issues

319 

320These are the most common issues with CLAUDE.md and auto memory, along with steps to debug them.

321 

322### Claude isn't following my CLAUDE.md

323 

324CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself. Claude reads it and tries to follow it, but there's no guarantee of strict compliance, especially for vague or conflicting instructions.

325 

326To debug:

327 

328* Run `/memory` to verify your CLAUDE.md files are being loaded. If a file isn't listed, Claude can't see it.

329* Check that the relevant CLAUDE.md is in a location that gets loaded for your session (see [Choose where to put CLAUDE.md files](#choose-where-to-put-claudemd-files)).

330* Make instructions more specific. "Use 2-space indentation" works better than "format code nicely."

331* Look for conflicting instructions across CLAUDE.md files. If two files give different guidance for the same behavior, Claude may pick one arbitrarily.

332 

333For instructions you want at the system prompt level, use [`--append-system-prompt`](/en/cli-reference#system-prompt-flags). This must be passed every invocation, so it's better suited to scripts and automation than interactive use.

334 

335<Tip>

336 Use the [`InstructionsLoaded` hook](/en/hooks#instructionsloaded) to log exactly which instruction files are loaded, when they load, and why. This is useful for debugging path-specific rules or lazy-loaded files in subdirectories.

337</Tip>

338 

339### I don't know what auto memory saved

340 

341Run `/memory` and select the auto memory folder to browse what Claude has saved. Everything is plain markdown you can read, edit, or delete.

342 

343### My CLAUDE.md is too large

344 

345Files over 200 lines consume more context and may reduce adherence. Move detailed content into separate files referenced with `@path` imports (see [Import additional files](#import-additional-files)), or split your instructions across `.claude/rules/` files.

346 

347### Instructions seem lost after `/compact`

348 

349CLAUDE.md fully survives compaction. After `/compact`, Claude re-reads your CLAUDE.md from disk and re-injects it fresh into the session. If an instruction disappeared after compaction, it was given only in conversation, not written to CLAUDE.md. Add it to CLAUDE.md to make it persist across sessions.

350 

351See [Write effective instructions](#write-effective-instructions) for guidance on size, structure, and specificity.

352 

353## Related resources

222 354 

223> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt355* [Skills](/en/skills): package repeatable workflows that load on demand

356* [Settings](/en/settings): configure Claude Code behavior with settings files

357* [Manage sessions](/en/sessions): manage context, resume conversations, and run parallel sessions

358* [Subagent memory](/en/sub-agents#enable-persistent-memory): let subagents maintain their own auto memory

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code on Microsoft Foundry5# Claude Code on Microsoft Foundry

2 6 

3> Learn about configuring Claude Code through Microsoft Foundry, including setup, configuration, and troubleshooting.7> Learn about configuring Claude Code through Microsoft Foundry, including setup, configuration, and troubleshooting.


10* RBAC permissions to create Microsoft Foundry resources and deployments14* RBAC permissions to create Microsoft Foundry resources and deployments

11* Azure CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials)15* Azure CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials)

12 16 

17<Note>

18 If you are deploying Claude Code to multiple users, [pin your model versions](#4-pin-model-versions) to prevent breakage when Anthropic releases new models.

19</Note>

20 

13## Setup21## Setup

14 22 

15### 1. Provision Microsoft Foundry resource23### 1. Provision Microsoft Foundry resource


55 63 

56### 3. Configure Claude Code64### 3. Configure Claude Code

57 65 

58Set the following environment variables to enable Microsoft Foundry. Note that your deployments' names are set as the model identifiers in Claude Code (may be optional if using suggested deployment names).66Set the following environment variables to enable Microsoft Foundry:

59 67 

60```bash theme={null}68```bash theme={null}

61# Enable Microsoft Foundry integration69# Enable Microsoft Foundry integration


64# Azure resource name (replace {resource} with your resource name)72# Azure resource name (replace {resource} with your resource name)

65export ANTHROPIC_FOUNDRY_RESOURCE={resource}73export ANTHROPIC_FOUNDRY_RESOURCE={resource}

66# Or provide the full base URL:74# Or provide the full base URL:

67# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com75# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com/anthropic

76```

77 

78### 4. Pin model versions

68 79 

69# Set models to your resource's deployment names80<Warning>

70export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-5'81 Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn't available in your Foundry account, breaking existing users when Anthropic releases updates. When you create Azure deployments, select a specific model version rather than "auto-update to latest."

82</Warning>

83 

84Set the model variables to match the deployment names you created in step 1:

85 

86```bash theme={null}

87export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'

88export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

71export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'89export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'

72export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-1'

73```90```

74 91 

75For more details on model configuration options, see [Model configuration](/en/model-config).92For current and legacy model IDs, see [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables.

76 93 

77## Azure RBAC configuration94## Azure RBAC configuration

78 95 


105* [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)122* [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)

106* [Microsoft Foundry models](https://ai.azure.com/explore/models)123* [Microsoft Foundry models](https://ai.azure.com/explore/models)

107* [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)124* [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)

108 

109 

110 

111> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

model-config.md +160 −23

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Model configuration5# Model configuration

2 6 

3> Learn about the Claude Code model configuration, including model aliases like `opusplan`7> Learn about the Claude Code model configuration, including model aliases like `opusplan`


8 12 

9* A **model alias**13* A **model alias**

10* A **model name**14* A **model name**

11 * Anthropic API: A full **[model name](https://docs.claude.com/en/docs/about-claude/models/overview#model-names)**15 * Anthropic API: A full **[model name](https://platform.claude.com/docs/en/about-claude/models/overview)**

12 * Bedrock: an inference profile ARN16 * Bedrock: an inference profile ARN

13 * Foundry: a deployment name17 * Foundry: a deployment name

14 * Vertex: a version name18 * Vertex: a version name


19remembering exact version numbers:23remembering exact version numbers:

20 24 

21| Model alias | Behavior |25| Model alias | Behavior |

22| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |26| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

23| **`default`** | Recommended model setting, depending on your account type |27| **`default`** | Recommended model setting, depending on your account type |

24| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.5) for daily coding tasks |28| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.6) for daily coding tasks |

25| **`opus`** | Uses Opus model (currently Opus 4.5) for specialized complex reasoning tasks |29| **`opus`** | Uses the latest Opus model (currently Opus 4.6) for complex reasoning tasks |

26| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |30| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |

27| **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) window for long sessions |31| **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions |

32| **`opus[1m]`** | Uses Opus with a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions |

28| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |33| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |

29 34 

35Aliases always point to the latest version. To pin to a specific version, use the full model name (for example, `claude-opus-4-6`) or set the corresponding environment variable like `ANTHROPIC_DEFAULT_OPUS_MODEL`.

36 

30### Setting your model37### Setting your model

31 38 

32You can configure your model in several ways, listed in order of priority:39You can configure your model in several ways, listed in order of priority:


49 56 

50Example settings file:57Example settings file:

51 58 

52```59```json theme={null}

53{60{

54 "permissions": {61 "permissions": {

55 ...62 ...


58}65}

59```66```

60 67 

68## Restrict model selection

69 

70Enterprise administrators can use `availableModels` in [managed or policy settings](/en/settings#settings-files) to restrict which models users can select.

71 

72When `availableModels` is set, users cannot switch to models not in the list via `/model`, `--model` flag, Config tool, or `ANTHROPIC_MODEL` environment variable.

73 

74```json theme={null}

75{

76 "availableModels": ["sonnet", "haiku"]

77}

78```

79 

80### Default model behavior

81 

82The Default option in the model picker is not affected by `availableModels`. It always remains available and represents the system's runtime default [based on the user's subscription tier](#default-model-setting).

83 

84Even with `availableModels: []`, users can still use Claude Code with the Default model for their tier.

85 

86### Control the model users run on

87 

88To fully control the model experience, use `availableModels` together with the `model` setting:

89 

90* **availableModels**: restricts what users can switch to

91* **model**: sets the explicit model override, taking precedence over the Default

92 

93This example ensures all users run Sonnet 4.6 and can only choose between Sonnet and Haiku:

94 

95```json theme={null}

96{

97 "model": "sonnet",

98 "availableModels": ["sonnet", "haiku"]

99}

100```

101 

102### Merge behavior

103 

104When `availableModels` is set at multiple levels, such as user settings and project settings, arrays are merged and deduplicated. To enforce a strict allowlist, set `availableModels` in managed or policy settings which take highest priority.

105 

61## Special model behavior106## Special model behavior

62 107 

63### `default` model setting108### `default` model setting

64 109 

65The behavior of `default` depends on your account type.110The behavior of `default` depends on your account type:

111 

112* **Max and Team Premium**: defaults to Opus 4.6

113* **Pro and Team Standard**: defaults to Sonnet 4.6

114* **Enterprise**: Opus 4.6 is available but not the default

66 115 

67For certain Max users, Claude Code will automatically fall back to Sonnet if you116Claude Code may automatically fall back to Sonnet if you hit a usage threshold with Opus.

68hit a usage threshold with Opus.

69 117 

70### `opusplan` model setting118### `opusplan` model setting

71 119 


79This gives you the best of both worlds: Opus's superior reasoning for planning,127This gives you the best of both worlds: Opus's superior reasoning for planning,

80and Sonnet's efficiency for execution.128and Sonnet's efficiency for execution.

81 129 

82### Extended context with \[1m]130### Adjust effort level

131 

132[Effort levels](https://platform.claude.com/docs/en/build-with-claude/effort) control adaptive reasoning, which dynamically allocates thinking based on task complexity. Lower effort is faster and cheaper for straightforward tasks, while higher effort provides deeper reasoning for complex problems.

133 

134Three levels persist across sessions: **low**, **medium**, and **high**. A fourth level, **max**, provides the deepest reasoning with no constraint on token spending, so responses are slower and cost more than at `high`. `max` is available on Opus 4.6 only and applies to the current session without persisting. Opus 4.6 defaults to medium effort for Max and Team subscribers.

135 

136**Setting effort:**

137 

138* **`/effort`**: run `/effort low`, `/effort medium`, `/effort high`, or `/effort max` to change the level, or `/effort auto` to reset to the model default

139* **In `/model`**: use left/right arrow keys to adjust the effort slider when selecting a model

140* **`--effort` flag**: pass `low`, `medium`, `high`, or `max` to set the level for a single session when launching Claude Code

141* **Environment variable**: set `CLAUDE_CODE_EFFORT_LEVEL` to `low`, `medium`, `high`, `max`, or `auto`

142* **Settings**: set `effortLevel` in your settings file to `"low"`, `"medium"`, or `"high"`

143 

144The environment variable takes precedence, then your configured level, then the model default.

145 

146Effort is supported on Opus 4.6 and Sonnet 4.6. The effort slider appears in `/model` when a supported model is selected. The current effort level is also displayed next to the logo and spinner, for example "with low effort", so you can confirm which setting is active without opening `/model`.

147 

148To disable adaptive reasoning on Opus 4.6 and Sonnet 4.6 and revert to the previous fixed thinking budget, set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1`. When disabled, these models use the fixed budget controlled by `MAX_THINKING_TOKENS`. See [environment variables](/en/env-vars).

149 

150### Extended context

151 

152Opus 4.6 and Sonnet 4.6 support a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions with large codebases.

153 

154Availability varies by model and plan. On Max, Team, and Enterprise plans, Opus is automatically upgraded to 1M context with no additional configuration. This applies to both Team Standard and Team Premium seats.

83 155 

84For Console/API users, the `[1m]` suffix can be added to full model names to156| Plan | Opus 4.6 with 1M context | Sonnet 4.6 with 1M context |

85enable a157| ------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |

86[1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window).158| Max, Team, and Enterprise | Included with subscription | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

159| Pro | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

160| API and pay-as-you-go | Full access | Full access |

161 

162To disable 1M context entirely, set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. This removes 1M model variants from the model picker. See [environment variables](/en/env-vars).

163 

164The 1M context window uses standard model pricing with no premium for tokens beyond 200K. For plans where extended context is included with your subscription, usage remains covered by your subscription. For plans that access extended context through extra usage, tokens are billed to extra usage.

165 

166If your account supports 1M context, the option appears in the model picker (`/model`) in the latest versions of Claude Code. If you don't see it, try restarting your session.

167 

168You can also use the `[1m]` suffix with model aliases or full model names:

87 169 

88```bash theme={null}170```bash theme={null}

89# Example of using a full model name with the [1m] suffix171# Use the opus[1m] or sonnet[1m] alias

90/model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]172/model opus[1m]

91```173/model sonnet[1m]

92 174 

93Note: Extended context models have175# Or append [1m] to a full model name

94[different pricing](https://docs.claude.com/en/docs/about-claude/pricing#long-context-pricing).176/model claude-opus-4-6[1m]

177```

95 178 

96## Checking your current model179## Checking your current model

97 180 


115Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of198Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of

116`ANTHROPIC_DEFAULT_HAIKU_MODEL`.199`ANTHROPIC_DEFAULT_HAIKU_MODEL`.

117 200 

201### Pin models for third-party deployments

202 

203When deploying Claude Code through [Bedrock](/en/amazon-bedrock), [Vertex AI](/en/google-vertex-ai), or [Foundry](/en/microsoft-foundry), pin model versions before rolling out to users.

204 

205Without pinning, Claude Code uses model aliases (`sonnet`, `opus`, `haiku`) that resolve to the latest version. When Anthropic releases a new model, users whose accounts don't have the new version enabled will break silently.

206 

207<Warning>

208 Set all three model environment variables to specific version IDs as part of your initial setup. Skipping this step means a Claude Code update can break your users without any action on your part.

209</Warning>

210 

211Use the following environment variables with version-specific model IDs for your provider:

212 

213| Provider | Example |

214| :-------- | :---------------------------------------------------------------------- |

215| Bedrock | `export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'` |

216| Vertex AI | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |

217| Foundry | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |

218 

219Apply the same pattern for `ANTHROPIC_DEFAULT_SONNET_MODEL` and `ANTHROPIC_DEFAULT_HAIKU_MODEL`. For current and legacy model IDs across all providers, see [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). To upgrade users to a new model version, update these environment variables and redeploy.

220 

221To enable [extended context](#extended-context) for a pinned model, append `[1m]` to the model ID in `ANTHROPIC_DEFAULT_OPUS_MODEL` or `ANTHROPIC_DEFAULT_SONNET_MODEL`:

222 

223```bash theme={null}

224export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6[1m]'

225```

226 

227The `[1m]` suffix applies the 1M context window to all usage of that alias, including `opusplan`. Claude Code strips the suffix before sending the model ID to your provider. Only append `[1m]` when the underlying model supports 1M context, such as Opus 4.6 or Sonnet 4.6.

228 

229<Note>

230 The `settings.availableModels` allowlist still applies when using third-party providers. Filtering matches on the model alias (`opus`, `sonnet`, `haiku`), not the provider-specific model ID.

231</Note>

232 

233### Override model IDs per version

234 

235The family-level environment variables above configure one model ID per family alias. If you need to map several versions within the same family to distinct provider IDs, use the `modelOverrides` setting instead.

236 

237`modelOverrides` maps individual Anthropic model IDs to the provider-specific strings that Claude Code sends to your provider's API. When a user selects a mapped model in the `/model` picker, Claude Code uses your configured value instead of the built-in default.

238 

239This lets enterprise administrators route each model version to a specific Bedrock inference profile ARN, Vertex AI version name, or Foundry deployment name for governance, cost allocation, or regional routing.

240 

241Set `modelOverrides` in your [settings file](/en/settings#settings-files):

242 

243```json theme={null}

244{

245 "modelOverrides": {

246 "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod",

247 "claude-opus-4-5-20251101": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-45-prod",

248 "claude-sonnet-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/sonnet-prod"

249 }

250}

251```

252 

253Keys must be Anthropic model IDs as listed in the [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). For dated model IDs, include the date suffix exactly as it appears there. Unknown keys are ignored.

254 

255Overrides replace the built-in model IDs that back each entry in the `/model` picker. On Bedrock, overrides take precedence over any inference profiles that Claude Code discovers automatically at startup. Values you supply directly through `ANTHROPIC_MODEL`, `--model`, or the `ANTHROPIC_DEFAULT_*_MODEL` environment variables are passed to the provider as-is and are not transformed by `modelOverrides`.

256 

257`modelOverrides` works alongside `availableModels`. The allowlist is evaluated against the Anthropic model ID, not the override value, so an entry like `"opus"` in `availableModels` continues to match even when Opus versions are mapped to ARNs.

258 

118### Prompt caching configuration259### Prompt caching configuration

119 260 

120Claude Code automatically uses [prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:261Claude Code automatically uses [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:

121 262 

122| Environment variable | Description |263| Environment variable | Description |

123| ------------------------------- | ---------------------------------------------------------------------------------------------- |264| ------------------------------- | ---------------------------------------------------------------------------------------------- |


127| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only |268| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only |

128 269 

129These environment variables give you fine-grained control over prompt caching behavior. The global `DISABLE_PROMPT_CACHING` setting takes precedence over the model-specific settings, allowing you to quickly disable all caching when needed. The per-model settings are useful for selective control, such as when debugging specific models or working with cloud providers that may have different caching implementations.270These environment variables give you fine-grained control over prompt caching behavior. The global `DISABLE_PROMPT_CACHING` setting takes precedence over the model-specific settings, allowing you to quickly disable all caching when needed. The per-model settings are useful for selective control, such as when debugging specific models or working with cloud providers that may have different caching implementations.

130 

131 

132 

133> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Monitoring5# Monitoring

2 6 

3> Learn how to enable and configure OpenTelemetry for Claude Code.7> Learn how to enable and configure OpenTelemetry for Claude Code.

4 8 

5Claude Code supports OpenTelemetry (OTel) metrics and events for monitoring and observability.9Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, and events via the logs/events protocol. Configure your metrics and logs backends to match your monitoring requirements.

6 

7All metrics are time series data exported via OpenTelemetry's standard metrics protocol, and events are exported via OpenTelemetry's logs/events protocol. It is the user's responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements.

8 10 

9## Quick start11## Quick start

10 12 


52 "OTEL_METRICS_EXPORTER": "otlp",54 "OTEL_METRICS_EXPORTER": "otlp",

53 "OTEL_LOGS_EXPORTER": "otlp",55 "OTEL_LOGS_EXPORTER": "otlp",

54 "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",56 "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",

55 "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317",57 "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4317",

56 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token"58 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token"

57 }59 }

58}60}

59```61```


67### Common configuration variables69### Common configuration variables

68 70 

69| Environment Variable | Description | Example Values |71| Environment Variable | Description | Example Values |

70| ----------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------ |72| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |

71| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |73| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |

72| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |74| `OTEL_METRICS_EXPORTER` | Metrics exporter types, comma-separated | `console`, `otlp`, `prometheus` |

73| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |75| `OTEL_LOGS_EXPORTER` | Logs/events exporter types, comma-separated | `console`, `otlp` |

74| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |76| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter, applies to all signals | `grpc`, `http/json`, `http/protobuf` |

75| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |77| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint for all signals | `http://localhost:4317` |

76| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics (overrides general) | `grpc`, `http/json`, `http/protobuf` |78| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

77| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint (overrides general) | `http://localhost:4318/v1/metrics` |79| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint, overrides general setting | `http://localhost:4318/v1/metrics` |

78| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs (overrides general) | `grpc`, `http/json`, `http/protobuf` |80| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

79| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint (overrides general) | `http://localhost:4318/v1/logs` |81| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint, overrides general setting | `http://localhost:4318/v1/logs` |

80| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |82| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |

81| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |83| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |

82| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |84| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |

83| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |85| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |

84| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |86| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |

85| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |87| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |

88| `OTEL_LOG_TOOL_DETAILS` | Enable logging of MCP server/tool names and skill names in tool events (default: disabled) | `1` to enable |

89| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality | `delta`, `cumulative` |

86| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |90| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |

87 91 

88### Metrics cardinality control92### Metrics cardinality control


144<Warning>148<Warning>

145 **Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:**149 **Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:**

146 150 

147 The `OTEL_RESOURCE_ATTRIBUTES` environment variable follows the [W3C Baggage specification](https://www.w3.org/TR/baggage/), which has strict formatting requirements:151 The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements:

148 152 

149 * **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid153 * **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid

150 * **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2`154 * **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2`


170 174 

171### Example configurations175### Example configurations

172 176 

177Set these environment variables before running `claude`. Each block shows a complete configuration for a different exporter or deployment scenario:

178 

173```bash theme={null}179```bash theme={null}

174# Console debugging (1-second intervals)180# Console debugging (1-second intervals)

175export CLAUDE_CODE_ENABLE_TELEMETRY=1181export CLAUDE_CODE_ENABLE_TELEMETRY=1


196export OTEL_METRICS_EXPORTER=otlp202export OTEL_METRICS_EXPORTER=otlp

197export OTEL_LOGS_EXPORTER=otlp203export OTEL_LOGS_EXPORTER=otlp

198export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf204export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf

199export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.company.com:4318205export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.example.com:4318

200export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc206export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc

201export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.company.com:4317207export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.example.com:4317

202 208 

203# Metrics only (no events/logs)209# Metrics only (no events/logs)

204export CLAUDE_CODE_ENABLE_TELEMETRY=1210export CLAUDE_CODE_ENABLE_TELEMETRY=1


220All metrics and events share these standard attributes:226All metrics and events share these standard attributes:

221 227 

222| Attribute | Description | Controlled By |228| Attribute | Description | Controlled By |

223| ------------------- | -------------------------------------------------------------------- | --------------------------------------------------- |229| ------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------- |

224| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |230| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |

225| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |231| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |

226| `organization.id` | Organization UUID (when authenticated) | Always included when available |232| `organization.id` | Organization UUID (when authenticated) | Always included when available |

227| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |233| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |

228| `terminal.type` | Terminal type (for example, `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |234| `user.id` | Anonymous device/installation identifier, generated per Claude Code installation | Always included |

235| `user.email` | User email address (when authenticated via OAuth) | Always included when available |

236| `terminal.type` | Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux` | Always included when detected |

229 237 

230### Metrics238### Metrics

231 239 


244 252 

245### Metric details253### Metric details

246 254 

255Each metric includes the standard attributes listed above. Metrics with additional context-specific attributes are noted below.

256 

247#### Session counter257#### Session counter

248 258 

249Incremented at the start of each session.259Incremented at the start of each session.


284**Attributes**:294**Attributes**:

285 295 

286* All [standard attributes](#standard-attributes)296* All [standard attributes](#standard-attributes)

287* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929")297* `model`: Model identifier (for example, "claude-sonnet-4-6")

288 298 

289#### Token counter299#### Token counter

290 300 


294 304 

295* All [standard attributes](#standard-attributes)305* All [standard attributes](#standard-attributes)

296* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)306* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)

297* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929")307* `model`: Model identifier (for example, "claude-sonnet-4-6")

298 308 

299#### Code edit tool decision counter309#### Code edit tool decision counter

300 310 


303**Attributes**:313**Attributes**:

304 314 

305* All [standard attributes](#standard-attributes)315* All [standard attributes](#standard-attributes)

306* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)316* `tool_name`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)

307* `decision`: User decision (`"accept"`, `"reject"`)317* `decision`: User decision (`"accept"`, `"reject"`)

308* `language`: Programming language of the edited file (for example, `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.318* `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

319* `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions.

309 320 

310#### Active time counter321#### Active time counter

311 322 

312Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.323Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions (typing, reading responses) and during CLI processing (tool execution, AI response generation).

313 324 

314**Attributes**:325**Attributes**:

315 326 

316* All [standard attributes](#standard-attributes)327* All [standard attributes](#standard-attributes)

328* `type`: `"user"` for keyboard interactions, `"cli"` for tool execution and AI responses

317 329 

318### Events330### Events

319 331 

320Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):332Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):

321 333 

334#### Event correlation attributes

335 

336When a user submits a prompt, Claude Code may make multiple API calls and run several tools. The `prompt.id` attribute lets you tie all of those events back to the single prompt that triggered them.

337 

338| Attribute | Description |

339| ----------- | ------------------------------------------------------------------------------------ |

340| `prompt.id` | UUID v4 identifier linking all events produced while processing a single user prompt |

341 

342To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user\_prompt event, any api\_request events, and any tool\_result events that occurred while processing that prompt.

343 

344<Note>

345 `prompt.id` is intentionally excluded from metrics because each prompt generates a unique ID, which would create an ever-growing number of time series. Use it for event-level analysis and audit trails only.

346</Note>

347 

322#### User prompt event348#### User prompt event

323 349 

324Logged when a user submits a prompt.350Logged when a user submits a prompt.


330* All [standard attributes](#standard-attributes)356* All [standard attributes](#standard-attributes)

331* `event.name`: `"user_prompt"`357* `event.name`: `"user_prompt"`

332* `event.timestamp`: ISO 8601 timestamp358* `event.timestamp`: ISO 8601 timestamp

359* `event.sequence`: monotonically increasing counter for ordering events within a session

333* `prompt_length`: Length of the prompt360* `prompt_length`: Length of the prompt

334* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)361* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)

335 362 


344* All [standard attributes](#standard-attributes)371* All [standard attributes](#standard-attributes)

345* `event.name`: `"tool_result"`372* `event.name`: `"tool_result"`

346* `event.timestamp`: ISO 8601 timestamp373* `event.timestamp`: ISO 8601 timestamp

374* `event.sequence`: monotonically increasing counter for ordering events within a session

347* `tool_name`: Name of the tool375* `tool_name`: Name of the tool

348* `success`: `"true"` or `"false"`376* `success`: `"true"` or `"false"`

349* `duration_ms`: Execution time in milliseconds377* `duration_ms`: Execution time in milliseconds

350* `error`: Error message (if failed)378* `error`: Error message (if failed)

351* `decision`: Either `"accept"` or `"reject"`379* `decision_type`: Either `"accept"` or `"reject"`

352* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`380* `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

381* `tool_result_size_bytes`: Size of the tool result in bytes

382* `mcp_server_scope`: MCP server scope identifier (for MCP tools)

353* `tool_parameters`: JSON string containing tool-specific parameters (when available)383* `tool_parameters`: JSON string containing tool-specific parameters (when available)

354 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`384 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds)

385 * For MCP tools (when `OTEL_LOG_TOOL_DETAILS=1`): includes `mcp_server_name`, `mcp_tool_name`

386 * For Skill tool (when `OTEL_LOG_TOOL_DETAILS=1`): includes `skill_name`

355 387 

356#### API request event388#### API request event

357 389 


364* All [standard attributes](#standard-attributes)396* All [standard attributes](#standard-attributes)

365* `event.name`: `"api_request"`397* `event.name`: `"api_request"`

366* `event.timestamp`: ISO 8601 timestamp398* `event.timestamp`: ISO 8601 timestamp

367* `model`: Model used (for example, "claude-sonnet-4-5-20250929")399* `event.sequence`: monotonically increasing counter for ordering events within a session

400* `model`: Model used (for example, "claude-sonnet-4-6")

368* `cost_usd`: Estimated cost in USD401* `cost_usd`: Estimated cost in USD

369* `duration_ms`: Request duration in milliseconds402* `duration_ms`: Request duration in milliseconds

370* `input_tokens`: Number of input tokens403* `input_tokens`: Number of input tokens

371* `output_tokens`: Number of output tokens404* `output_tokens`: Number of output tokens

372* `cache_read_tokens`: Number of tokens read from cache405* `cache_read_tokens`: Number of tokens read from cache

373* `cache_creation_tokens`: Number of tokens used for cache creation406* `cache_creation_tokens`: Number of tokens used for cache creation

407* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active

374 408 

375#### API error event409#### API error event

376 410 


383* All [standard attributes](#standard-attributes)417* All [standard attributes](#standard-attributes)

384* `event.name`: `"api_error"`418* `event.name`: `"api_error"`

385* `event.timestamp`: ISO 8601 timestamp419* `event.timestamp`: ISO 8601 timestamp

386* `model`: Model used (for example, "claude-sonnet-4-5-20250929")420* `event.sequence`: monotonically increasing counter for ordering events within a session

421* `model`: Model used (for example, "claude-sonnet-4-6")

387* `error`: Error message422* `error`: Error message

388* `status_code`: HTTP status code (if applicable)423* `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors

389* `duration_ms`: Request duration in milliseconds424* `duration_ms`: Request duration in milliseconds

390* `attempt`: Attempt number (for retried requests)425* `attempt`: Attempt number (for retried requests)

426* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active

391 427 

392#### Tool decision event428#### Tool decision event

393 429 


400* All [standard attributes](#standard-attributes)436* All [standard attributes](#standard-attributes)

401* `event.name`: `"tool_decision"`437* `event.name`: `"tool_decision"`

402* `event.timestamp`: ISO 8601 timestamp438* `event.timestamp`: ISO 8601 timestamp

439* `event.sequence`: monotonically increasing counter for ordering events within a session

403* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")440* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")

404* `decision`: Either `"accept"` or `"reject"`441* `decision`: Either `"accept"` or `"reject"`

405* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`442* `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

406 443 

407## Interpreting metrics and events data444## Interpret metrics and events data

408 445 

409The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:446The exported metrics and events support a range of analyses:

410 447 

411### Usage monitoring448### Usage monitoring

412 449 


485 522 

486For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear.523For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear.

487 524 

488## Security/privacy considerations525## Security and privacy

489 526 

490* Telemetry is opt-in and requires explicit configuration527* Telemetry is opt-in and requires explicit configuration

491* Sensitive information like API keys or file contents are never included in metrics or events528* Raw file contents and code snippets are not included in metrics or events. Tool execution events include bash commands and file paths in the `tool_parameters` field, which may contain sensitive values. If your commands may include secrets, configure your telemetry backend to filter or redact `tool_parameters`

492* User prompt content is redacted by default - only prompt length is recorded. To enable user prompt logging, set `OTEL_LOG_USER_PROMPTS=1`529* When authenticated via OAuth, `user.email` is included in telemetry attributes. If this is a concern for your organization, work with your telemetry backend to filter or redact this field

530* User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`

531* MCP server/tool names and skill names are not logged by default because they can reveal user-specific configurations. To include them, set `OTEL_LOG_TOOL_DETAILS=1`

493 532 

494## Monitoring Claude Code on Amazon Bedrock533## Monitor Claude Code on Amazon Bedrock

495 534 

496For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md).535For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md).

497 

498 

499 

500> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Enterprise network configuration5# Enterprise network configuration

2 6 

3> Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.7> Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.


76 80 

77Claude Code requires access to the following URLs:81Claude Code requires access to the following URLs:

78 82 

79* `api.anthropic.com` - Claude API endpoints83* `api.anthropic.com`: Claude API endpoints

80* `claude.ai` - WebFetch safeguards84* `claude.ai`: authentication for claude.ai accounts

81* `statsig.anthropic.com` - Telemetry and metrics85* `platform.claude.com`: authentication for Anthropic Console accounts

82* `sentry.io` - Error reporting

83 86 

84Ensure these URLs are allowlisted in your proxy configuration and firewall rules. This is especially important when using Claude Code in containerized or restricted network environments.87Ensure these URLs are allowlisted in your proxy configuration and firewall rules. This is especially important when using Claude Code in containerized or restricted network environments.

85 88 

89[Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review) connect to your repositories from Anthropic-managed infrastructure. If your GitHub Enterprise Cloud organization restricts access by IP address, enable [IP allow list inheritance for installed GitHub Apps](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address) instead, or to configure other firewalls, see the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).

90 

86## Additional resources91## Additional resources

87 92 

88* [Claude Code settings](/en/settings)93* [Claude Code settings](/en/settings)

89* [Environment variables reference](/en/settings#environment-variables)94* [Environment variables reference](/en/env-vars)

90* [Troubleshooting guide](/en/troubleshooting)95* [Troubleshooting guide](/en/troubleshooting)

91 

92 

93 

94> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

output-styles.md +20 −15

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Output styles5# Output styles

2 6 

3> Adapt Claude Code for uses beyond software engineering7> Adapt Claude Code for uses beyond software engineering


38 42 

39## Change your output style43## Change your output style

40 44 

41You can either:45Run `/config` and select **Output style** to pick a style from a menu. Your

46selection is saved to `.claude/settings.local.json` at the

47[local project level](/en/settings).

42 48 

43* Run `/output-style` to access a menu and select your output style (this can49To set a style without the menu, edit the `outputStyle` field directly in a

44 also be accessed from the `/config` menu)50settings file:

45 51 

46* Run `/output-style [style]`, such as `/output-style explanatory`, to directly52```json theme={null}

47 switch to a style53{

54 "outputStyle": "Explanatory"

55}

56```

48 57 

49These changes apply to the [local project level](/en/settings) and are saved in58Because the output style is set in the system prompt at session start,

50`.claude/settings.local.json`. You can also directly edit the `outputStyle`59changes take effect the next time you start a new session. This keeps the system

51field in a settings file at a different level.60prompt stable throughout a conversation so prompt caching can reduce latency and

61cost.

52 62 

53## Create a custom output style63## Create a custom output style

54 64 


77 87 

78### Frontmatter88### Frontmatter

79 89 

80Output style files support frontmatter, useful for specifying metadata about the90Output style files support frontmatter for specifying metadata:

81command:

82 91 

83| Frontmatter | Purpose | Default |92| Frontmatter | Purpose | Default |

84| :------------------------- | :-------------------------------------------------------------------------- | :---------------------- |93| :------------------------- | :-------------------------------------------------------------------------- | :---------------------- |

85| `name` | Name of the output style, if not the file name | Inherits from file name |94| `name` | Name of the output style, if not the file name | Inherits from file name |

86| `description` | Description of the output style. Used only in the UI of `/output-style` | None |95| `description` | Description of the output style, shown in the `/config` picker | None |

87| `keep-coding-instructions` | Whether to keep the parts of Claude Code's system prompt related to coding. | false |96| `keep-coding-instructions` | Whether to keep the parts of Claude Code's system prompt related to coding. | false |

88 97 

89## Comparisons to related features98## Comparisons to related features


106### Output Styles vs. [Skills](/en/skills)115### Output Styles vs. [Skills](/en/skills)

107 116 

108Output styles modify how Claude responds (formatting, tone, structure) and are always active once selected. Skills are task-specific prompts that you invoke with `/skill-name` or that Claude loads automatically when relevant. Use output styles for consistent formatting preferences; use skills for reusable workflows and tasks.117Output styles modify how Claude responds (formatting, tone, structure) and are always active once selected. Skills are task-specific prompts that you invoke with `/skill-name` or that Claude loads automatically when relevant. Use output styles for consistent formatting preferences; use skills for reusable workflows and tasks.

109 

110 

111 

112> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

overview.md +148 −70

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code overview5# Claude Code overview

2 6 

3> Learn about Claude Code, Anthropic's agentic coding tool that lives in your terminal and helps you turn ideas into code faster than ever before.7> Claude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in your terminal, IDE, desktop app, and browser.

4 8 

5## Get started in 30 seconds9Claude Code is an AI-powered coding assistant that helps you build features, fix bugs, and automate development tasks. It understands your entire codebase and can work across multiple files and tools to get things done.

6 10 

7Prerequisites:11## Get started

8 12 

9* A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise) or [Claude Console](https://console.anthropic.com/) account13Choose your environment to get started. Most surfaces require a [Claude subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_pricing) or [Anthropic Console](https://console.anthropic.com/) account. The Terminal CLI and VS Code also support [third-party providers](/en/third-party-integrations).

10 14 

11**Install Claude Code:**15<Tabs>

16 <Tab title="Terminal">

17 The full-featured CLI for working with Claude Code directly in your terminal. Edit files, run commands, and manage your entire project from the command line.

12 18 

13To install Claude Code, use one of the following methods:19 To install Claude Code, use one of the following methods:

14 20 

15<Tabs>21 <Tabs>

16 <Tab title="Native Install (Recommended)">22 <Tab title="Native Install (Recommended)">

17 **macOS, Linux, WSL:**23 **macOS, Linux, WSL:**

18 24 


32 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd38 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

33 ```39 ```

34 40 

41 **Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it.

42 

35 <Info>43 <Info>

36 Native installations automatically update in the background to keep you on the latest version.44 Native installations automatically update in the background to keep you on the latest version.

37 </Info>45 </Info>

38 </Tab>46 </Tab>

39 47 

40 <Tab title="Homebrew">48 <Tab title="Homebrew">

41 ```sh theme={null}49 ```bash theme={null}

42 brew install --cask claude-code50 brew install --cask claude-code

43 ```51 ```

44 52 


56 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.64 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

57 </Info>65 </Info>

58 </Tab>66 </Tab>

59</Tabs>67 </Tabs>

60 68 

61**Start using Claude Code:**69 Then start Claude Code in any project:

62 70 

63```bash theme={null}71 ```bash theme={null}

64cd your-project72 cd your-project

65claude73 claude

66```74 ```

67 75 

68You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 minutes) →](/en/quickstart)76 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/en/quickstart)

69 77 

70<Tip>78 <Tip>

71 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.79 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.

72</Tip>80 </Tip>

81 </Tab>

73 82 

74## What Claude Code does for you83 <Tab title="VS Code">

84 The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.

75 85 

76* **Build features from descriptions**: Tell Claude what you want to build in plain English. It will make a plan, write the code, and ensure it works.86 * [Install for VS Code](vscode:extension/anthropic.claude-code)

77* **Debug and fix issues**: Describe a bug or paste an error message. Claude Code will analyze your codebase, identify the problem, and implement a fix.87 * [Install for Cursor](cursor:extension/anthropic.claude-code)

78* **Navigate any codebase**: Ask anything about your team's codebase, and get a thoughtful answer back. Claude Code maintains awareness of your entire project structure, can find up-to-date information from the web, and with [MCP](/en/mcp) can pull from external data sources like Google Drive, Figma, and Slack.

79* **Automate tedious tasks**: Fix fiddly lint issues, resolve merge conflicts, and write release notes. Do all this in a single command from your developer machines, or automatically in CI.

80 88 

81## Why developers love Claude Code89 Or search for "Claude Code" in the Extensions view (`Cmd+Shift+X` on Mac, `Ctrl+Shift+X` on Windows/Linux). After installing, open the Command Palette (`Cmd+Shift+P` / `Ctrl+Shift+P`), type "Claude Code", and select **Open in New Tab**.

82 90 

83* **Works in your terminal**: Not another chat window. Not another IDE. Claude Code meets you where you already work, with the tools you already love.91 [Get started with VS Code →](/en/vs-code#get-started)

84* **Takes action**: Claude Code can directly edit files, run commands, and create commits. Need more? [MCP](/en/mcp) lets Claude read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling.92 </Tab>

85* **Unix philosophy**: Claude Code is composable and scriptable. `tail -f app.log | claude -p "Slack me if you see any anomalies appear in this log stream"` *works*. Your CI can run `claude -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`.

86* **Enterprise-ready**: Use the Claude API, or host on AWS or GCP. Enterprise-grade [security](/en/security), [privacy](/en/data-usage), and [compliance](https://trust.anthropic.com/) is built-in.

87 93 

88## Next steps94 <Tab title="Desktop app">

95 A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, schedule recurring tasks, and kick off cloud sessions.

89 96 

90<CardGroup>97 Download and install:

91 <Card title="Quickstart" icon="rocket" href="/en/quickstart">

92 See Claude Code in action with practical examples

93 </Card>

94 98 

95 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">99 * [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) (Intel and Apple Silicon)

96 Step-by-step guides for common workflows100 * [Windows](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs) (x64)

97 </Card>101 * [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs) (remote sessions only)

98 102 

99 <Card title="Troubleshooting" icon="wrench" href="/en/troubleshooting">103 After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_desktop_pricing) is required.

100 Solutions for common issues with Claude Code

101 </Card>

102 104 

103 <Card title="IDE setup" icon="laptop" href="/en/vs-code">105 [Learn more about the desktop app →](/en/desktop-quickstart)

104 Add Claude Code to your IDE106 </Tab>

105 </Card>

106</CardGroup>

107 107 

108## Additional resources108 <Tab title="Web">

109 Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they're done, work on repos you don't have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.

109 110 

110<CardGroup>111 Start coding at [claude.ai/code](https://claude.ai/code).

111 <Card title="About Claude Code" icon="sparkles" href="https://claude.com/product/claude-code">

112 Learn more about Claude Code on claude.com

113 </Card>

114 112 

115 <Card title="Build with the Agent SDK" icon="code-branch" href="https://docs.claude.com/en/docs/agent-sdk/overview">113 [Get started on the web →](/en/claude-code-on-the-web#getting-started)

116 Create custom AI agents with the Claude Agent SDK114 </Tab>

117 </Card>115 

116 <Tab title="JetBrains">

117 A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.

118 118 

119 <Card title="Host on AWS or GCP" icon="cloud" href="/en/third-party-integrations">119 Install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains Marketplace and restart your IDE.

120 Configure Claude Code with Amazon Bedrock or Google Vertex AI

121 </Card>

122 120 

123 <Card title="Settings" icon="gear" href="/en/settings">121 [Get started with JetBrains →](/en/jetbrains)

124 Customize Claude Code for your workflow122 </Tab>

125 </Card>123</Tabs>

126 124 

127 <Card title="Commands" icon="terminal" href="/en/cli-reference">125## What you can do

128 Learn about CLI commands and controls

129 </Card>

130 126 

131 <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">127Here are some of the ways you can use Claude Code:

132 Clone our development container reference implementation

133 </Card>

134 128 

135 <Card title="Security" icon="shield" href="/en/security">129<AccordionGroup>

136 Discover Claude Code's safeguards and best practices for safe usage130 <Accordion title="Automate the work you keep putting off" icon="wand-magic-sparkles">

137 </Card>131 Claude Code handles the tedious tasks that eat up your day: writing tests for untested code, fixing lint errors across a project, resolving merge conflicts, updating dependencies, and writing release notes.

138 132 

139 <Card title="Privacy and data usage" icon="lock" href="/en/data-usage">133 ```bash theme={null}

140 Understand how Claude Code handles your data134 claude "write tests for the auth module, run them, and fix any failures"

141 </Card>135 ```

142</CardGroup>136 </Accordion>

143 137 

138 <Accordion title="Build features and fix bugs" icon="hammer">

139 Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.

140 

141 For bugs, paste an error message or describe the symptom. Claude Code traces the issue through your codebase, identifies the root cause, and implements a fix. See [common workflows](/en/common-workflows) for more examples.

142 </Accordion>

143 

144 <Accordion title="Create commits and pull requests" icon="code-branch">

145 Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests.

146 

147 ```bash theme={null}

148 claude "commit my changes with a descriptive message"

149 ```

150 

151 In CI, you can automate code review and issue triage with [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd).

152 </Accordion>

153 

154 <Accordion title="Connect your tools with MCP" icon="plug">

155 The [Model Context Protocol (MCP)](/en/mcp) is an open standard for connecting AI tools to external data sources. With MCP, Claude Code can read your design docs in Google Drive, update tickets in Jira, pull data from Slack, or use your own custom tooling.

156 </Accordion>

157 

158 <Accordion title="Customize with instructions, skills, and hooks" icon="sliders">

159 [`CLAUDE.md`](/en/memory) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds [auto memory](/en/memory#auto-memory) as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.

160 

161 Create [custom commands](/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.

162 

163 [Hooks](/en/hooks) let you run shell commands before or after Claude Code actions, like auto-formatting after every file edit or running lint before a commit.

164 </Accordion>

165 

166 <Accordion title="Run agent teams and build custom agents" icon="users">

167 Spawn [multiple Claude Code agents](/en/sub-agents) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.

168 

169 For fully custom workflows, the [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) lets you build your own agents powered by Claude Code's tools and capabilities, with full control over orchestration, tool access, and permissions.

170 </Accordion>

171 

172 <Accordion title="Pipe, script, and automate with the CLI" icon="terminal">

173 Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:

174 

175 ```bash theme={null}

176 # Monitor logs and get alerted

177 tail -f app.log | claude -p "Slack me if you see any anomalies"

178 

179 # Automate translations in CI

180 claude -p "translate new strings into French and raise a PR for review"

181 

182 # Bulk operations across files

183 git diff main --name-only | claude -p "review these changed files for security issues"

184 ```

185 

186 See the [CLI reference](/en/cli-reference) for the full set of commands and flags.

187 </Accordion>

188 

189 <Accordion title="Work from anywhere" icon="globe">

190 Sessions aren't tied to a single surface. Move work between environments as your context changes:

191 

192 * Step away from your desk and keep working from your phone or any browser with [Remote Control](/en/remote-control)

193 * Kick off a long-running task on the [web](/en/claude-code-on-the-web) or [iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684), then pull it into your terminal with `/teleport`

194 * Hand off a terminal session to the [Desktop app](/en/desktop) with `/desktop` for visual diff review

195 * Route tasks from team chat: mention `@Claude` in [Slack](/en/slack) with a bug report and get a pull request back

196 </Accordion>

197</AccordionGroup>

198 

199## Use Claude Code everywhere

200 

201Each surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them.

202 

203Beyond the [Terminal](/en/quickstart), [VS Code](/en/vs-code), [JetBrains](/en/jetbrains), [Desktop](/en/desktop), and [Web](/en/claude-code-on-the-web) environments above, Claude Code integrates with CI/CD, chat, and browser workflows:

204 

205| I want to... | Best option |

206| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |

207| Continue a local session from my phone or another device | [Remote Control](/en/remote-control) |

208| Start a task locally, continue on mobile | [Web](/en/claude-code-on-the-web) or [Claude iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684) |

209| Automate PR reviews and issue triage | [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd) |

210| Get automatic code review on every PR | [GitHub Code Review](/en/code-review) |

211| Route bug reports from Slack to pull requests | [Slack](/en/slack) |

212| Debug live web applications | [Chrome](/en/chrome) |

213| Build custom agents for your own workflows | [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) |

214 

215## Next steps

144 216 

217Once you've installed Claude Code, these guides help you go deeper.

145 218 

146> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt219* [Quickstart](/en/quickstart): walk through your first real task, from exploring a codebase to committing a fix

220* [Store instructions and memories](/en/memory): give Claude persistent instructions with CLAUDE.md files and auto memory

221* [Common workflows](/en/common-workflows) and [best practices](/en/best-practices): patterns for getting the most out of Claude Code

222* [Settings](/en/settings): customize Claude Code for your workflow

223* [Troubleshooting](/en/troubleshooting): solutions for common issues

224* [code.claude.com](https://code.claude.com/): demos, pricing, and product details

permissions.md +259 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Configure permissions

6 

7> Control what Claude Code can access and do with fine-grained permission rules, modes, and managed policies.

8 

9Claude Code supports fine-grained permissions so that you can specify exactly what the agent is allowed to do and what it cannot. Permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.

10 

11## Permission system

12 

13Claude Code uses a tiered permission system to balance power and safety:

14 

15| Tool type | Example | Approval required | "Yes, don't ask again" behavior |

16| :---------------- | :--------------- | :---------------- | :-------------------------------------------- |

17| Read-only | File reads, Grep | No | N/A |

18| Bash commands | Shell execution | Yes | Permanently per project directory and command |

19| File modification | Edit/write files | Yes | Until session end |

20 

21## Manage permissions

22 

23You can view and manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.

24 

25* **Allow** rules let Claude Code use the specified tool without manual approval.

26* **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool.

27* **Deny** rules prevent Claude Code from using the specified tool.

28 

29Rules are evaluated in order: **deny -> ask -> allow**. The first matching rule wins, so deny rules always take precedence.

30 

31## Permission modes

32 

33Claude Code supports several permission modes that control how tools are approved. Set the `defaultMode` in your [settings files](/en/settings#settings-files):

34 

35| Mode | Description |

36| :------------------ | :------------------------------------------------------------------------------------ |

37| `default` | Standard behavior: prompts for permission on first use of each tool |

38| `acceptEdits` | Automatically accepts file edit permissions for the session |

39| `plan` | Plan Mode: Claude can analyze but not modify files or execute commands |

40| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules |

41| `bypassPermissions` | Skips all permission prompts (requires safe environment, see warning below) |

42 

43<Warning>

44 `bypassPermissions` mode disables all permission checks. Only use this in isolated environments like containers or VMs where Claude Code cannot cause damage. Administrators can prevent this mode by setting `disableBypassPermissionsMode` to `"disable"` in [managed settings](#managed-settings).

45</Warning>

46 

47## Permission rule syntax

48 

49Permission rules follow the format `Tool` or `Tool(specifier)`.

50 

51### Match all uses of a tool

52 

53To match all uses of a tool, use just the tool name without parentheses:

54 

55| Rule | Effect |

56| :--------- | :----------------------------- |

57| `Bash` | Matches all Bash commands |

58| `WebFetch` | Matches all web fetch requests |

59| `Read` | Matches all file reads |

60 

61`Bash(*)` is equivalent to `Bash` and matches all Bash commands.

62 

63### Use specifiers for fine-grained control

64 

65Add a specifier in parentheses to match specific tool uses:

66 

67| Rule | Effect |

68| :----------------------------- | :------------------------------------------------------- |

69| `Bash(npm run build)` | Matches the exact command `npm run build` |

70| `Read(./.env)` | Matches reading the `.env` file in the current directory |

71| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

72 

73### Wildcard patterns

74 

75Bash rules support glob patterns with `*`. Wildcards can appear at any position in the command. This configuration allows npm and git commit commands while blocking git push:

76 

77```json theme={null}

78{

79 "permissions": {

80 "allow": [

81 "Bash(npm run *)",

82 "Bash(git commit *)",

83 "Bash(git * main)",

84 "Bash(* --version)",

85 "Bash(* --help *)"

86 ],

87 "deny": [

88 "Bash(git push *)"

89 ]

90 }

91}

92```

93 

94The space before `*` matters: `Bash(ls *)` matches `ls -la` but not `lsof`, while `Bash(ls*)` matches both. The legacy `:*` suffix syntax is equivalent to ` *` but is deprecated.

95 

96## Tool-specific permission rules

97 

98### Bash

99 

100Bash permission rules support wildcard matching with `*`. Wildcards can appear at any position in the command, including at the beginning, middle, or end:

101 

102* `Bash(npm run build)` matches the exact Bash command `npm run build`

103* `Bash(npm run test *)` matches Bash commands starting with `npm run test`

104* `Bash(npm *)` matches any command starting with `npm `

105* `Bash(* install)` matches any command ending with ` install`

106* `Bash(git * main)` matches commands like `git checkout main`, `git merge main`

107 

108When `*` appears at the end with a space before it (like `Bash(ls *)`), it enforces a word boundary, requiring the prefix to be followed by a space or end-of-string. For example, `Bash(ls *)` matches `ls -la` but not `lsof`. In contrast, `Bash(ls*)` without a space matches both `ls -la` and `lsof` because there's no word boundary constraint.

109 

110<Tip>

111 Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd *)` won't give it permission to run the command `safe-cmd && other-cmd`.

112</Tip>

113 

114<Warning>

115 Bash permission patterns that try to constrain command arguments are fragile. For example, `Bash(curl http://github.com/ *)` intends to restrict curl to GitHub URLs, but won't match variations like:

116 

117 * Options before URL: `curl -X GET http://github.com/...`

118 * Different protocol: `curl https://github.com/...`

119 * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)

120 * Variables: `URL=http://github.com && curl $URL`

121 * Extra spaces: `curl http://github.com`

122 

123 For more reliable URL filtering, consider:

124 

125 * **Restrict Bash network tools**: use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains

126 * **Use PreToolUse hooks**: implement a hook that validates URLs in Bash commands and blocks disallowed domains

127 * Instructing Claude Code about your allowed curl patterns via CLAUDE.md

128 

129 Note that using WebFetch alone does not prevent network access. If Bash is allowed, Claude can still use `curl`, `wget`, or other tools to reach any URL.

130</Warning>

131 

132### Read and Edit

133 

134`Edit` rules apply to all built-in tools that edit files. Claude makes a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep and Glob.

135 

136Read and Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

137 

138| Pattern | Meaning | Example | Matches |

139| ------------------ | -------------------------------------- | -------------------------------- | ------------------------------ |

140| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

141| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

142| `/path` | Path **relative to project root** | `Edit(/src/**/*.ts)` | `<project root>/src/**/*.ts` |

143| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

144 

145<Warning>

146 A pattern like `/Users/alice/file` is NOT an absolute path. It's relative to the project root. Use `//Users/alice/file` for absolute paths.

147</Warning>

148 

149Examples:

150 

151* `Edit(/docs/**)`: edits in `<project>/docs/` (NOT `/docs/` and NOT `<project>/.claude/docs/`)

152* `Read(~/.zshrc)`: reads your home directory's `.zshrc`

153* `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt`

154* `Read(src/**)`: reads from `<current-directory>/src/`

155 

156<Note>

157 In gitignore patterns, `*` matches files in a single directory while `**` matches recursively across directories. To allow all file access, use just the tool name without parentheses: `Read`, `Edit`, or `Write`.

158</Note>

159 

160### WebFetch

161 

162* `WebFetch(domain:example.com)` matches fetch requests to example.com

163 

164### MCP

165 

166* `mcp__puppeteer` matches any tool provided by the `puppeteer` server (name configured in Claude Code)

167* `mcp__puppeteer__*` wildcard syntax that also matches all tools from the `puppeteer` server

168* `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server

169 

170### Agent (subagents)

171 

172Use `Agent(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use:

173 

174* `Agent(Explore)` matches the Explore subagent

175* `Agent(Plan)` matches the Plan subagent

176* `Agent(my-custom-agent)` matches a custom subagent named `my-custom-agent`

177 

178Add these rules to the `deny` array in your settings or use the `--disallowedTools` CLI flag to disable specific agents. To disable the Explore agent:

179 

180```json theme={null}

181{

182 "permissions": {

183 "deny": ["Agent(Explore)"]

184 }

185}

186```

187 

188## Extend permissions with hooks

189 

190[Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system, and the hook output can determine whether to approve or deny the tool call in place of the permission system.

191 

192## Working directories

193 

194By default, Claude has access to files in the directory where it was launched. You can extend this access:

195 

196* **During startup**: use `--add-dir <path>` CLI argument

197* **During session**: use `/add-dir` command

198* **Persistent configuration**: add to `additionalDirectories` in [settings files](/en/settings#settings-files)

199 

200Files in additional directories follow the same permission rules as the original working directory: they become readable without prompts, and file editing permissions follow the current permission mode.

201 

202## How permissions interact with sandboxing

203 

204Permissions and [sandboxing](/en/sandboxing) are complementary security layers:

205 

206* **Permissions** control which tools Claude Code can use and which files or domains it can access. They apply to all tools (Bash, Read, Edit, WebFetch, MCP, and others).

207* **Sandboxing** provides OS-level enforcement that restricts the Bash tool's filesystem and network access. It applies only to Bash commands and their child processes.

208 

209Use both for defense-in-depth:

210 

211* Permission deny rules block Claude from even attempting to access restricted resources

212* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making

213* Filesystem restrictions in the sandbox use Read and Edit deny rules, not separate sandbox configuration

214* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` list

215 

216## Managed settings

217 

218For organizations that need centralized control over Claude Code configuration, administrators can deploy managed settings that cannot be overridden by user or project settings. These policy settings follow the same format as regular settings files and can be delivered through MDM/OS-level policies, managed settings files, or [server-managed settings](/en/server-managed-settings). See [settings files](/en/settings#settings-files) for delivery mechanisms and file locations.

219 

220### Managed-only settings

221 

222Some settings are only effective in managed settings:

223 

224| Setting | Description |

225| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

226| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode and the `--dangerously-skip-permissions` flag |

227| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |

228| `allowManagedHooksOnly` | When `true`, prevents loading of user, project, and plugin hooks. Only managed hooks and SDK hooks are allowed |

229| `allowManagedMcpServersOnly` | When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) |

230| `blockedMarketplaces` | Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

231| `sandbox.network.allowManagedDomainsOnly` | When `true`, only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Non-allowed domains are blocked automatically without prompting the user. Denied domains still merge from all sources |

232| `strictKnownMarketplaces` | Controls which plugin marketplaces users can add. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

233| `allow_remote_sessions` | When `true`, allows users to start [Remote Control](/en/remote-control) and [web sessions](/en/claude-code-on-the-web). Defaults to `true`. Set to `false` to prevent remote session access |

234 

235## Settings precedence

236 

237Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings:

238 

2391. **Managed settings**: cannot be overridden by any other level, including command line arguments

2402. **Command line arguments**: temporary session overrides

2413. **Local project settings** (`.claude/settings.local.json`)

2424. **Shared project settings** (`.claude/settings.json`)

2435. **User settings** (`~/.claude/settings.json`)

244 

245If a tool is denied at any level, no other level can allow it. For example, a managed settings deny cannot be overridden by `--allowedTools`, and `--disallowedTools` can add restrictions beyond what managed settings define.

246 

247If a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked.

248 

249## Example configurations

250 

251This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios. Use these as starting points and adjust them to fit your needs.

252 

253## See also

254 

255* [Settings](/en/settings): complete configuration reference including the permission settings table

256* [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands

257* [Authentication](/en/authentication): set up user access to Claude Code

258* [Security](/en/security): security safeguards and best practices

259* [Hooks](/en/hooks-guide): automate workflows and extend permission evaluation

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Create and distribute a plugin marketplace5# Create and distribute a plugin marketplace

2 6 

3> Build and host plugin marketplaces to distribute Claude Code extensions across teams and communities.7> Build and host plugin marketplaces to distribute Claude Code extensions across teams and communities.

4 8 

5A plugin marketplace is a catalog that lets you distribute plugins to others. Marketplaces provide centralized discovery, version tracking, automatic updates, and support for multiple source types (git repositories, local paths, and more). This guide shows you how to create your own marketplace to share plugins with your team or community.9A **plugin marketplace** is a catalog that lets you distribute plugins to others. Marketplaces provide centralized discovery, version tracking, automatic updates, and support for multiple source types (git repositories, local paths, and more). This guide shows you how to create your own marketplace to share plugins with your team or community.

6 10 

7Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/en/discover-plugins).11Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/en/discover-plugins).

8 12 


19 23 

20## Walkthrough: create a local marketplace24## Walkthrough: create a local marketplace

21 25 

22This example creates a marketplace with one plugin: a `/review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.26This example creates a marketplace with one plugin: a `/quality-review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.

23 27 

24<Steps>28<Steps>

25 <Step title="Create the directory structure">29 <Step title="Create the directory structure">

26 ```bash theme={null}30 ```bash theme={null}

27 mkdir -p my-marketplace/.claude-plugin31 mkdir -p my-marketplace/.claude-plugin

28 mkdir -p my-marketplace/plugins/review-plugin/.claude-plugin32 mkdir -p my-marketplace/plugins/quality-review-plugin/.claude-plugin

29 mkdir -p my-marketplace/plugins/review-plugin/skills/review33 mkdir -p my-marketplace/plugins/quality-review-plugin/skills/quality-review

30 ```34 ```

31 </Step>35 </Step>

32 36 

33 <Step title="Create the skill">37 <Step title="Create the skill">

34 Create a `SKILL.md` file that defines what the `/review` skill does.38 Create a `SKILL.md` file that defines what the `/quality-review` skill does.

35 39 

36 ```markdown my-marketplace/plugins/review-plugin/skills/review/SKILL.md theme={null}40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}

37 ---41 ---

38 description: Review code for bugs, security, and performance42 description: Review code for bugs, security, and performance

39 disable-model-invocation: true43 disable-model-invocation: true


52 <Step title="Create the plugin manifest">56 <Step title="Create the plugin manifest">

53 Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory.57 Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory.

54 58 

55 ```json my-marketplace/plugins/review-plugin/.claude-plugin/plugin.json theme={null}59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}

56 {60 {

57 "name": "review-plugin",61 "name": "quality-review-plugin",

58 "description": "Adds a /review skill for quick code reviews",62 "description": "Adds a /quality-review skill for quick code reviews",

59 "version": "1.0.0"63 "version": "1.0.0"

60 }64 }

61 ```65 ```


72 },76 },

73 "plugins": [77 "plugins": [

74 {78 {

75 "name": "review-plugin",79 "name": "quality-review-plugin",

76 "source": "./plugins/review-plugin",80 "source": "./plugins/quality-review-plugin",

77 "description": "Adds a /review skill for quick code reviews"81 "description": "Adds a /quality-review skill for quick code reviews"

78 }82 }

79 ]83 ]

80 }84 }


86 90 

87 ```shell theme={null}91 ```shell theme={null}

88 /plugin marketplace add ./my-marketplace92 /plugin marketplace add ./my-marketplace

89 /plugin install review-plugin@my-plugins93 /plugin install quality-review-plugin@my-plugins

90 ```94 ```

91 </Step>95 </Step>

92 96 


104<Note>108<Note>

105 **How plugins are installed**: When users install a plugin, Claude Code copies the plugin directory to a cache location. This means plugins can't reference files outside their directory using paths like `../shared-utils`, because those files won't be copied.109 **How plugins are installed**: When users install a plugin, Claude Code copies the plugin directory to a cache location. This means plugins can't reference files outside their directory using paths like `../shared-utils`, because those files won't be copied.

106 110 

107 If you need to share files across plugins, use symlinks (which are followed during copying) or restructure your marketplace so the shared directory is inside the plugin source path. See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for details.111 If you need to share files across plugins, use symlinks (which are followed during copying). See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for details.

108</Note>112</Note>

109 113 

110## Create the marketplace file114## Create the marketplace file


187**Standard metadata fields:**191**Standard metadata fields:**

188 192 

189| Field | Type | Description |193| Field | Type | Description |

190| :------------ | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |194| :------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------- |

191| `description` | string | Brief plugin description |195| `description` | string | Brief plugin description |

192| `version` | string | Plugin version |196| `version` | string | Plugin version |

193| `author` | object | Plugin author information (`name` required, `email` optional) |197| `author` | object | Plugin author information (`name` required, `email` optional) |


197| `keywords` | array | Tags for plugin discovery and categorization |201| `keywords` | array | Tags for plugin discovery and categorization |

198| `category` | string | Plugin category for organization |202| `category` | string | Plugin category for organization |

199| `tags` | array | Tags for searchability |203| `tags` | array | Tags for searchability |

200| `strict` | boolean | Controls whether plugins need their own `plugin.json` file. When `true` (default), the plugin source must contain a `plugin.json`, and any fields you add here in the marketplace entry get merged with it. When `false`, the plugin doesn't need its own `plugin.json`; the marketplace entry itself defines everything about the plugin. Use `false` when you want to define simple plugins entirely in your marketplace file. |204| `strict` | boolean | Controls whether `plugin.json` is the authority for component definitions (default: true). See [Strict mode](#strict-mode) below. |

201 205 

202**Component configuration fields:**206**Component configuration fields:**

203 207 


211 215 

212## Plugin sources216## Plugin sources

213 217 

218Plugin sources tell Claude Code where to fetch each individual plugin listed in your marketplace. These are set in the `source` field of each plugin entry in `marketplace.json`.

219 

220Once a plugin is cloned or copied into the local machine, it is copied into the local versioned plugin cache at `~/.claude/plugins/cache`.

221 

222| Source | Type | Fields | Notes |

223| ------------- | ------------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------- |

224| Relative path | `string` (e.g. `"./my-plugin"`) | — | Local directory within the marketplace repo. Must start with `./` |

225| `github` | object | `repo`, `ref?`, `sha?` | |

226| `url` | object | `url` (must end .git), `ref?`, `sha?` | Git URL source |

227| `git-subdir` | object | `url`, `path`, `ref?`, `sha?` | Subdirectory within a git repo. Clones sparsely to minimize bandwidth for monorepos |

228| `npm` | object | `package`, `version?`, `registry?` | Installed via `npm install` |

229| `pip` | object | `package`, `version?`, `registry?` | Installed via pip |

230 

231<Note>

232 **Marketplace sources vs plugin sources**: These are different concepts that control different things.

233 

234 * **Marketplace source** — where to fetch the `marketplace.json` catalog itself. Set when users run `/plugin marketplace add` or in `extraKnownMarketplaces` settings. Supports `ref` (branch/tag) but not `sha`.

235 * **Plugin source** — where to fetch an individual plugin listed in the marketplace. Set in the `source` field of each plugin entry inside `marketplace.json`. Supports both `ref` (branch/tag) and `sha` (exact commit).

236 

237 For example, a marketplace hosted at `acme-corp/plugin-catalog` (marketplace source) can list a plugin fetched from `acme-corp/code-formatter` (plugin source). The marketplace source and plugin source point to different repositories and are pinned independently.

238</Note>

239 

214### Relative paths240### Relative paths

215 241 

216For plugins in the same repository:242For plugins in the same repository, use a path starting with `./`:

217 243 

218```json theme={null}244```json theme={null}

219{245{


222}248}

223```249```

224 250 

251Paths resolve relative to the marketplace root, which is the directory containing `.claude-plugin/`. In the example above, `./plugins/my-plugin` points to `<repo>/plugins/my-plugin`, even though `marketplace.json` lives at `<repo>/.claude-plugin/marketplace.json`. Do not use `../` to climb out of `.claude-plugin/`.

252 

225<Note>253<Note>

226 Relative paths only work when users add your marketplace via Git (GitHub, GitLab, or git URL). If users add your marketplace via a direct URL to the `marketplace.json` file, relative paths will not resolve correctly. For URL-based distribution, use GitHub, npm, or git URL sources instead. See [Troubleshooting](#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.254 Relative paths only work when users add your marketplace via Git (GitHub, GitLab, or git URL). If users add your marketplace via a direct URL to the `marketplace.json` file, relative paths will not resolve correctly. For URL-based distribution, use GitHub, npm, or git URL sources instead. See [Troubleshooting](#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.

227</Note>255</Note>


285```313```

286 314 

287| Field | Type | Description |315| Field | Type | Description |

288| :---- | :----- | :-------------------------------------------------------------------- |316| :---- | :----- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |

289| `url` | string | Required. Full git repository URL (must end with `.git`) |317| `url` | string | Required. Full git repository URL (`https://` or `git@`). The `.git` suffix is optional, so Azure DevOps and AWS CodeCommit URLs without the suffix work |

318| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

319| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

320 

321### Git subdirectories

322 

323Use `git-subdir` to point to a plugin that lives inside a subdirectory of a git repository. Claude Code uses a sparse, partial clone to fetch only the subdirectory, minimizing bandwidth for large monorepos.

324 

325```json theme={null}

326{

327 "name": "my-plugin",

328 "source": {

329 "source": "git-subdir",

330 "url": "https://github.com/acme-corp/monorepo.git",

331 "path": "tools/claude-plugin"

332 }

333}

334```

335 

336You can pin to a specific branch, tag, or commit:

337 

338```json theme={null}

339{

340 "name": "my-plugin",

341 "source": {

342 "source": "git-subdir",

343 "url": "https://github.com/acme-corp/monorepo.git",

344 "path": "tools/claude-plugin",

345 "ref": "v2.0.0",

346 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

347 }

348}

349```

350 

351The `url` field also accepts a GitHub shorthand (`owner/repo`) or SSH URLs (`git@github.com:owner/repo.git`).

352 

353| Field | Type | Description |

354| :----- | :----- | :------------------------------------------------------------------------------------------------------- |

355| `url` | string | Required. Git repository URL, GitHub `owner/repo` shorthand, or SSH URL |

356| `path` | string | Required. Subdirectory path within the repo containing the plugin (for example, `"tools/claude-plugin"`) |

290| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |357| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

291| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |358| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

292 359 

360### npm packages

361 

362Plugins distributed as npm packages are installed using `npm install`. This works with any package on the public npm registry or a private registry your team hosts.

363 

364```json theme={null}

365{

366 "name": "my-npm-plugin",

367 "source": {

368 "source": "npm",

369 "package": "@acme/claude-plugin"

370 }

371}

372```

373 

374To pin to a specific version, add the `version` field:

375 

376```json theme={null}

377{

378 "name": "my-npm-plugin",

379 "source": {

380 "source": "npm",

381 "package": "@acme/claude-plugin",

382 "version": "2.1.0"

383 }

384}

385```

386 

387To install from a private or internal registry, add the `registry` field:

388 

389```json theme={null}

390{

391 "name": "my-npm-plugin",

392 "source": {

393 "source": "npm",

394 "package": "@acme/claude-plugin",

395 "version": "^2.0.0",

396 "registry": "https://npm.example.com"

397 }

398}

399```

400 

401| Field | Type | Description |

402| :--------- | :----- | :------------------------------------------------------------------------------------------- |

403| `package` | string | Required. Package name or scoped package (for example, `@org/plugin`) |

404| `version` | string | Optional. Version or version range (for example, `2.1.0`, `^2.0.0`, `~1.5.0`) |

405| `registry` | string | Optional. Custom npm registry URL. Defaults to the system npm registry (typically npmjs.org) |

406 

293### Advanced plugin entries407### Advanced plugin entries

294 408 

295This example shows a plugin entry using many of the optional fields, including custom paths for commands, agents, hooks, and MCP servers:409This example shows a plugin entry using many of the optional fields, including custom paths for commands, agents, hooks, and MCP servers:


345 459 

346* **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root.460* **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root.

347* **`${CLAUDE_PLUGIN_ROOT}`**: Use this variable in hooks and MCP server configs to reference files within the plugin's installation directory. This is necessary because plugins are copied to a cache location when installed.461* **`${CLAUDE_PLUGIN_ROOT}`**: Use this variable in hooks and MCP server configs to reference files within the plugin's installation directory. This is necessary because plugins are copied to a cache location when installed.

348* **`strict: false`**: Since this is set to false, the plugin doesn't need its own `plugin.json`. The marketplace entry defines everything.462* **`strict: false`**: Since this is set to false, the plugin doesn't need its own `plugin.json`. The marketplace entry defines everything. See [Strict mode](#strict-mode) below.

463 

464### Strict mode

465 

466The `strict` field controls whether `plugin.json` is the authority for component definitions (commands, agents, hooks, skills, MCP servers, output styles).

467 

468| Value | Behavior |

469| :--------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |

470| `true` (default) | `plugin.json` is the authority. The marketplace entry can supplement it with additional components, and both sources are merged. |

471| `false` | The marketplace entry is the entire definition. If the plugin also has a `plugin.json` that declares components, that's a conflict and the plugin fails to load. |

472 

473**When to use each mode:**

474 

475* **`strict: true`**: the plugin has its own `plugin.json` and manages its own components. The marketplace entry can add extra commands or hooks on top. This is the default and works for most plugins.

476* **`strict: false`**: the marketplace operator wants full control. The plugin repo provides raw files, and the marketplace entry defines which of those files are exposed as commands, agents, hooks, etc. Useful when the marketplace restructures or curates a plugin's components differently than the plugin author intended.

349 477 

350## Host and distribute marketplaces478## Host and distribute marketplaces

351 479 


369 497 

370### Private repositories498### Private repositories

371 499 

372Claude Code supports installing plugins from private repositories. Set the appropriate authentication token in your environment, and Claude Code will use it when authentication is required.500Claude Code supports installing plugins from private repositories. For manual installation and updates, Claude Code uses your existing git credential helpers. If `git clone` works for a private repository in your terminal, it works in Claude Code too. Common credential helpers include `gh auth login` for GitHub, macOS Keychain, and `git-credential-store`.

501 

502Background auto-updates run at startup without credential helpers, since interactive prompts would block Claude Code from starting. To enable auto-updates for private marketplaces, set the appropriate authentication token in your environment:

373 503 

374| Provider | Environment variables | Notes |504| Provider | Environment variables | Notes |

375| :-------- | :--------------------------- | :---------------------------------------- |505| :-------- | :--------------------------- | :---------------------------------------- |


383export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx513export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

384```514```

385 515 

386Authentication tokens are only used when a repository requires authentication. Public repositories work without any tokens configured, even if tokens are present in your environment.

387 

388<Note>516<Note>

389 For CI/CD environments, configure the token as a secret environment variable. GitHub Actions automatically provides `GITHUB_TOKEN` for repositories in the same organization.517 For CI/CD environments, configure the token as a secret environment variable. GitHub Actions automatically provides `GITHUB_TOKEN` for repositories in the same organization.

390</Note>518</Note>


474}602}

475```603```

476 604 

605Allow all marketplaces from an internal git server using regex pattern matching on the host:

606 

607```json theme={null}

608{

609 "strictKnownMarketplaces": [

610 {

611 "source": "hostPattern",

612 "hostPattern": "^github\\.example\\.com$"

613 }

614 ]

615}

616```

617 

618Allow filesystem-based marketplaces from a specific directory using regex pattern matching on the path:

619 

620```json theme={null}

621{

622 "strictKnownMarketplaces": [

623 {

624 "source": "pathPattern",

625 "pathPattern": "^/opt/approved/"

626 }

627 ]

628}

629```

630 

631Use `".*"` as the `pathPattern` to allow any filesystem path while still controlling network sources with `hostPattern`.

632 

633<Note>

634 `strictKnownMarketplaces` restricts what users can add, but does not register marketplaces on its own. To make allowed marketplaces available automatically without users running `/plugin marketplace add`, pair it with [`extraKnownMarketplaces`](/en/settings#extraknownmarketplaces) in the same `managed-settings.json`. See [Using both together](/en/settings#strictknownmarketplaces).

635</Note>

636 

477#### How restrictions work637#### How restrictions work

478 638 

479Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.639Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.

480 640 

481The allowlist uses exact matching. For a marketplace to be allowed, all specified fields must match exactly:641The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly:

482 642 

483* For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist643* For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist

484* For URL sources: the full URL must match exactly644* For URL sources: the full URL must match exactly

645* For `hostPattern` sources: the marketplace host is matched against the regex pattern

646* For `pathPattern` sources: the marketplace's filesystem path is matched against the regex pattern

485 647 

486Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.648Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.

487 649 

488For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).650For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).

489 651 

652### Version resolution and release channels

653 

654Plugin versions determine cache paths and update detection. You can specify the version in the plugin manifest (`plugin.json`) or in the marketplace entry (`marketplace.json`).

655 

656<Warning>

657 When possible, avoid setting the version in both places. The plugin manifest always wins silently, which can cause the marketplace version to be ignored. For relative-path plugins, set the version in the marketplace entry. For all other plugin sources, set it in the plugin manifest.

658</Warning>

659 

660#### Set up release channels

661 

662To support "stable" and "latest" release channels for your plugins, you can set up two marketplaces that point to different refs or SHAs of the same repo. You can then assign the two marketplaces to different user groups through [managed settings](/en/settings#settings-files).

663 

664<Warning>

665 The plugin's `plugin.json` must declare a different `version` at each pinned ref or commit. If two refs or commits have the same manifest version, Claude Code treats them as identical and skips the update.

666</Warning>

667 

668##### Example

669 

670```json theme={null}

671{

672 "name": "stable-tools",

673 "plugins": [

674 {

675 "name": "code-formatter",

676 "source": {

677 "source": "github",

678 "repo": "acme-corp/code-formatter",

679 "ref": "stable"

680 }

681 }

682 ]

683}

684```

685 

686```json theme={null}

687{

688 "name": "latest-tools",

689 "plugins": [

690 {

691 "name": "code-formatter",

692 "source": {

693 "source": "github",

694 "repo": "acme-corp/code-formatter",

695 "ref": "latest"

696 }

697 }

698 ]

699}

700```

701 

702##### Assign channels to user groups

703 

704Assign each marketplace to the appropriate user group through managed settings. For example, the stable group receives:

705 

706```json theme={null}

707{

708 "extraKnownMarketplaces": {

709 "stable-tools": {

710 "source": {

711 "source": "github",

712 "repo": "acme-corp/stable-tools"

713 }

714 }

715 }

716}

717```

718 

719The early-access group receives `latest-tools` instead:

720 

721```json theme={null}

722{

723 "extraKnownMarketplaces": {

724 "latest-tools": {

725 "source": {

726 "source": "github",

727 "repo": "acme-corp/latest-tools"

728 }

729 }

730 }

731}

732```

733 

490## Validation and testing734## Validation and testing

491 735 

492Test your marketplace before sharing.736Test your marketplace before sharing.


535Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. Common errors:779Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. Common errors:

536 780 

537| Error | Cause | Solution |781| Error | Cause | Solution |

538| :------------------------------------------------ | :------------------------------ | :------------------------------------------------------------ |782| :------------------------------------------------ | :------------------------------ | :--------------------------------------------------------------------------------------------- |

539| `File not found: .claude-plugin/marketplace.json` | Missing manifest | Create `.claude-plugin/marketplace.json` with required fields |783| `File not found: .claude-plugin/marketplace.json` | Missing manifest | Create `.claude-plugin/marketplace.json` with required fields |

540| `Invalid JSON syntax: Unexpected token...` | JSON syntax error | Check for missing commas, extra commas, or unquoted strings |784| `Invalid JSON syntax: Unexpected token...` | JSON syntax error | Check for missing commas, extra commas, or unquoted strings |

541| `Duplicate plugin name "x" found in marketplace` | Two plugins share the same name | Give each plugin a unique `name` value |785| `Duplicate plugin name "x" found in marketplace` | Two plugins share the same name | Give each plugin a unique `name` value |

542| `plugins[0].source: Path traversal not allowed` | Source path contains `..` | Use paths relative to marketplace root without `..` |786| `plugins[0].source: Path contains ".."` | Source path contains `..` | Use paths relative to the marketplace root without `..`. See [Relative paths](#relative-paths) |

543 787 

544**Warnings** (non-blocking):788**Warnings** (non-blocking):

545 789 

546* `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array790* `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array

547* `No marketplace description provided`: add `metadata.description` to help users understand your marketplace791* `No marketplace description provided`: add `metadata.description` to help users understand your marketplace

548* `Plugin "x" uses npm source which is not yet fully implemented`: use `github` or local path sources instead

549 792 

550### Plugin installation failures793### Plugin installation failures

551 794 


560 803 

561### Private repository authentication fails804### Private repository authentication fails

562 805 

563**Symptoms**: Authentication errors when installing plugins from private repositories, even with tokens configured806**Symptoms**: Authentication errors when installing plugins from private repositories

564 807 

565**Solutions**:808**Solutions**:

566 809 

567* Verify your token is set in the current shell session: `echo $GITHUB_TOKEN`810For manual installation and updates:

811 

812* Verify you're authenticated with your git provider (for example, run `gh auth status` for GitHub)

813* Check that your credential helper is configured correctly: `git config --global credential.helper`

814* Try cloning the repository manually to verify your credentials work

815 

816For background auto-updates:

817 

818* Set the appropriate token in your environment: `echo $GITHUB_TOKEN`

568* Check that the token has the required permissions (read access to the repository)819* Check that the token has the required permissions (read access to the repository)

569* For GitHub, ensure the token has the `repo` scope for private repositories820* For GitHub, ensure the token has the `repo` scope for private repositories

570* For GitLab, ensure the token has at least `read_repository` scope821* For GitLab, ensure the token has at least `read_repository` scope

571* Verify the token hasn't expired822* Verify the token hasn't expired

572* If using multiple git providers, ensure you've set the token for the correct provider823 

824### Git operations time out

825 

826**Symptoms**: Plugin installation or marketplace updates fail with a timeout error like "Git clone timed out after 120s" or "Git pull timed out after 120s".

827 

828**Cause**: Claude Code uses a 120-second timeout for all git operations, including cloning plugin repositories and pulling marketplace updates. Large repositories or slow network connections may exceed this limit.

829 

830**Solution**: Increase the timeout using the `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` environment variable. The value is in milliseconds:

831 

832```bash theme={null}

833export CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS=300000 # 5 minutes

834```

573 835 

574### Plugins with relative paths fail in URL-based marketplaces836### Plugins with relative paths fail in URL-based marketplaces

575 837 


602* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas864* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas

603* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options865* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options

604* [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions866* [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions

605 

606 

607 

608> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

plugins.md +44 −20

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Create plugins5# Create plugins

2 6 

3> Create custom plugins to extend Claude Code with skills, agents, hooks, and MCP servers.7> Create custom plugins to extend Claude Code with skills, agents, hooks, and MCP servers.


20* You're customizing Claude Code for a single project24* You're customizing Claude Code for a single project

21* The configuration is personal and doesn't need to be shared25* The configuration is personal and doesn't need to be shared

22* You're experimenting with skills or hooks before packaging them26* You're experimenting with skills or hooks before packaging them

23* You want short skill names like `/hello` or `/review`27* You want short skill names like `/hello` or `/deploy`

24 28 

25**Use plugins when**:29**Use plugins when**:

26 30 


118 claude --plugin-dir ./my-first-plugin122 claude --plugin-dir ./my-first-plugin

119 ```123 ```

120 124 

121 Once Claude Code starts, try your new command:125 Once Claude Code starts, try your new skill:

122 126 

123 ```shell theme={null}127 ```shell theme={null}

124 /my-first-plugin:hello128 /my-first-plugin:hello

125 ```129 ```

126 130 

127 You'll see Claude respond with a greeting. Run `/help` to see your command listed under the plugin namespace.131 You'll see Claude respond with a greeting. Run `/help` to see your skill listed under the plugin namespace.

128 132 

129 <Note>133 <Note>

130 **Why namespacing?** Plugin skills are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have skills with the same name.134 **Why namespacing?** Plugin skills are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have skills with the same name.


136 <Step title="Add skill arguments">140 <Step title="Add skill arguments">

137 Make your skill dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the skill name.141 Make your skill dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the skill name.

138 142 

139 Update your `hello.md` file:143 Update your `SKILL.md` file:

140 144 

141 ```markdown my-first-plugin/commands/hello.md theme={null}145 ```markdown my-first-plugin/skills/hello/SKILL.md theme={null}

142 ---146 ---

143 description: Greet the user with a personalized message147 description: Greet the user with a personalized message

144 ---148 ---

145 149 

146 # Hello Command150 # Hello Skill

147 151 

148 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.152 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.

149 ```153 ```

150 154 

151 Restart Claude Code to pick up the changes, then try the command with your name:155 Run `/reload-plugins` to pick up the changes, then try the skill with your name:

152 156 

153 ```shell theme={null}157 ```shell theme={null}

154 /my-first-plugin:hello Alex158 /my-first-plugin:hello Alex


161You've successfully created and tested a plugin with these key components:165You've successfully created and tested a plugin with these key components:

162 166 

163* **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata167* **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata

164* **Commands directory** (`commands/`): contains your custom skills168* **Skills directory** (`skills/`): contains your custom skills

165* **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior169* **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior

166 170 

167<Tip>171<Tip>


177</Warning>181</Warning>

178 182 

179| Directory | Location | Purpose |183| Directory | Location | Purpose |

180| :---------------- | :---------- | :---------------------------------------------- |184| :---------------- | :---------- | :----------------------------------------------------------------------------- |

181| `.claude-plugin/` | Plugin root | Contains only `plugin.json` manifest (required) |185| `.claude-plugin/` | Plugin root | Contains `plugin.json` manifest (optional if components use default locations) |

182| `commands/` | Plugin root | Skills as Markdown files |186| `commands/` | Plugin root | Skills as Markdown files |

183| `agents/` | Plugin root | Custom agent definitions |187| `agents/` | Plugin root | Custom agent definitions |

184| `skills/` | Plugin root | Agent Skills with `SKILL.md` files |188| `skills/` | Plugin root | Agent Skills with `SKILL.md` files |

185| `hooks/` | Plugin root | Event handlers in `hooks.json` |189| `hooks/` | Plugin root | Event handlers in `hooks.json` |

186| `.mcp.json` | Plugin root | MCP server configurations |190| `.mcp.json` | Plugin root | MCP server configurations |

187| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |191| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |

192| `settings.json` | Plugin root | Default [settings](/en/settings) applied when the plugin is enabled |

188 193 

189<Note>194<Note>

190 **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference).195 **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference).


200 205 

201Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:206Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:

202 207 

203```208```text theme={null}

204my-plugin/209my-plugin/

205├── .claude-plugin/210├── .claude-plugin/

206│ └── plugin.json211│ └── plugin.json


2244. Test coverage2294. Test coverage

225```230```

226 231 

227After installing the plugin, restart Claude Code to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills).232After installing the plugin, run `/reload-plugins` to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills).

228 233 

229### Add LSP servers to your plugin234### Add LSP servers to your plugin

230 235 


250 255 

251For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers).256For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers).

252 257 

258### Ship default settings with your plugin

259 

260Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` key is supported.

261 

262Setting `agent` activates one of the plugin's [custom agents](/en/sub-agents) as the main thread, applying its system prompt, tool restrictions, and model. This lets a plugin change how Claude Code behaves by default when enabled.

263 

264```json settings.json theme={null}

265{

266 "agent": "security-reviewer"

267}

268```

269 

270This example activates the `security-reviewer` agent defined in the plugin's `agents/` directory. Settings from `settings.json` take priority over `settings` declared in `plugin.json`. Unknown keys are silently ignored.

271 

253### Organize complex plugins272### Organize complex plugins

254 273 

255For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/plugins-reference#plugin-directory-structure).274For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/plugins-reference#plugin-directory-structure).


262claude --plugin-dir ./my-plugin281claude --plugin-dir ./my-plugin

263```282```

264 283 

265As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components:284When a `--plugin-dir` plugin has the same name as an installed marketplace plugin, the local copy takes precedence for that session. This lets you test changes to a plugin you already have installed without uninstalling it first. Marketplace plugins force-enabled by managed settings are the only exception and cannot be overridden.

285 

286As you make changes to your plugin, run `/reload-plugins` to pick up the updates without restarting. This reloads commands, skills, agents, hooks, plugin MCP servers, and plugin LSP servers. Test your plugin components:

266 287 

267* Try your commands with `/command-name`288* Try your skills with `/plugin-name:skill-name`

268* Check that agents appear in `/agents`289* Check that agents appear in `/agents`

269* Verify hooks work as expected290* Verify hooks work as expected

270 291 


295 316 

296Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins).317Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins).

297 318 

319### Submit your plugin to the official marketplace

320 

321To submit a plugin to the official Anthropic marketplace, use one of the in-app submission forms:

322 

323* **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

324* **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

325 

298<Note>326<Note>

299 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).327 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).

300</Note>328</Note>


346 mkdir my-plugin/hooks374 mkdir my-plugin/hooks

347 ```375 ```

348 376 

349 Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`the format is the same:377 Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`, since the format is the same. The command receives hook input as JSON on stdin, so use `jq` to extract the file path:

350 378 

351 ```json my-plugin/hooks/hooks.json theme={null}379 ```json my-plugin/hooks/hooks.json theme={null}

352 {380 {


354 "PostToolUse": [382 "PostToolUse": [

355 {383 {

356 "matcher": "Write|Edit",384 "matcher": "Write|Edit",

357 "hooks": [{ "type": "command", "command": "npm run lint:fix $FILE" }]385 "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }]

358 }386 }

359 ]387 ]

360 }388 }


404 * [Subagents](/en/sub-agents): agent configuration and capabilities432 * [Subagents](/en/sub-agents): agent configuration and capabilities

405 * [Hooks](/en/hooks): event handling and automation433 * [Hooks](/en/hooks): event handling and automation

406 * [MCP](/en/mcp): external tool integration434 * [MCP](/en/mcp): external tool integration

407 

408 

409 

410> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Plugins reference5# Plugins reference

2 6 

3> Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications.7> Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications.


8 12 

9This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.13This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.

10 14 

11## Plugin components reference15A **plugin** is a self-contained directory of components that extends Claude Code with custom functionality. Plugin components include skills, agents, hooks, MCP servers, and LSP servers.

12 16 

13This section documents the types of components that plugins can provide.17## Plugin components reference

14 18 

15### Skills19### Skills

16 20 


22 26 

23**Skill structure**:27**Skill structure**:

24 28 

25```29```text theme={null}

26skills/30skills/

27├── pdf-processor/31├── pdf-processor/

28│ ├── SKILL.md32│ ├── SKILL.md


52 56 

53```markdown theme={null}57```markdown theme={null}

54---58---

55description: What this agent specializes in59name: agent-name

56capabilities: ["task1", "task2", "task3"]60description: What this agent specializes in and when Claude should invoke it

57---61---

58 62 

59# Agent Name63Detailed system prompt for the agent describing its role, expertise, and behavior.

60 

61Detailed description of the agent's role, expertise, and when Claude should invoke it.

62 

63## Capabilities

64- Specific task the agent excels at

65- Another specialized capability

66- When to use this agent vs others

67 

68## Context and examples

69Provide examples of when this agent should be used and what kinds of problems it solves.

70```64```

71 65 

72**Integration points**:66**Integration points**:


76* Agents can be invoked manually by users70* Agents can be invoked manually by users

77* Plugin agents work alongside built-in Claude agents71* Plugin agents work alongside built-in Claude agents

78 72 

73For complete details, see [Subagents](/en/sub-agents).

74 

79### Hooks75### Hooks

80 76 

81Plugins can provide event handlers that respond to Claude Code events automatically.77Plugins can provide event handlers that respond to Claude Code events automatically.


115* `Stop`: When Claude attempts to stop111* `Stop`: When Claude attempts to stop

116* `SubagentStart`: When a subagent is started112* `SubagentStart`: When a subagent is started

117* `SubagentStop`: When a subagent attempts to stop113* `SubagentStop`: When a subagent attempts to stop

118* `Setup`: When `--init`, `--init-only`, or `--maintenance` flags are used

119* `SessionStart`: At the beginning of sessions114* `SessionStart`: At the beginning of sessions

120* `SessionEnd`: At the end of sessions115* `SessionEnd`: At the end of sessions

116* `TeammateIdle`: When an agent team teammate is about to go idle

117* `TaskCompleted`: When a task is being marked as completed

121* `PreCompact`: Before conversation history is compacted118* `PreCompact`: Before conversation history is compacted

122 119 

123**Hook types**:120**Hook types**:


165### LSP servers162### LSP servers

166 163 

167<Tip>164<Tip>

168 Looking to use LSP plugins? Install them from the official marketplacesearch for "lsp" in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace.165 Looking to use LSP plugins? Install them from the official marketplace: search for "lsp" in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace.

169</Tip>166</Tip>

170 167 

171Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase.168Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase.


254When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:251When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:

255 252 

256| Scope | Settings file | Use case |253| Scope | Settings file | Use case |

257| :-------- | :---------------------------- | :------------------------------------------------------- |254| :-------- | :---------------------------------------------- | :------------------------------------------------------- |

258| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |255| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |

259| `project` | `.claude/settings.json` | Team plugins shared via version control |256| `project` | `.claude/settings.json` | Team plugins shared via version control |

260| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |257| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |

261| `managed` | `managed-settings.json` | Managed plugins (read-only, update only) |258| `managed` | [Managed settings](/en/settings#settings-files) | Managed plugins (read-only, update only) |

262 259 

263Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/en/settings#configuration-scopes).260Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/en/settings#configuration-scopes).

264 261 


266 263 

267## Plugin manifest schema264## Plugin manifest schema

268 265 

269The `plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.266The `.claude-plugin/plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.

267 

268The manifest is optional. If omitted, Claude Code auto-discovers components in [default locations](#file-locations-reference) and derives the plugin name from the directory name. Use a manifest when you need to provide metadata or custom component paths.

270 269 

271### Complete schema270### Complete schema

272 271 


296 295 

297### Required fields296### Required fields

298 297 

298If you include a manifest, `name` is the only required field.

299 

299| Field | Type | Description | Example |300| Field | Type | Description | Example |

300| :----- | :----- | :---------------------------------------- | :------------------- |301| :----- | :----- | :---------------------------------------- | :------------------- |

301| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |302| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |

302 303 

304This name is used for namespacing components. For example, in the UI, the

305agent `agent-creator` for the plugin with name `plugin-dev` will appear as

306`plugin-dev:agent-creator`.

307 

303### Metadata fields308### Metadata fields

304 309 

305| Field | Type | Description | Example |310| Field | Type | Description | Example |

306| :------------ | :----- | :---------------------------------- | :------------------------------------------------- |311| :------------ | :----- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |

307| `version` | string | Semantic version | `"2.1.0"` |312| `version` | string | Semantic version. If also set in the marketplace entry, `plugin.json` takes priority. You only need to set it in one place. | `"2.1.0"` |

308| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |313| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |

309| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |314| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |

310| `homepage` | string | Documentation URL | `"https://docs.example.com"` |315| `homepage` | string | Documentation URL | `"https://docs.example.com"` |


315### Component path fields320### Component path fields

316 321 

317| Field | Type | Description | Example |322| Field | Type | Description | Example |

318| :------------- | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- |323| :------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- |

319| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |324| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |

320| `agents` | string\|array | Additional agent files | `"./custom/agents/"` |325| `agents` | string\|array | Additional agent files | `"./custom/agents/reviewer.md"` |

321| `skills` | string\|array | Additional skill directories | `"./custom/skills/"` |326| `skills` | string\|array | Additional skill directories | `"./custom/skills/"` |

322| `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` |327| `hooks` | string\|array\|object | Hook config paths or inline config | `"./my-extra-hooks.json"` |

323| `mcpServers` | string\|object | MCP config path or inline config | `"./mcp-config.json"` |328| `mcpServers` | string\|array\|object | MCP config paths or inline config | `"./my-extra-mcp-config.json"` |

324| `outputStyles` | string\|array | Additional output style files/directories | `"./styles/"` |329| `outputStyles` | string\|array | Additional output style files/directories | `"./styles/"` |

325| `lspServers` | string\|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) config for code intelligence (go to definition, find references, etc.) | `"./.lsp.json"` |330| `lspServers` | string\|array\|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) configs for code intelligence (go to definition, find references, etc.) | `"./.lsp.json"` |

326 331 

327### Path behavior rules332### Path behavior rules

328 333 


373 378 

374## Plugin caching and file resolution379## Plugin caching and file resolution

375 380 

376For security and verification purposes, Claude Code copies plugins to a cache directory rather than using them in-place. Understanding this behavior is important when developing plugins that reference external files.381Plugins are specified in one of two ways:

377 

378### How plugin caching works

379 382 

380When you install a plugin, Claude Code copies the plugin files to a cache directory:383* Through `claude --plugin-dir`, for the duration of a session.

384* Through a marketplace, installed for future sessions.

381 385 

382* **For marketplace plugins with relative paths**: The path specified in the `source` field is copied recursively. For example, if your marketplace entry specifies `"source": "./plugins/my-plugin"`, the entire `./plugins` directory is copied.386For security and verification purposes, Claude Code copies *marketplace* plugins to the user's local **plugin cache** (`~/.claude/plugins/cache`) rather than using them in-place. Understanding this behavior is important when developing plugins that reference external files.

383* **For plugins with `.claude-plugin/plugin.json`**: The implicit root directory (the directory containing `.claude-plugin/plugin.json`) is copied recursively.

384 387 

385### Path traversal limitations388### Path traversal limitations

386 389 

387Plugins cannot reference files outside their copied directory structure. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache.390Installed plugins cannot reference files outside their directory. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache.

388 391 

389### Working with external dependencies392### Working with external dependencies

390 393 

391If your plugin needs to access files outside its directory, you have two options:394If your plugin needs to access files outside its directory, you can create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process:

392 

393**Option 1: Use symlinks**

394 

395Create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process:

396 395 

397```bash theme={null}396```bash theme={null}

398# Inside your plugin directory397# Inside your plugin directory

399ln -s /path/to/shared-utils ./shared-utils398ln -s /path/to/shared-utils ./shared-utils

400```399```

401 400 

402The symlinked content will be copied into the plugin cache.401The symlinked content will be copied into the plugin cache. This provides flexibility while maintaining the security benefits of the caching system.

403 

404**Option 2: Restructure your marketplace**

405 

406Set the plugin path to a parent directory that contains all required files, then provide the rest of the plugin manifest directly in the marketplace entry:

407 

408```json theme={null}

409{

410 "name": "my-plugin",

411 "source": "./",

412 "description": "Plugin that needs root-level access",

413 "commands": ["./plugins/my-plugin/commands/"],

414 "agents": ["./plugins/my-plugin/agents/"],

415 "strict": false

416}

417```

418 

419This approach copies the entire marketplace root, giving your plugin access to sibling directories.

420 

421<Note>

422 Symlinks that point to locations outside the plugin's logical root are followed during copying. This provides flexibility while maintaining the security benefits of the caching system.

423</Note>

424 402 

425***403***

426 404 


430 408 

431A complete plugin follows this structure:409A complete plugin follows this structure:

432 410 

433```411```text theme={null}

434enterprise-plugin/412enterprise-plugin/

435├── .claude-plugin/ # Metadata directory413├── .claude-plugin/ # Metadata directory (optional)

436│ └── plugin.json # Required: plugin manifest414│ └── plugin.json # plugin manifest

437├── commands/ # Default command location415├── commands/ # Default command location

438│ ├── status.md416│ ├── status.md

439│ └── logs.md417│ └── logs.md


450├── hooks/ # Hook configurations428├── hooks/ # Hook configurations

451│ ├── hooks.json # Main hook config429│ ├── hooks.json # Main hook config

452│ └── security-hooks.json # Additional hooks430│ └── security-hooks.json # Additional hooks

431├── settings.json # Default settings for the plugin

453├── .mcp.json # MCP server definitions432├── .mcp.json # MCP server definitions

454├── .lsp.json # LSP server configurations433├── .lsp.json # LSP server configurations

455├── scripts/ # Hook and utility scripts434├── scripts/ # Hook and utility scripts


467### File locations reference446### File locations reference

468 447 

469| Component | Default Location | Purpose |448| Component | Default Location | Purpose |

470| :-------------- | :--------------------------- | :---------------------------------------------------------- |449| :-------------- | :--------------------------- | :------------------------------------------------------------------------------------------------------------------------ |

471| **Manifest** | `.claude-plugin/plugin.json` | Required metadata file |450| **Manifest** | `.claude-plugin/plugin.json` | Plugin metadata and configuration (optional) |

472| **Commands** | `commands/` | Skill Markdown files (legacy; use `skills/` for new skills) |451| **Commands** | `commands/` | Skill Markdown files (legacy; use `skills/` for new skills) |

473| **Agents** | `agents/` | Subagent Markdown files |452| **Agents** | `agents/` | Subagent Markdown files |

474| **Skills** | `skills/` | Skills with `<name>/SKILL.md` structure |453| **Skills** | `skills/` | Skills with `<name>/SKILL.md` structure |

475| **Hooks** | `hooks/hooks.json` | Hook configuration |454| **Hooks** | `hooks/hooks.json` | Hook configuration |

476| **MCP servers** | `.mcp.json` | MCP server definitions |455| **MCP servers** | `.mcp.json` | MCP server definitions |

477| **LSP servers** | `.lsp.json` | Language server configurations |456| **LSP servers** | `.lsp.json` | Language server configurations |

457| **Settings** | `settings.json` | Default configuration applied when the plugin is enabled. Only [`agent`](/en/sub-agents) settings are currently supported |

478 458 

479***459***

480 460 


501| `-s, --scope <scope>` | Installation scope: `user`, `project`, or `local` | `user` |481| `-s, --scope <scope>` | Installation scope: `user`, `project`, or `local` | `user` |

502| `-h, --help` | Display help for command | |482| `-h, --help` | Display help for command | |

503 483 

484Scope determines which settings file the installed plugin is added to. For example, --scope project writes to `enabledPlugins` in .claude/settings.json, making the plugin available to everyone who clones the project repository.

485 

504**Examples:**486**Examples:**

505 487 

506```bash theme={null}488```bash theme={null}


598 580 

599### Debugging commands581### Debugging commands

600 582 

601Use `claude --debug` to see plugin loading details:583Use `claude --debug` (or `/debug` within the TUI) to see plugin loading details:

602 

603```bash theme={null}

604claude --debug

605```

606 584 

607This shows:585This shows:

608 586 


634 612 

635* `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`: command path exists but contains no valid command files613* `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`: command path exists but contains no valid command files

636* `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`: the `source` path in marketplace.json points to a non-existent directory614* `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`: the `source` path in marketplace.json points to a non-existent directory

637* `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`: remove duplicate component definitions or set `strict: true` in marketplace entry615* `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`: remove duplicate component definitions or remove `strict: false` in marketplace entry

638 616 

639### Hook troubleshooting617### Hook troubleshooting

640 618 


672 650 

673**Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`.651**Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`.

674 652 

675```653```text theme={null}

676my-plugin/654my-plugin/

677├── .claude-plugin/655├── .claude-plugin/

678│ └── plugin.json ← Only manifest here656│ └── plugin.json ← Only manifest here


717* Document changes in a `CHANGELOG.md` file695* Document changes in a `CHANGELOG.md` file

718* Use pre-release versions like `2.0.0-beta.1` for testing696* Use pre-release versions like `2.0.0-beta.1` for testing

719 697 

698<Warning>

699 Claude Code uses the version to determine whether to update your plugin. If you change your plugin's code but don't bump the version in `plugin.json`, your plugin's existing users won't see your changes due to caching.

700 

701 If your plugin is within a [marketplace](/en/plugin-marketplaces) directory, you can manage the version through `marketplace.json` instead and omit the `version` field from `plugin.json`.

702</Warning>

703 

720***704***

721 705 

722## See also706## See also


728* [Hooks](/en/hooks) - Event handling and automation712* [Hooks](/en/hooks) - Event handling and automation

729* [MCP](/en/mcp) - External tool integration713* [MCP](/en/mcp) - External tool integration

730* [Settings](/en/settings) - Configuration options for plugins714* [Settings](/en/settings) - Configuration options for plugins

731 

732 

733 

734> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

quickstart.md +81 −89

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Quickstart5# Quickstart

2 6 

3> Welcome to Claude Code!7> Welcome to Claude Code!

4 8 

5This quickstart guide will have you using AI-powered coding assistance in just a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.9This quickstart guide will have you using AI-powered coding assistance in a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.

6 10 

7## Before you begin11## Before you begin

8 12 

9Make sure you have:13Make sure you have:

10 14 

11* A terminal or command prompt open15* A terminal or command prompt open

16 * If you've never used the terminal before, check out the [terminal guide](/en/terminal-guide)

12* A code project to work with17* A code project to work with

13* A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise) or [Claude Console](https://console.anthropic.com/) account18* A [Claude subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq) (Pro, Max, Teams, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/en/third-party-integrations)

19 

20<Note>

21 This guide covers the terminal CLI. Claude Code is also available on the [web](https://claude.ai/code), as a [desktop app](/en/desktop), in [VS Code](/en/vs-code) and [JetBrains IDEs](/en/jetbrains), in [Slack](/en/slack), and in CI/CD with [GitHub Actions](/en/github-actions) and [GitLab](/en/gitlab-ci-cd). See [all interfaces](/en/overview#use-claude-code-everywhere).

22</Note>

14 23 

15## Step 1: Install Claude Code24## Step 1: Install Claude Code

16 25 


36 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

37 ```46 ```

38 47 

48 **Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it.

49 

39 <Info>50 <Info>

40 Native installations automatically update in the background to keep you on the latest version.51 Native installations automatically update in the background to keep you on the latest version.

41 </Info>52 </Info>

42 </Tab>53 </Tab>

43 54 

44 <Tab title="Homebrew">55 <Tab title="Homebrew">

45 ```sh theme={null}56 ```bash theme={null}

46 brew install --cask claude-code57 brew install --cask claude-code

47 ```58 ```

48 59 


78 89 

79You can log in using any of these account types:90You can log in using any of these account types:

80 91 

81* [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended)92* [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login) (recommended)

82* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits)93* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits). On first login, a "Claude Code" workspace is automatically created in the Console for centralized cost tracking.

94* [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) (enterprise cloud providers)

83 95 

84Once logged in, your credentials are stored and you won't need to log in again.96Once logged in, your credentials are stored and you won't need to log in again. To switch accounts later, use the `/login` command.

85 

86<Note>

87 When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization.

88</Note>

89 

90<Note>

91 You can have both account types under the same email address. If you need to log in again or switch accounts, use the `/login` command within Claude Code.

92</Note>

93 97 

94## Step 3: Start your first session98## Step 3: Start your first session

95 99 


103You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.107You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.

104 108 

105<Tip>109<Tip>

106 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/iam#credential-management).110 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/authentication#credential-management).

107</Tip>111</Tip>

108 112 

109## Step 4: Ask your first question113## Step 4: Ask your first question

110 114 

111Let's start with understanding your codebase. Try one of these commands:115Let's start with understanding your codebase. Try one of these commands:

112 116 

113```117```text theme={null}

114> what does this project do?118what does this project do?

115```119```

116 120 

117Claude will analyze your files and provide a summary. You can also ask more specific questions:121Claude will analyze your files and provide a summary. You can also ask more specific questions:

118 122 

119```123```text theme={null}

120> what technologies does this project use?124what technologies does this project use?

121```125```

122 126 

123```127```text theme={null}

124> where is the main entry point?128where is the main entry point?

125```129```

126 130 

127```131```text theme={null}

128> explain the folder structure132explain the folder structure

129```133```

130 134 

131You can also ask Claude about its own capabilities:135You can also ask Claude about its own capabilities:

132 136 

133```137```text theme={null}

134> what can Claude Code do?138what can Claude Code do?

135```139```

136 140 

137```141```text theme={null}

138> how do I create custom skills in Claude Code?142how do I create custom skills in Claude Code?

139```143```

140 144 

141```145```text theme={null}

142> can Claude Code work with Docker?146can Claude Code work with Docker?

143```147```

144 148 

145<Note>149<Note>

146 Claude Code reads your files as needed - you don't have to manually add context. Claude also has access to its own documentation and can answer questions about its features and capabilities.150 Claude Code reads your project files as needed. You don't have to manually add context.

147</Note>151</Note>

148 152 

149## Step 5: Make your first code change153## Step 5: Make your first code change

150 154 

151Now let's make Claude Code do some actual coding. Try a simple task:155Now let's make Claude Code do some actual coding. Try a simple task:

152 156 

153```157```text theme={null}

154> add a hello world function to the main file158add a hello world function to the main file

155```159```

156 160 

157Claude Code will:161Claude Code will:


169 173 

170Claude Code makes Git operations conversational:174Claude Code makes Git operations conversational:

171 175 

172```176```text theme={null}

173> what files have I changed?177what files have I changed?

174```178```

175 179 

176```180```text theme={null}

177> commit my changes with a descriptive message181commit my changes with a descriptive message

178```182```

179 183 

180You can also prompt for more complex Git operations:184You can also prompt for more complex Git operations:

181 185 

182```186```text theme={null}

183> create a new branch called feature/quickstart187create a new branch called feature/quickstart

184```188```

185 189 

186```190```text theme={null}

187> show me the last 5 commits191show me the last 5 commits

188```192```

189 193 

190```194```text theme={null}

191> help me resolve merge conflicts195help me resolve merge conflicts

192```196```

193 197 

194## Step 7: Fix a bug or add a feature198## Step 7: Fix a bug or add a feature


197 201 

198Describe what you want in natural language:202Describe what you want in natural language:

199 203 

200```204```text theme={null}

201> add input validation to the user registration form205add input validation to the user registration form

202```206```

203 207 

204Or fix existing issues:208Or fix existing issues:

205 209 

206```210```text theme={null}

207> there's a bug where users can submit empty forms - fix it211there's a bug where users can submit empty forms - fix it

208```212```

209 213 

210Claude Code will:214Claude Code will:


220 224 

221**Refactor code**225**Refactor code**

222 226 

223```227```text theme={null}

224> refactor the authentication module to use async/await instead of callbacks228refactor the authentication module to use async/await instead of callbacks

225```229```

226 230 

227**Write tests**231**Write tests**

228 232 

229```233```text theme={null}

230> write unit tests for the calculator functions234write unit tests for the calculator functions

231```235```

232 236 

233**Update documentation**237**Update documentation**

234 238 

235```239```text theme={null}

236> update the README with installation instructions240update the README with installation instructions

237```241```

238 242 

239**Code review**243**Code review**

240 244 

241```245```text theme={null}

242> review my changes and suggest improvements246review my changes and suggest improvements

243```247```

244 248 

245<Tip>249<Tip>

246 **Remember**: Claude Code is your AI pair programmer. Talk to it like you would a helpful colleague - describe what you want to achieve, and it will help you get there.250 Talk to Claude like you would a helpful colleague. Describe what you want to achieve, and it will help you get there.

247</Tip>251</Tip>

248 252 

249## Essential commands253## Essential commands


258| `claude -c` | Continue most recent conversation in current directory | `claude -c` |262| `claude -c` | Continue most recent conversation in current directory | `claude -c` |

259| `claude -r` | Resume a previous conversation | `claude -r` |263| `claude -r` | Resume a previous conversation | `claude -r` |

260| `claude commit` | Create a Git commit | `claude commit` |264| `claude commit` | Create a Git commit | `claude commit` |

261| `/clear` | Clear conversation history | `> /clear` |265| `/clear` | Clear conversation history | `/clear` |

262| `/help` | Show available commands | `> /help` |266| `/help` | Show available commands | `/help` |

263| `exit` or Ctrl+C | Exit Claude Code | `> exit` |267| `exit` or Ctrl+C | Exit Claude Code | `exit` |

264 268 

265See the [CLI reference](/en/cli-reference) for a complete list of commands.269See the [CLI reference](/en/cli-reference) for a complete list of commands.

266 270 

267## Pro tips for beginners271## Pro tips for beginners

268 272 

273For more, see [best practices](/en/best-practices) and [common workflows](/en/common-workflows).

274 

269<AccordionGroup>275<AccordionGroup>

270 <Accordion title="Be specific with your requests">276 <Accordion title="Be specific with your requests">

271 Instead of: "fix the bug"277 Instead of: "fix the bug"


276 <Accordion title="Use step-by-step instructions">282 <Accordion title="Use step-by-step instructions">

277 Break complex tasks into steps:283 Break complex tasks into steps:

278 284 

279 ```285 ```text theme={null}

280 > 1. create a new database table for user profiles286 1. create a new database table for user profiles

281 ```287 2. create an API endpoint to get and update user profiles

282 288 3. build a webpage that allows users to see and edit their information

283 ```

284 > 2. create an API endpoint to get and update user profiles

285 ```

286 

287 ```

288 > 3. build a webpage that allows users to see and edit their information

289 ```289 ```

290 </Accordion>290 </Accordion>

291 291 

292 <Accordion title="Let Claude explore first">292 <Accordion title="Let Claude explore first">

293 Before making changes, let Claude understand your code:293 Before making changes, let Claude understand your code:

294 294 

295 ```295 ```text theme={null}

296 > analyze the database schema296 analyze the database schema

297 ```297 ```

298 298 

299 ```299 ```text theme={null}

300 > build a dashboard showing products that are most frequently returned by our UK customers300 build a dashboard showing products that are most frequently returned by our UK customers

301 ```301 ```

302 </Accordion>302 </Accordion>

303 303 


313 313 

314Now that you've learned the basics, explore more advanced features:314Now that you've learned the basics, explore more advanced features:

315 315 

316<CardGroup cols={3}>316<CardGroup cols={2}>

317 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">317 <Card title="How Claude Code works" icon="microchip" href="/en/how-claude-code-works">

318 Step-by-step guides for common tasks318 Understand the agentic loop, built-in tools, and how Claude Code interacts with your project

319 </Card>

320 

321 <Card title="CLI reference" icon="terminal" href="/en/cli-reference">

322 Master all commands and options

323 </Card>319 </Card>

324 320 

325 <Card title="Configuration" icon="gear" href="/en/settings">321 <Card title="Best practices" icon="star" href="/en/best-practices">

326 Customize Claude Code for your workflow322 Get better results with effective prompting and project setup

327 </Card>323 </Card>

328 324 

329 <Card title="Claude Code on the web" icon="cloud" href="/en/claude-code-on-the-web">325 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">

330 Run tasks asynchronously in the cloud326 Step-by-step guides for common tasks

331 </Card>327 </Card>

332 328 

333 <Card title="About Claude Code" icon="sparkles" href="https://claude.com/product/claude-code">329 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">

334 Learn more on claude.com330 Customize with CLAUDE.md, skills, hooks, MCP, and more

335 </Card>331 </Card>

336</CardGroup>332</CardGroup>

337 333 


340* **In Claude Code**: Type `/help` or ask "how do I..."336* **In Claude Code**: Type `/help` or ask "how do I..."

341* **Documentation**: You're here! Browse other guides337* **Documentation**: You're here! Browse other guides

342* **Community**: Join our [Discord](https://www.anthropic.com/discord) for tips and support338* **Community**: Join our [Discord](https://www.anthropic.com/discord) for tips and support

343 

344 

345 

346> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

remote-control.md +137 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Continue local sessions from any device with Remote Control

6 

7> Continue a local Claude Code session from your phone, tablet, or any browser using Remote Control. Works with claude.ai/code and the Claude mobile app.

8 

9<Note>

10 Remote Control is available on all plans. Team and Enterprise admins must first enable Claude Code in [admin settings](https://claude.ai/admin-settings/claude-code).

11</Note>

12 

13Remote Control connects [claude.ai/code](https://claude.ai/code) or the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer.

14 

15When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so nothing moves to the cloud. With Remote Control you can:

16 

17* **Use your full local environment remotely**: your filesystem, [MCP servers](/en/mcp), tools, and project configuration all stay available

18* **Work from both surfaces at once**: the conversation stays in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably

19* **Survive interruptions**: if your laptop sleeps or your network drops, the session reconnects automatically when your machine comes back online

20 

21Unlike [Claude Code on the web](/en/claude-code-on-the-web), which runs on cloud infrastructure, Remote Control sessions run directly on your machine and interact with your local filesystem. The web and mobile interfaces are just a window into that local session.

22 

23<Note>

24 Remote Control requires Claude Code v2.1.51 or later. Check your version with `claude --version`.

25</Note>

26 

27This page covers setup, how to start and connect to sessions, and how Remote Control compares to Claude Code on the web.

28 

29## Requirements

30 

31Before using Remote Control, confirm that your environment meets these conditions:

32 

33* **Subscription**: available on Pro, Max, Team, and Enterprise plans. Team and Enterprise admins must first enable Claude Code in [admin settings](https://claude.ai/admin-settings/claude-code). API keys are not supported.

34* **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven't already.

35* **Workspace trust**: run `claude` in your project directory at least once to accept the workspace trust dialog.

36 

37## Start a Remote Control session

38 

39You can start a dedicated Remote Control server, start an interactive session with Remote Control enabled, or connect a session that's already running.

40 

41<Tabs>

42 <Tab title="Server mode">

43 Navigate to your project directory and run:

44 

45 ```bash theme={null}

46 claude remote-control

47 ```

48 

49 The process stays running in your terminal in server mode, waiting for remote connections. It displays a session URL you can use to [connect from another device](#connect-from-another-device), and you can press spacebar to show a QR code for quick access from your phone. While a remote session is active, the terminal shows connection status and tool activity.

50 

51 Available flags:

52 

53 | Flag | Description |

54 | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

55 | `--name "My Project"` | Set a custom session title visible in the session list at claude.ai/code. |

56 | `--spawn <mode>` | How concurrent sessions are created. Press `w` at runtime to toggle.<br />• `same-dir` (default): all sessions share the current working directory, so they can conflict if editing the same files.<br />• `worktree`: each on-demand session gets its own [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Requires a git repository. |

57 | `--capacity <N>` | Maximum number of concurrent sessions. Default is 32. |

58 | `--verbose` | Show detailed connection and session logs. |

59 | `--sandbox` / `--no-sandbox` | Enable or disable [sandboxing](/en/sandboxing) for filesystem and network isolation. Off by default. |

60 </Tab>

61 

62 <Tab title="Interactive session">

63 To start a normal interactive Claude Code session with Remote Control enabled, use the `--remote-control` flag (or `--rc`):

64 

65 ```bash theme={null}

66 claude --remote-control

67 ```

68 

69 Optionally pass a name for the session:

70 

71 ```bash theme={null}

72 claude --remote-control "My Project"

73 ```

74 

75 This gives you a full interactive session in your terminal that you can also control from claude.ai or the Claude app. Unlike `claude remote-control` (server mode), you can type messages locally while the session is also available remotely.

76 </Tab>

77 

78 <Tab title="From an existing session">

79 If you're already in a Claude Code session and want to continue it remotely, use the `/remote-control` (or `/rc`) command:

80 

81 ```text theme={null}

82 /remote-control

83 ```

84 

85 Pass a name as an argument to set a custom session title:

86 

87 ```text theme={null}

88 /remote-control My Project

89 ```

90 

91 This starts a Remote Control session that carries over your current conversation history and displays a session URL and QR code you can use to [connect from another device](#connect-from-another-device). The `--verbose`, `--sandbox`, and `--no-sandbox` flags are not available with this command.

92 </Tab>

93</Tabs>

94 

95### Connect from another device

96 

97Once a Remote Control session is active, you have a few ways to connect from another device:

98 

99* **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code). Both `claude remote-control` and `/remote-control` display this URL in the terminal.

100* **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.

101* **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. Remote Control sessions show a computer icon with a green status dot when online.

102 

103The remote session takes its name from the `--name` argument (or the name passed to `/remote-control`), your last message, your `/rename` value, or "Remote Control session" if there's no conversation history. If the environment already has an active session, you'll be asked whether to continue it or start a new one.

104 

105If you don't have the Claude app yet, use the `/mobile` command inside Claude Code to display a download QR code for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude).

106 

107### Enable Remote Control for all sessions

108 

109By default, Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it back to `false` to disable.

110 

111With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode with `--spawn` instead.

112 

113## Connection and security

114 

115Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection.

116 

117All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently.

118 

119## Remote Control vs Claude Code on the web

120 

121Remote Control and [Claude Code on the web](/en/claude-code-on-the-web) both use the claude.ai/code interface. The key difference is where the session runs: Remote Control executes on your machine, so your local MCP servers, tools, and project configuration stay available. Claude Code on the web executes in Anthropic-managed cloud infrastructure.

122 

123Use Remote Control when you're in the middle of local work and want to keep going from another device. Use Claude Code on the web when you want to kick off a task without any local setup, work on a repo you don't have cloned, or run multiple tasks in parallel.

124 

125## Limitations

126 

127* **One remote session per interactive process**: outside of server mode, each Claude Code instance supports one remote session at a time. Use server mode with `--spawn` to run multiple concurrent sessions from a single process.

128* **Terminal must stay open**: Remote Control runs as a local process. If you close the terminal or stop the `claude` process, the session ends. Run `claude remote-control` again to start a new one.

129* **Extended network outage**: if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session.

130 

131## Related resources

132 

133* [Claude Code on the web](/en/claude-code-on-the-web): run sessions in Anthropic-managed cloud environments instead of on your machine

134* [Authentication](/en/authentication): set up `/login` and manage credentials for claude.ai

135* [CLI reference](/en/cli-reference): full list of flags and commands including `claude remote-control`

136* [Security](/en/security): how Remote Control sessions fit into the Claude Code security model

137* [Data usage](/en/data-usage): what data flows through the Anthropic API during local and remote sessions

sandboxing.md +62 −11

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Sandboxing5# Sandboxing

2 6 

3> Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution.7> Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution.


38* **Blocked access**: Cannot modify files outside the current working directory without explicit permission42* **Blocked access**: Cannot modify files outside the current working directory without explicit permission

39* **Configurable**: Define custom allowed and denied paths through settings43* **Configurable**: Define custom allowed and denied paths through settings

40 44 

45You can grant write access to additional paths using `sandbox.filesystem.allowWrite` in your settings. These restrictions are enforced at the OS level (Seatbelt on macOS, bubblewrap on Linux), so they apply to all subprocess commands, including tools like `kubectl`, `terraform`, and `npm`, not just Claude's file tools.

46 

41### Network isolation47### Network isolation

42 48 

43Network access is controlled through a proxy server running outside the sandbox:49Network access is controlled through a proxy server running outside the sandbox:

44 50 

45* **Domain restrictions**: Only approved domains can be accessed51* **Domain restrictions**: Only approved domains can be accessed

46* **User confirmation**: New domain requests trigger permission prompts52* **User confirmation**: New domain requests trigger permission prompts (unless [`allowManagedDomainsOnly`](/en/settings#sandbox-settings) is enabled, which blocks non-allowed domains automatically)

47* **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic53* **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic

48* **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands54* **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands

49 55 


85 91 

86You can enable sandboxing by running the `/sandbox` command:92You can enable sandboxing by running the `/sandbox` command:

87 93 

88```94```text theme={null}

89> /sandbox95/sandbox

90```96```

91 97 

92This opens a menu where you can choose between sandbox modes.98This opens a menu where you can choose between sandbox modes. If required dependencies are missing (such as `bubblewrap` or `socat` on Linux), the menu displays installation instructions for your platform.

93 99 

94### Sandbox modes100### Sandbox modes

95 101 


109 115 

110Customize sandbox behavior through your `settings.json` file. See [Settings](/en/settings#sandbox-settings) for complete configuration reference.116Customize sandbox behavior through your `settings.json` file. See [Settings](/en/settings#sandbox-settings) for complete configuration reference.

111 117 

118#### Granting subprocess write access to specific paths

119 

120By default, sandboxed commands can only write to the current working directory. If subprocess commands like `kubectl`, `terraform`, or `npm` need to write outside the project directory, use `sandbox.filesystem.allowWrite` to grant access to specific paths:

121 

122```json theme={null}

123{

124 "sandbox": {

125 "enabled": true,

126 "filesystem": {

127 "allowWrite": ["~/.kube", "//tmp/build"]

128 }

129 }

130}

131```

132 

133These paths are enforced at the OS level, so all commands running inside the sandbox, including their child processes, respect them. This is the recommended approach when a tool needs write access to a specific location, rather than excluding the tool from the sandbox entirely with `excludedCommands`.

134 

135When `allowWrite` (or `denyWrite`/`denyRead`) is defined in multiple [settings scopes](/en/settings#settings-precedence), the arrays are **merged**, meaning paths from every scope are combined, not replaced. For example, if managed settings allow writes to `//opt/company-tools` and a user adds `~/.kube` in their personal settings, both paths are included in the final sandbox configuration. This means users and projects can extend the list without duplicating or overriding paths set by higher-priority scopes.

136 

137Path prefixes control how paths are resolved:

138 

139| Prefix | Meaning | Example |

140| :---------------- | :------------------------------------------ | :------------------------------------- |

141| `//` | Absolute path from filesystem root | `//tmp/build` becomes `/tmp/build` |

142| `~/` | Relative to home directory | `~/.kube` becomes `$HOME/.kube` |

143| `/` | Relative to the settings file's directory | `/build` becomes `$SETTINGS_DIR/build` |

144| `./` or no prefix | Relative path (resolved by sandbox runtime) | `./output` |

145 

146You can also deny write or read access using `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead`. These are merged with any paths from `Edit(...)` and `Read(...)` permission rules.

147 

112<Tip>148<Tip>

113 Not all commands are compatible with sandboxing out of the box. Some notes that may help you make the most out of the sandbox:149 Not all commands are compatible with sandboxing out of the box. Some notes that may help you make the most out of the sandbox:

114 150 


133 169 

134* Cannot modify critical config files such as `~/.bashrc`170* Cannot modify critical config files such as `~/.bashrc`

135* Cannot modify system-level files in `/bin/`171* Cannot modify system-level files in `/bin/`

136* Cannot read files that are denied in your [Claude permission settings](/en/iam#configuring-permissions)172* Cannot read files that are denied in your [Claude permission settings](/en/permissions#manage-permissions)

137 173 

138**Network protection:**174**Network protection:**

139 175 


180* Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files.216* Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files.

181* Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used in cases where additional isolation is otherwise enforced.217* Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used in cases where additional isolation is otherwise enforced.

182 218 

219## How sandboxing relates to permissions

220 

221Sandboxing and [permissions](/en/permissions) are complementary security layers that work together:

222 

223* **Permissions** control which tools Claude Code can use and are evaluated before any tool runs. They apply to all tools: Bash, Read, Edit, WebFetch, MCP, and others.

224* **Sandboxing** provides OS-level enforcement that restricts what Bash commands can access at the filesystem and network level. It applies only to Bash commands and their child processes.

225 

226Filesystem and network restrictions are configured through both sandbox settings and permission rules:

227 

228* Use `sandbox.filesystem.allowWrite` to grant subprocess write access to paths outside the working directory

229* Use `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead` to block subprocess access to specific paths

230* Use `Read` and `Edit` deny rules to block access to specific files or directories

231* Use `WebFetch` allow/deny rules to control domain access

232* Use sandbox `allowedDomains` to control which domains Bash commands can reach

233 

234Paths from both `sandbox.filesystem` settings and permission rules are merged together into the final sandbox configuration.

235 

236This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios, including sandbox-specific examples. Use these as starting points and adjust them to fit your needs.

237 

183## Advanced usage238## Advanced usage

184 239 

185### Custom proxy configuration240### Custom proxy configuration


206 261 

207The sandboxed bash tool works alongside:262The sandboxed bash tool works alongside:

208 263 

209* **IAM policies**: Combine with [permission settings](/en/iam) for defense-in-depth264* **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth

210* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation265* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation

211* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)266* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)

212 267 


237## See also292## See also

238 293 

239* [Security](/en/security) - Comprehensive security features and best practices294* [Security](/en/security) - Comprehensive security features and best practices

240* [IAM](/en/iam) - Permission configuration and access control295* [Permissions](/en/permissions) - Permission configuration and access control

241* [Settings](/en/settings) - Complete configuration reference296* [Settings](/en/settings) - Complete configuration reference

242* [CLI reference](/en/cli-reference) - Command-line options297* [CLI reference](/en/cli-reference) - Command-line options

243 

244 

245 

246> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

scheduled-tasks.md +133 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Run prompts on a schedule

6 

7> Use /loop and the cron scheduling tools to run prompts repeatedly, poll for status, or set one-time reminders within a Claude Code session.

8 

9<Note>

10 Scheduled tasks require Claude Code v2.1.72 or later. Check your version with `claude --version`.

11</Note>

12 

13Scheduled tasks let Claude re-run a prompt automatically on an interval. Use them to poll a deployment, babysit a PR, check back on a long-running build, or remind yourself to do something later in the session.

14 

15Tasks are session-scoped: they live in the current Claude Code process and are gone when you exit. For durable scheduling that survives restarts and runs without an active terminal session, see [Desktop scheduled tasks](/en/desktop#schedule-recurring-tasks) or [GitHub Actions](/en/github-actions).

16 

17## Schedule a recurring prompt with /loop

18 

19The `/loop` [bundled skill](/en/skills#bundled-skills) is the quickest way to schedule a recurring prompt. Pass an optional interval and a prompt, and Claude sets up a cron job that fires in the background while the session stays open.

20 

21```text theme={null}

22/loop 5m check if the deployment finished and tell me what happened

23```

24 

25Claude parses the interval, converts it to a cron expression, schedules the job, and confirms the cadence and job ID.

26 

27### Interval syntax

28 

29Intervals are optional. You can lead with them, trail with them, or leave them out entirely.

30 

31| Form | Example | Parsed interval |

32| :---------------------- | :------------------------------------ | :--------------------------- |

33| Leading token | `/loop 30m check the build` | every 30 minutes |

34| Trailing `every` clause | `/loop check the build every 2 hours` | every 2 hours |

35| No interval | `/loop check the build` | defaults to every 10 minutes |

36 

37Supported units are `s` for seconds, `m` for minutes, `h` for hours, and `d` for days. Seconds are rounded up to the nearest minute since cron has one-minute granularity. Intervals that don't divide evenly into their unit, such as `7m` or `90m`, are rounded to the nearest clean interval and Claude tells you what it picked.

38 

39### Loop over another command

40 

41The scheduled prompt can itself be a command or skill invocation. This is useful for re-running a workflow you've already packaged.

42 

43```text theme={null}

44/loop 20m /review-pr 1234

45```

46 

47Each time the job fires, Claude runs `/review-pr 1234` as if you had typed it.

48 

49## Set a one-time reminder

50 

51For one-shot reminders, describe what you want in natural language instead of using `/loop`. Claude schedules a single-fire task that deletes itself after running.

52 

53```text theme={null}

54remind me at 3pm to push the release branch

55```

56 

57```text theme={null}

58in 45 minutes, check whether the integration tests passed

59```

60 

61Claude pins the fire time to a specific minute and hour using a cron expression and confirms when it will fire.

62 

63## Manage scheduled tasks

64 

65Ask Claude in natural language to list or cancel tasks, or reference the underlying tools directly.

66 

67```text theme={null}

68what scheduled tasks do I have?

69```

70 

71```text theme={null}

72cancel the deploy check job

73```

74 

75Under the hood, Claude uses these tools:

76 

77| Tool | Purpose |

78| :----------- | :-------------------------------------------------------------------------------------------------------------- |

79| `CronCreate` | Schedule a new task. Accepts a 5-field cron expression, the prompt to run, and whether it recurs or fires once. |

80| `CronList` | List all scheduled tasks with their IDs, schedules, and prompts. |

81| `CronDelete` | Cancel a task by ID. |

82 

83Each scheduled task has an 8-character ID you can pass to `CronDelete`. A session can hold up to 50 scheduled tasks at once.

84 

85## How scheduled tasks run

86 

87The scheduler checks every second for due tasks and enqueues them at low priority. A scheduled prompt fires between your turns, not while Claude is mid-response. If Claude is busy when a task comes due, the prompt waits until the current turn ends.

88 

89All times are interpreted in your local timezone. A cron expression like `0 9 * * *` means 9am wherever you're running Claude Code, not UTC.

90 

91### Jitter

92 

93To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a small deterministic offset to fire times:

94 

95* Recurring tasks fire up to 10% of their period late, capped at 15 minutes. An hourly job might fire anywhere from `:00` to `:06`.

96* One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.

97 

98The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not `:00` or `:30`, for example `3 9 * * *` instead of `0 9 * * *`, and the one-shot jitter will not apply.

99 

100### Three-day expiry

101 

102Recurring tasks automatically expire 3 days after creation. The task fires one final time, then deletes itself. This bounds how long a forgotten loop can run. If you need a recurring task to last longer, cancel and recreate it before it expires, or use [Desktop scheduled tasks](/en/desktop#schedule-recurring-tasks) for durable scheduling.

103 

104## Cron expression reference

105 

106`CronCreate` accepts standard 5-field cron expressions: `minute hour day-of-month month day-of-week`. All fields support wildcards (`*`), single values (`5`), steps (`*/15`), ranges (`1-5`), and comma-separated lists (`1,15,30`).

107 

108| Example | Meaning |

109| :------------- | :--------------------------- |

110| `*/5 * * * *` | Every 5 minutes |

111| `0 * * * *` | Every hour on the hour |

112| `7 * * * *` | Every hour at 7 minutes past |

113| `0 9 * * *` | Every day at 9am local |

114| `0 9 * * 1-5` | Weekdays at 9am local |

115| `30 14 15 3 *` | March 15 at 2:30pm local |

116 

117Day-of-week uses `0` or `7` for Sunday through `6` for Saturday. Extended syntax like `L`, `W`, `?`, and name aliases such as `MON` or `JAN` is not supported.

118 

119When both day-of-month and day-of-week are constrained, a date matches if either field matches. This follows standard vixie-cron semantics.

120 

121## Disable scheduled tasks

122 

123Set `CLAUDE_CODE_DISABLE_CRON=1` in your environment to disable the scheduler entirely. The cron tools and `/loop` become unavailable, and any already-scheduled tasks stop firing. See [Environment variables](/en/env-vars) for the full list of disable flags.

124 

125## Limitations

126 

127Session-scoped scheduling has inherent constraints:

128 

129* Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit cancels everything.

130* No catch-up for missed fires. If a task's scheduled time passes while Claude is busy on a long-running request, it fires once when Claude becomes idle, not once per missed interval.

131* No persistence across restarts. Restarting Claude Code clears all session-scoped tasks.

132 

133For cron-driven automation that needs to run unattended, use a [GitHub Actions workflow](/en/github-actions) with a `schedule` trigger, or [Desktop scheduled tasks](/en/desktop#schedule-recurring-tasks) if you want a graphical setup flow.

security.md +12 −9

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Security5# Security

2 6 

3> Learn about Claude Code's security safeguards and best practices for safe usage.7> Learn about Claude Code's security safeguards and best practices for safe usage.


14 18 

15We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.19We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.

16 20 

17For detailed permission configuration, see [Identity and Access Management](/en/iam).21For detailed permission configuration, see [Permissions](/en/permissions).

18 22 

19### Built-in protections23### Built-in protections

20 24 


38* **Permission system**: Sensitive operations require explicit approval42* **Permission system**: Sensitive operations require explicit approval

39* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request43* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request

40* **Input sanitization**: Prevents command injection by processing user inputs44* **Input sanitization**: Prevents command injection by processing user inputs

41* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/iam#tool-specific-permission-rules)45* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/permissions#tool-specific-permission-rules)

42 46 

43### Privacy safeguards47### Privacy safeguards

44 48 


59* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted63* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted

60* **Fail-closed matching**: Unmatched commands default to requiring manual approval64* **Fail-closed matching**: Unmatched commands default to requiring manual approval

61* **Natural language descriptions**: Complex bash commands include explanations for user understanding65* **Natural language descriptions**: Complex bash commands include explanations for user understanding

62* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/iam#credential-management)66* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/authentication#credential-management)

63 67 

64<Warning>68<Warning>

65 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.69 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.


102 106 

103For more details on cloud execution, see [Claude Code on the web](/en/claude-code-on-the-web).107For more details on cloud execution, see [Claude Code on the web](/en/claude-code-on-the-web).

104 108 

109[Remote Control](/en/remote-control) sessions work differently: the web interface connects to a Claude Code process running on your local machine. All code execution and file access stays local, and the same data that flows during any local Claude Code session travels through the Anthropic API over TLS. No cloud VMs or sandboxing are involved. The connection uses multiple short-lived, narrowly scoped credentials, each limited to a specific purpose and expiring independently, to limit the blast radius of any single compromised credential.

110 

105## Security best practices111## Security best practices

106 112 

107### Working with sensitive code113### Working with sensitive code


113 119 

114### Team security120### Team security

115 121 

116* Use [managed settings](/en/iam#managed-settings) to enforce organizational standards122* Use [managed settings](/en/settings#settings-files) to enforce organizational standards

117* Share approved permission configurations through version control123* Share approved permission configurations through version control

118* Train team members on security best practices124* Train team members on security best practices

119* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)125* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)

126* Audit or block settings changes during sessions with [`ConfigChange` hooks](/en/hooks#configchange)

120 127 

121### Reporting security issues128### Reporting security issues

122 129 


130## Related resources137## Related resources

131 138 

132* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands139* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands

133* [Identity and Access Management](/en/iam) - Configure permissions and access controls140* [Permissions](/en/permissions) - Configure permissions and access controls

134* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity141* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity

135* [Development containers](/en/devcontainer) - Secure, isolated environments142* [Development containers](/en/devcontainer) - Secure, isolated environments

136* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance143* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance

137 

138 

139 

140> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

server-managed-settings.md +164 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Configure server-managed settings (public beta)

6 

7> Centrally configure Claude Code for your organization through server-delivered settings, without requiring device management infrastructure.

8 

9Server-managed settings allow administrators to centrally configure Claude Code through a web-based interface on Claude.ai. Claude Code clients automatically receive these settings when users authenticate with their organization credentials.

10 

11This approach is designed for organizations that do not have device management infrastructure in place, or need to manage settings for users on unmanaged devices.

12 

13<Note>

14 Server-managed settings are in public beta and available for [Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=server_settings_teams#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=server_settings_enterprise) customers. Features may evolve before general availability.

15</Note>

16 

17## Requirements

18 

19To use server-managed settings, you need:

20 

21* Claude for Teams or Claude for Enterprise plan

22* Claude Code version 2.1.38 or later for Claude for Teams, or version 2.1.30 or later for Claude for Enterprise

23* Network access to `api.anthropic.com`

24 

25## Choose between server-managed and endpoint-managed settings

26 

27Claude Code supports two approaches for centralized configuration. Server-managed settings deliver configuration from Anthropic's servers. [Endpoint-managed settings](/en/settings#settings-files) are deployed directly to devices through native OS policies (macOS managed preferences, Windows registry) or managed settings files.

28 

29| Approach | Best for | Security model |

30| :----------------------------------------------------------- | :------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- |

31| **Server-managed settings** | Organizations without MDM, or users on unmanaged devices | Settings delivered from Anthropic's servers at authentication time |

32| **[Endpoint-managed settings](/en/settings#settings-files)** | Organizations with MDM or endpoint management | Settings deployed to devices via MDM configuration profiles, registry policies, or managed settings files |

33 

34If your devices are enrolled in an MDM or endpoint management solution, endpoint-managed settings provide stronger security guarantees because the settings file can be protected from user modification at the OS level.

35 

36## Configure server-managed settings

37 

38<Steps>

39 <Step title="Open the admin console">

40 In [Claude.ai](https://claude.ai), navigate to **Admin Settings > Claude Code > Managed settings**.

41 </Step>

42 

43 <Step title="Define your settings">

44 Add your configuration as JSON. All [settings available in `settings.json`](/en/settings#available-settings) are supported, including [managed-only settings](/en/permissions#managed-only-settings) like `disableBypassPermissionsMode`.

45 

46 This example enforces a permission deny list and prevents users from bypassing permissions:

47 

48 ```json theme={null}

49 {

50 "permissions": {

51 "deny": [

52 "Bash(curl *)",

53 "Read(./.env)",

54 "Read(./.env.*)",

55 "Read(./secrets/**)"

56 ],

57 "disableBypassPermissionsMode": "disable"

58 }

59 }

60 ```

61 </Step>

62 

63 <Step title="Save and deploy">

64 Save your changes. Claude Code clients receive the updated settings on their next startup or hourly polling cycle.

65 </Step>

66</Steps>

67 

68### Verify settings delivery

69 

70To confirm that settings are being applied, ask a user to restart Claude Code. If the configuration includes settings that trigger the [security approval dialog](#security-approval-dialogs), the user sees a prompt describing the managed settings on startup. You can also verify that managed permission rules are active by having a user run `/permissions` to view their effective permission rules.

71 

72### Access control

73 

74The following roles can manage server-managed settings:

75 

76* **Primary Owner**

77* **Owner**

78 

79Restrict access to trusted personnel, as settings changes apply to all users in the organization.

80 

81### Current limitations

82 

83Server-managed settings have the following limitations during the beta period:

84 

85* Settings apply uniformly to all users in the organization. Per-group configurations are not yet supported.

86* [MCP server configurations](/en/mcp#managed-mcp-configuration) cannot be distributed through server-managed settings.

87 

88## Settings delivery

89 

90### Settings precedence

91 

92Server-managed settings and [endpoint-managed settings](/en/settings#settings-files) both occupy the highest tier in the Claude Code [settings hierarchy](/en/settings#settings-precedence). No other settings level can override them, including command line arguments. When both are present, server-managed settings take precedence and endpoint-managed settings are not used.

93 

94### Fetch and caching behavior

95 

96Claude Code fetches settings from Anthropic's servers at startup and polls for updates hourly during active sessions.

97 

98**First launch without cached settings:**

99 

100* Claude Code fetches settings asynchronously

101* If the fetch fails, Claude Code continues without managed settings

102* There is a brief window before settings load where restrictions are not yet enforced

103 

104**Subsequent launches with cached settings:**

105 

106* Cached settings apply immediately at startup

107* Claude Code fetches fresh settings in the background

108* Cached settings persist through network failures

109 

110Claude Code applies settings updates automatically without a restart, except for advanced settings like OpenTelemetry configuration, which require a full restart to take effect.

111 

112### Security approval dialogs

113 

114Certain settings that could pose security risks require explicit user approval before being applied:

115 

116* **Shell command settings**: settings that execute shell commands

117* **Custom environment variables**: variables not in the known safe allowlist

118* **Hook configurations**: any hook definition

119 

120When these settings are present, users see a security dialog explaining what is being configured. Users must approve to proceed. If a user rejects the settings, Claude Code exits.

121 

122<Note>

123 In non-interactive mode with the `-p` flag, Claude Code skips security dialogs and applies settings without user approval.

124</Note>

125 

126## Platform availability

127 

128Server-managed settings require a direct connection to `api.anthropic.com` and are not available when using third-party model providers:

129 

130* Amazon Bedrock

131* Google Vertex AI

132* Microsoft Foundry

133* Custom API endpoints via `ANTHROPIC_BASE_URL` or [LLM gateways](/en/llm-gateway)

134 

135## Audit logging

136 

137Audit log events for settings changes are available through the compliance API or audit log export. Contact your Anthropic account team for access.

138 

139Audit events include the type of action performed, the account and device that performed the action, and references to the previous and new values.

140 

141## Security considerations

142 

143Server-managed settings provide centralized policy enforcement, but they operate as a client-side control. On unmanaged devices, users with admin or sudo access can modify the Claude Code binary, filesystem, or network configuration.

144 

145| Scenario | Behavior |

146| :----------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |

147| User edits the cached settings file | Tampered file applies at startup, but correct settings restore on the next server fetch |

148| User deletes the cached settings file | First-launch behavior occurs: settings fetch asynchronously with a brief unenforced window |

149| API is unavailable | Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch |

150| User authenticates with a different organization | Settings are not delivered for accounts outside the managed organization |

151| User sets a non-default `ANTHROPIC_BASE_URL` | Server-managed settings are bypassed when using third-party API providers |

152 

153To detect runtime configuration changes, use [`ConfigChange` hooks](/en/hooks#configchange) to log modifications or block unauthorized changes before they take effect.

154 

155For stronger enforcement guarantees, use [endpoint-managed settings](/en/settings#settings-files) on devices enrolled in an MDM solution.

156 

157## See also

158 

159Related pages for managing Claude Code configuration:

160 

161* [Settings](/en/settings): complete configuration reference including all available settings

162* [Endpoint-managed settings](/en/settings#settings-files): managed settings deployed to devices by IT

163* [Authentication](/en/authentication): set up user access to Claude Code

164* [Security](/en/security): security safeguards and best practices

settings.md +197 −317

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code settings5# Claude Code settings

2 6 

3> Configure Claude Code with global and project-level settings, and environment variables.7> Configure Claude Code with global and project-level settings, and environment variables.


11### Available scopes15### Available scopes

12 16 

13| Scope | Location | Who it affects | Shared with team? |17| Scope | Location | Who it affects | Shared with team? |

14| :---------- | :----------------------------------- | :----------------------------------- | :--------------------- |18| :---------- | :--------------------------------------------------------------------------------- | :----------------------------------- | :--------------------- |

15| **Managed** | System-level `managed-settings.json` | All users on the machine | Yes (deployed by IT) |19| **Managed** | Server-managed settings, plist / registry, or system-level `managed-settings.json` | All users on the machine | Yes (deployed by IT) |

16| **User** | `~/.claude/` directory | You, across all projects | No |20| **User** | `~/.claude/` directory | You, across all projects | No |

17| **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |21| **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |

18| **Local** | `.claude/*.local.*` files | You, in this repository only | No (gitignored) |22| **Local** | `.claude/settings.local.json` | You, in this repository only | No (gitignored) |

19 23 

20### When to use each scope24### When to use each scope

21 25 


62| Feature | User location | Project location | Local location |66| Feature | User location | Project location | Local location |

63| :-------------- | :------------------------ | :--------------------------------- | :----------------------------- |67| :-------------- | :------------------------ | :--------------------------------- | :----------------------------- |

64| **Settings** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |68| **Settings** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

65| **Subagents** | `~/.claude/agents/` | `.claude/agents/` | |69| **Subagents** | `~/.claude/agents/` | `.claude/agents/` | None |

66| **MCP servers** | `~/.claude.json` | `.mcp.json` | `~/.claude.json` (per-project) |70| **MCP servers** | `~/.claude.json` | `.mcp.json` | `~/.claude.json` (per-project) |

67| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |71| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

68| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` |72| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | None |

69 73 

70***74***

71 75 

72## Settings files76## Settings files

73 77 

74The `settings.json` file is our official mechanism for configuring Claude78The `settings.json` file is the official mechanism for configuring Claude

75Code through hierarchical settings:79Code through hierarchical settings:

76 80 

77* **User settings** are defined in `~/.claude/settings.json` and apply to all81* **User settings** are defined in `~/.claude/settings.json` and apply to all


79* **Project settings** are saved in your project directory:83* **Project settings** are saved in your project directory:

80 * `.claude/settings.json` for settings that are checked into source control and shared with your team84 * `.claude/settings.json` for settings that are checked into source control and shared with your team

81 * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.85 * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.

82* **Managed settings**: For organizations that need centralized control, Claude Code supports `managed-settings.json` and `managed-mcp.json` files that can be deployed to system directories:86* **Managed settings**: For organizations that need centralized control, Claude Code supports multiple delivery mechanisms for managed settings. All use the same JSON format and cannot be overridden by user or project settings:

87 

88 * **Server-managed settings**: delivered from Anthropic's servers via the Claude.ai admin console. See [server-managed settings](/en/server-managed-settings).

89 * **MDM/OS-level policies**: delivered through native device management on macOS and Windows:

90 * macOS: `com.anthropic.claudecode` managed preferences domain (deployed via configuration profiles in Jamf, Kandji, or other MDM tools)

91 * Windows: `HKLM\SOFTWARE\Policies\ClaudeCode` registry key with a `Settings` value (REG\_SZ or REG\_EXPAND\_SZ) containing JSON (deployed via Group Policy or Intune)

92 * Windows (user-level): `HKCU\SOFTWARE\Policies\ClaudeCode` (lowest policy priority, only used when no admin-level source exists)

93 * **File-based**: `managed-settings.json` and `managed-mcp.json` deployed to system directories:

83 94 

84 * macOS: `/Library/Application Support/ClaudeCode/`95 * macOS: `/Library/Application Support/ClaudeCode/`

85 * Linux and WSL: `/etc/claude-code/`96 * Linux and WSL: `/etc/claude-code/`

86 * Windows: `C:\Program Files\ClaudeCode\`97 * Windows: `C:\Program Files\ClaudeCode\`

87 98 

88 <Note>99 <Warning>

89 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.100 The legacy Windows path `C:\ProgramData\ClaudeCode\managed-settings.json` is no longer supported as of v2.1.75. Administrators who deployed settings to that location must migrate files to `C:\Program Files\ClaudeCode\managed-settings.json`.

90 </Note>101 </Warning>

91 102 

92 See [Managed settings](/en/iam#managed-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details.103 See [managed settings](/en/permissions#managed-only-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details.

93 104 

94 <Note>105 <Note>

95 Managed deployments can also restrict **plugin marketplace additions** using106 Managed deployments can also restrict **plugin marketplace additions** using


97 </Note>108 </Note>

98* **Other configuration** is stored in `~/.claude.json`. This file contains your preferences (theme, notification settings, editor mode), OAuth session, [MCP server](/en/mcp) configurations for user and local scopes, per-project state (allowed tools, trust settings), and various caches. Project-scoped MCP servers are stored separately in `.mcp.json`.109* **Other configuration** is stored in `~/.claude.json`. This file contains your preferences (theme, notification settings, editor mode), OAuth session, [MCP server](/en/mcp) configurations for user and local scopes, per-project state (allowed tools, trust settings), and various caches. Project-scoped MCP servers are stored separately in `.mcp.json`.

99 110 

111<Note>

112 Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.

113</Note>

114 

100```JSON Example settings.json theme={null}115```JSON Example settings.json theme={null}

101{116{

117 "$schema": "https://json.schemastore.org/claude-code-settings.json",

102 "permissions": {118 "permissions": {

103 "allow": [119 "allow": [

104 "Bash(npm run lint)",120 "Bash(npm run lint)",

105 "Bash(npm run test:*)",121 "Bash(npm run test *)",

106 "Read(~/.zshrc)"122 "Read(~/.zshrc)"

107 ],123 ],

108 "deny": [124 "deny": [

109 "Bash(curl:*)",125 "Bash(curl *)",

110 "Read(./.env)",126 "Read(./.env)",

111 "Read(./.env.*)",127 "Read(./.env.*)",

112 "Read(./secrets/**)"128 "Read(./secrets/**)"


124}140}

125```141```

126 142 

143The `$schema` line in the example above points to the [official JSON schema](https://json.schemastore.org/claude-code-settings.json) for Claude Code settings. Adding it to your `settings.json` enables autocomplete and inline validation in VS Code, Cursor, and any other editor that supports JSON schema validation.

144 

127### Available settings145### Available settings

128 146 

129`settings.json` supports a number of options:147`settings.json` supports a number of options:

130 148 

131| Key | Description | Example |149| Key | Description | Example |

132| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- |150| :-------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------- |

133| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |151| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |

134| `cleanupPeriodDays` | Sessions inactive for longer than this period are deleted at startup. Setting to `0` immediately deletes all sessions. (default: 30 days) | `20` |152| `autoMemoryDirectory` | Custom directory for [auto memory](/en/memory#storage-location) storage. Accepts `~/`-expanded paths. Not accepted in project settings (`.claude/settings.json`) to prevent shared repos from redirecting memory writes to sensitive locations. Accepted from policy, local, and user settings | `"~/my-memory-dir"` |

153| `cleanupPeriodDays` | Sessions inactive for longer than this period are deleted at startup (default: 30 days).<br /><br />Setting to `0` deletes all existing transcripts at startup and disables session persistence entirely. No new `.jsonl` files are written, `/resume` shows no conversations, and hooks receive an empty `transcript_path`. | `20` |

135| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |154| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |

136| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |155| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |

137| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |156| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |

138| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |157| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |

158| `includeGitInstructions` | Include built-in commit and PR workflow instructions in Claude's system prompt (default: `true`). Set to `false` to remove these instructions, for example when using your own git workflow skills. The `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` environment variable takes precedence over this setting when set | `false` |

139| `permissions` | See table below for structure of permissions. | |159| `permissions` | See table below for structure of permissions. | |

140| `hooks` | Configure custom commands to run before or after tool executions. See [hooks documentation](/en/hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` |160| `hooks` | Configure custom commands to run at lifecycle events. See [hooks documentation](/en/hooks) for format | See [hooks](/en/hooks) |

141| `disableAllHooks` | Disable all [hooks](/en/hooks) | `true` |161| `disableAllHooks` | Disable all [hooks](/en/hooks) and any custom [status line](/en/statusline) | `true` |

142| `allowManagedHooksOnly` | (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See [Hook configuration](#hook-configuration) | `true` |162| `allowManagedHooksOnly` | (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See [Hook configuration](#hook-configuration) | `true` |

143| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` |163| `allowedHttpHookUrls` | Allowlist of URL patterns that HTTP hooks may target. Supports `*` as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See [Hook configuration](#hook-configuration) | `["https://hooks.example.com/*"]` |

164| `httpHookAllowedEnvVars` | Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective `allowedEnvVars` is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See [Hook configuration](#hook-configuration) | `["MY_TOKEN", "HOOK_SECRET"]` |

165| `allowManagedPermissionRulesOnly` | (Managed settings only) Prevent user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. See [Managed-only settings](/en/permissions#managed-only-settings) | `true` |

166| `allowManagedMcpServersOnly` | (Managed settings only) Only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. Users can still add MCP servers, but only the admin-defined allowlist applies. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `true` |

167| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-6"` |

168| `availableModels` | Restrict which models users can select via `/model`, `--model`, Config tool, or `ANTHROPIC_MODEL`. Does not affect the Default option. See [Restrict model selection](/en/model-config#restrict-model-selection) | `["sonnet", "haiku"]` |

169| `modelOverrides` | Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs. Each model picker entry uses its mapped value when calling the provider API. See [Override model IDs per version](/en/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |

170| `effortLevel` | Persist the [effort level](/en/model-config#adjust-effort-level) across sessions. Accepts `"low"`, `"medium"`, or `"high"`. Written automatically when you run `/effort low`, `/effort medium`, or `/effort high`. Supported on Opus 4.6 and Sonnet 4.6 | `"medium"` |

144| `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically (see [Dynamic headers](/en/monitoring-usage#dynamic-headers)) | `/bin/generate_otel_headers.sh` |171| `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically (see [Dynamic headers](/en/monitoring-usage#dynamic-headers)) | `/bin/generate_otel_headers.sh` |

145| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |172| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |

146| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |173| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |


154| `allowedMcpServers` | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "github" }]` |181| `allowedMcpServers` | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "github" }]` |

155| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` |182| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` |

156| `strictKnownMarketplaces` | When set in managed-settings.json, allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Applies to marketplace additions only. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |183| `strictKnownMarketplaces` | When set in managed-settings.json, allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Applies to marketplace additions only. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |

184| `blockedMarketplaces` | (Managed settings only) Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "untrusted/plugins" }]` |

185| `pluginTrustMessage` | (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use this to add organization-specific context, for example to confirm that plugins from your internal marketplace are vetted. | `"All plugins from our marketplace are approved by IT"` |

157| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |186| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |

158| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |187| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |

159| `alwaysThinkingEnabled` | Enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) by default for all sessions. Typically configured via the `/config` command rather than editing directly | `true` |188| `alwaysThinkingEnabled` | Enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) by default for all sessions. Typically configured via the `/config` command rather than editing directly | `true` |

160| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |189| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |

161| `showTurnDuration` | Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to `false` to hide these messages | `true` |190| `showTurnDuration` | Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to `false` to hide these messages | `true` |

191| `spinnerVerbs` | Customize the action verbs shown in the spinner and turn duration messages. Set `mode` to `"replace"` to use only your verbs, or `"append"` to add them to the defaults | `{"mode": "append", "verbs": ["Pondering", "Crafting"]}` |

162| `language` | Configure Claude's preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default | `"japanese"` |192| `language` | Configure Claude's preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default | `"japanese"` |

163| `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` |193| `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` |

164| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |194| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |

195| `spinnerTipsOverride` | Override spinner tips with custom strings. `tips`: array of tip strings. `excludeDefault`: if `true`, only show custom tips; if `false` or absent, custom tips are merged with built-in tips | `{ "excludeDefault": true, "tips": ["Use our internal tool X"] }` |

165| `terminalProgressBarEnabled` | Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: `true`) | `false` |196| `terminalProgressBarEnabled` | Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: `true`) | `false` |

197| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |

198| `fastModePerSessionOptIn` | When `true`, fast mode does not persist across sessions. Each session starts with fast mode off, requiring users to enable it with `/fast`. The user's fast mode preference is still saved. See [Require per-session opt-in](/en/fast-mode#require-per-session-opt-in) | `true` |

199| `teammateMode` | How [agent team](/en/agent-teams) teammates display: `auto` (picks split panes in tmux or iTerm2, in-process otherwise), `in-process`, or `tmux`. See [set up agent teams](/en/agent-teams#set-up-agent-teams) | `"in-process"` |

200| `feedbackSurveyRate` | Probability (0–1) that the [session quality survey](/en/data-usage#session-quality-surveys) appears when eligible. Set to `0` to suppress entirely. Useful when using Bedrock, Vertex, or Foundry where the default sample rate does not apply | `0.05` |

166 201 

167### Permission settings202### Worktree settings

168 203 

169| Keys | Description | Example |204Configure how `--worktree` creates and manages git worktrees. Use these settings to reduce disk usage and startup time in large monorepos.

170| :----------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |

171| `allow` | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details | `[ "Bash(git diff:*)" ]` |

172| `ask` | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below | `[ "Bash(git push:*)" ]` |

173| `deny` | Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. See [Permission rule syntax](#permission-rule-syntax) and [Bash permission limitations](/en/iam#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` |

174| `additionalDirectories` | Additional [working directories](/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` |

175| `defaultMode` | Default [permission mode](/en/iam#permission-modes) when opening Claude Code | `"acceptEdits"` |

176| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed settings](/en/iam#managed-settings) | `"disable"` |

177 205 

178### Permission rule syntax206| Key | Description | Example |

179 207| :---------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |

180Permission rules follow the format `Tool` or `Tool(specifier)`. Understanding the syntax helps you write rules that match exactly what you intend.208| `worktree.symlinkDirectories` | Directories to symlink from the main repository into each worktree to avoid duplicating large directories on disk. No directories are symlinked by default | `["node_modules", ".cache"]` |

181 209| `worktree.sparsePaths` | Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos | `["packages/my-app", "shared/utils"]` |

182#### Rule evaluation order

183 

184When multiple rules could match the same tool use, rules are evaluated in this order:

185 

1861. **Deny** rules are checked first

1872. **Ask** rules are checked second

1883. **Allow** rules are checked last

189 

190The first matching rule determines the behavior. This means deny rules always take precedence over allow rules, even if both match the same command.

191 

192#### Matching all uses of a tool

193 210 

194To match all uses of a tool, use just the tool name without parentheses:211### Permission settings

195 212 

196| Rule | Effect |213| Keys | Description | Example |

197| :--------- | :--------------------------------- |214| :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |

198| `Bash` | Matches **all** Bash commands |215| `allow` | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details | `[ "Bash(git diff *)" ]` |

199| `WebFetch` | Matches **all** web fetch requests |216| `ask` | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below | `[ "Bash(git push *)" ]` |

200| `Read` | Matches **all** file reads |217| `deny` | Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. See [Permission rule syntax](#permission-rule-syntax) and [Bash permission limitations](/en/permissions#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` |

218| `additionalDirectories` | Additional [working directories](/en/permissions#working-directories) that Claude has access to | `[ "../docs/" ]` |

219| `defaultMode` | Default [permission mode](/en/permissions#permission-modes) when opening Claude Code | `"acceptEdits"` |

220| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed settings](/en/permissions#managed-only-settings) | `"disable"` |

201 221 

202<Warning>222### Permission rule syntax

203 `Bash(*)` does **not** match all Bash commands. The `*` wildcard only matches within the specifier context. To allow or deny all uses of a tool, use just the tool name: `Bash`, not `Bash(*)`.

204</Warning>

205 223 

206#### Using specifiers for fine-grained control224Permission rules follow the format `Tool` or `Tool(specifier)`. Rules are evaluated in order: deny rules first, then ask, then allow. The first matching rule wins.

207 225 

208Add a specifier in parentheses to match specific tool uses:226Quick examples:

209 227 

210| Rule | Effect |228| Rule | Effect |

211| :----------------------------- | :------------------------------------------------------- |229| :----------------------------- | :--------------------------------------- |

212| `Bash(npm run build)` | Matches the exact command `npm run build` |230| `Bash` | Matches all Bash commands |

213| `Read(./.env)` | Matches reading the `.env` file in the current directory |231| `Bash(npm run *)` | Matches commands starting with `npm run` |

232| `Read(./.env)` | Matches reading the `.env` file |

214| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |233| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

215 234 

216#### Wildcard patterns235For the complete rule syntax reference, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Agent rules, and security limitations of Bash patterns, see [Permission rule syntax](/en/permissions#permission-rule-syntax).

217 

218Two wildcard syntaxes are available for Bash rules:

219 

220| Wildcard | Position | Behavior | Example |

221| :------- | :------------------ | :----------------------------------------------------------------------------------------------- | :------------------------------------------- |

222| `:*` | End of pattern only | **Prefix matching** with word boundary. The prefix must be followed by a space or end-of-string. | `Bash(ls:*)` matches `ls -la` but not `lsof` |

223| `*` | Anywhere in pattern | **Glob matching** with no word boundary. Matches any sequence of characters at that position. | `Bash(ls*)` matches both `ls -la` and `lsof` |

224 

225**Prefix matching with `:*`**

226 

227The `:*` suffix matches any command that starts with the specified prefix. This works with multi-word commands. The following configuration allows npm and git commit commands while blocking git push and rm -rf:

228 

229```json theme={null}

230{

231 "permissions": {

232 "allow": [

233 "Bash(npm run:*)",

234 "Bash(git commit:*)",

235 "Bash(docker compose:*)"

236 ],

237 "deny": [

238 "Bash(git push:*)",

239 "Bash(rm -rf:*)"

240 ]

241 }

242}

243```

244 

245**Glob matching with `*`**

246 

247The `*` wildcard can appear at the beginning, middle, or end of a pattern. The following configuration allows any git command targeting main (like `git checkout main`, `git merge main`) and any version check command (like `node --version`, `npm --version`):

248 

249```json theme={null}

250{

251 "permissions": {

252 "allow": [

253 "Bash(git * main)",

254 "Bash(* --version)"

255 ]

256 }

257}

258```

259 

260<Warning>

261 Bash permission patterns that try to constrain command arguments are fragile. For example, `Bash(curl http://github.com/:*)` intends to restrict curl to GitHub URLs, but won't match `curl -X GET http://github.com/...` (flags before URL), `curl https://github.com/...` (different protocol), or commands using shell variables. Do not rely on argument-constraining patterns as a security boundary. See [Bash permission limitations](/en/iam#tool-specific-permission-rules) for alternatives.

262</Warning>

263 

264For detailed information about tool-specific permission patterns—including Read, Edit, WebFetch, MCP, Task rules, and Bash permission limitations—see [Tool-specific permission rules](/en/iam#tool-specific-permission-rules).

265 236 

266### Sandbox settings237### Sandbox settings

267 238 

268Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/sandboxing) for details.239Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/sandboxing) for details.

269 240 

270**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.

271 

272| Keys | Description | Example |241| Keys | Description | Example |

273| :-------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------ |242| :-------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ |

274| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |243| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |

275| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |244| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |

276| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |245| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |

277| `allowUnsandboxedCommands` | Allow commands to run outside the sandbox via the `dangerouslyDisableSandbox` parameter. When set to `false`, the `dangerouslyDisableSandbox` escape hatch is completely disabled and all commands must run sandboxed (or be in `excludedCommands`). Useful for enterprise policies that require strict sandboxing. Default: true | `false` |246| `allowUnsandboxedCommands` | Allow commands to run outside the sandbox via the `dangerouslyDisableSandbox` parameter. When set to `false`, the `dangerouslyDisableSandbox` escape hatch is completely disabled and all commands must run sandboxed (or be in `excludedCommands`). Useful for enterprise policies that require strict sandboxing. Default: true | `false` |

247| `filesystem.allowWrite` | Additional paths where sandboxed commands can write. Arrays are merged across all settings scopes: user, project, and managed paths are combined, not replaced. Also merged with paths from `Edit(...)` allow permission rules. See [path prefixes](#sandbox-path-prefixes) below. | `["//tmp/build", "~/.kube"]` |

248| `filesystem.denyWrite` | Paths where sandboxed commands cannot write. Arrays are merged across all settings scopes. Also merged with paths from `Edit(...)` deny permission rules. | `["//etc", "//usr/local/bin"]` |

249| `filesystem.denyRead` | Paths where sandboxed commands cannot read. Arrays are merged across all settings scopes. Also merged with paths from `Read(...)` deny permission rules. | `["~/.aws/credentials"]` |

278| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |250| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |

251| `network.allowAllUnixSockets` | Allow all Unix socket connections in sandbox. Default: false | `true` |

279| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |252| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |

253| `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` |

254| `network.allowManagedDomainsOnly` | (Managed settings only) Only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Domains from user, project, and local settings are ignored. Non-allowed domains are blocked automatically without prompting the user. Denied domains are still respected from all sources. Default: false | `true` |

280| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |255| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |

281| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |256| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |

282| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |257| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |

258| `enableWeakerNetworkIsolation` | (macOS only) Allow access to the system TLS trust service (`com.apple.trustd.agent`) in the sandbox. Required for Go-based tools like `gh`, `gcloud`, and `terraform` to verify TLS certificates when using `httpProxyPort` with a MITM proxy and custom CA. **Reduces security** by opening a potential data exfiltration path. Default: false | `true` |

259 

260#### Sandbox path prefixes

261 

262Paths in `filesystem.allowWrite`, `filesystem.denyWrite`, and `filesystem.denyRead` support these prefixes:

263 

264| Prefix | Meaning | Example |

265| :---------------- | :------------------------------------------ | :------------------------------------- |

266| `//` | Absolute path from filesystem root | `//tmp/build` becomes `/tmp/build` |

267| `~/` | Relative to home directory | `~/.kube` becomes `$HOME/.kube` |

268| `/` | Relative to the settings file's directory | `/build` becomes `$SETTINGS_DIR/build` |

269| `./` or no prefix | Relative path (resolved by sandbox runtime) | `./output` |

283 270 

284**Configuration example:**271**Configuration example:**

285 272 


289 "enabled": true,276 "enabled": true,

290 "autoAllowBashIfSandboxed": true,277 "autoAllowBashIfSandboxed": true,

291 "excludedCommands": ["docker"],278 "excludedCommands": ["docker"],

279 "filesystem": {

280 "allowWrite": ["//tmp/build", "~/.kube"],

281 "denyRead": ["~/.aws/credentials"]

282 },

292 "network": {283 "network": {

284 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],

293 "allowUnixSockets": [285 "allowUnixSockets": [

294 "/var/run/docker.sock"286 "/var/run/docker.sock"

295 ],287 ],

296 "allowLocalBinding": true288 "allowLocalBinding": true

297 }289 }

298 },

299 "permissions": {

300 "deny": [

301 "Read(.envrc)",

302 "Read(~/.aws/**)"

303 ]

304 }290 }

305}291}

306```292```

307 293 

308**Filesystem and network restrictions** use standard permission rules:294**Filesystem and network restrictions** can be configured in two ways that are merged together:

309 295 

310* Use `Read` deny rules to block Claude from reading specific files or directories296* **`sandbox.filesystem` settings** (shown above): Control paths at the OS-level sandbox boundary. These restrictions apply to all subprocess commands (e.g., `kubectl`, `terraform`, `npm`), not just Claude's file tools.

311* Use `Edit` allow rules to let Claude write to directories beyond the current working directory297* **Permission rules**: Use `Edit` allow/deny rules to control Claude's file tool access, `Read` deny rules to block reads, and `WebFetch` allow/deny rules to control network domains. Paths from these rules are also merged into the sandbox configuration.

312* Use `Edit` deny rules to block writes to specific paths

313* Use `WebFetch` allow/deny rules to control which network domains Claude can access

314 298 

315### Attribution settings299### Attribution settings

316 300 


326 310 

327**Default commit attribution:**311**Default commit attribution:**

328 312 

329```313```text theme={null}

330🤖 Generated with [Claude Code](https://claude.com/claude-code)314🤖 Generated with [Claude Code](https://claude.com/claude-code)

331 315 

332 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>316 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

333```317```

334 318 

335**Default pull request attribution:**319**Default pull request attribution:**

336 320 

337```321```text theme={null}

338🤖 Generated with [Claude Code](https://claude.com/claude-code)322🤖 Generated with [Claude Code](https://claude.com/claude-code)

339```323```

340 324 


374 358 

375Output newline-separated file paths to stdout (currently limited to 15):359Output newline-separated file paths to stdout (currently limited to 15):

376 360 

377```361```text theme={null}

378src/components/Button.tsx362src/components/Button.tsx

379src/components/Modal.tsx363src/components/Modal.tsx

380src/components/Form.tsx364src/components/Form.tsx


390 374 

391### Hook configuration375### Hook configuration

392 376 

393**Managed settings only**: Controls which hooks are allowed to run. This setting can only be configured in [managed settings](#settings-files) and provides administrators with strict control over hook execution.377These settings control which hooks are allowed to run and what HTTP hooks can access. The `allowManagedHooksOnly` setting can only be configured in [managed settings](#settings-files). The URL and env var allowlists can be set at any settings level and merge across sources.

394 378 

395**Behavior when `allowManagedHooksOnly` is `true`:**379**Behavior when `allowManagedHooksOnly` is `true`:**

396 380 

397* Managed hooks and SDK hooks are loaded381* Managed hooks and SDK hooks are loaded

398* User hooks, project hooks, and plugin hooks are blocked382* User hooks, project hooks, and plugin hooks are blocked

399 383 

400**Configuration:**384**Restrict HTTP hook URLs:**

385 

386Limit which URLs HTTP hooks can target. Supports `*` as a wildcard for matching. When the array is defined, HTTP hooks targeting non-matching URLs are silently blocked.

387 

388```json theme={null}

389{

390 "allowedHttpHookUrls": ["https://hooks.example.com/*", "http://localhost:*"]

391}

392```

393 

394**Restrict HTTP hook environment variables:**

395 

396Limit which environment variable names HTTP hooks can interpolate into header values. Each hook's effective `allowedEnvVars` is the intersection of its own list and this setting.

401 397 

402```json theme={null}398```json theme={null}

403{399{

404 "allowManagedHooksOnly": true400 "httpHookAllowedEnvVars": ["MY_TOKEN", "HOOK_SECRET"]

405}401}

406```402```

407 403 


409 405 

410Settings apply in order of precedence. From highest to lowest:406Settings apply in order of precedence. From highest to lowest:

411 407 

4121. **Managed settings** (`managed-settings.json`)4081. **Managed settings** ([server-managed](/en/server-managed-settings), [MDM/OS-level policies](#configuration-scopes), or [managed settings](/en/settings#settings-files))

413 * Policies deployed by IT/DevOps to system directories409 * Policies deployed by IT through server delivery, MDM configuration profiles, registry policies, or managed settings files

414 * Cannot be overridden by user or project settings410 * Cannot be overridden by any other level, including command line arguments

411 * Within the managed tier, precedence is: server-managed > MDM/OS-level policies > `managed-settings.json` > HKCU registry (Windows only). Only one managed source is used; sources do not merge.

415 412 

4162. **Command line arguments**4132. **Command line arguments**

417 * Temporary overrides for a specific session414 * Temporary overrides for a specific session


427 424 

428This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience.425This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience.

429 426 

430For example, if your user settings allow `Bash(npm run:*)` but a project's shared settings deny it, the project setting takes precedence and the command is blocked.427For example, if your user settings allow `Bash(npm run *)` but a project's shared settings deny it, the project setting takes precedence and the command is blocked.

428 

429<Note>

430 **Array settings merge across scopes.** When the same array-valued setting (such as `sandbox.filesystem.allowWrite` or `permissions.allow`) appears in multiple scopes, the arrays are **concatenated and deduplicated**, not replaced. This means lower-priority scopes can add entries without overriding those set by higher-priority scopes, and vice versa. For example, if managed settings set `allowWrite` to `["//opt/company-tools"]` and a user adds `["~/.kube"]`, both paths are included in the final configuration.

431</Note>

432 

433### Verify active settings

434 

435Run `/status` inside Claude Code to see which settings sources are active and where they come from. The output shows each configuration layer (managed, user, project) along with its origin, such as `Enterprise managed settings (remote)`, `Enterprise managed settings (plist)`, `Enterprise managed settings (HKLM)`, or `Enterprise managed settings (file)`. If a settings file contains errors, `/status` reports the issue so you can fix it.

431 436 

432### Key points about the configuration system437### Key points about the configuration system

433 438 


554* `github`: GitHub repository (uses `repo`)559* `github`: GitHub repository (uses `repo`)

555* `git`: Any git URL (uses `url`)560* `git`: Any git URL (uses `url`)

556* `directory`: Local filesystem path (uses `path`, for development only)561* `directory`: Local filesystem path (uses `path`, for development only)

562* `hostPattern`: regex pattern to match marketplace hosts (uses `hostPattern`)

557 563 

558#### `strictKnownMarketplaces`564#### `strictKnownMarketplaces`

559 565 

560**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [`managed-settings.json`](/en/iam#managed-settings) and provides administrators with strict control over marketplace sources.566**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [managed settings](/en/settings#settings-files) and provides administrators with strict control over marketplace sources.

561 567 

562**Managed settings file locations**:568**Managed settings file locations**:

563 569 


570* Only available in managed settings (`managed-settings.json`)576* Only available in managed settings (`managed-settings.json`)

571* Cannot be overridden by user or project settings (highest precedence)577* Cannot be overridden by user or project settings (highest precedence)

572* Enforced BEFORE network/filesystem operations (blocked sources never execute)578* Enforced BEFORE network/filesystem operations (blocked sources never execute)

573* Uses exact matching for source specifications (including `ref`, `path` for git sources)579* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching

574 580 

575**Allowlist behavior**:581**Allowlist behavior**:

576 582 


580 586 

581**All supported source types**:587**All supported source types**:

582 588 

583The allowlist supports six marketplace source types. Each source must match exactly for a user's marketplace addition to be allowed.589The allowlist supports seven marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host.

584 590 

5851. **GitHub repositories**:5911. **GitHub repositories**:

586 592 


642 648 

643Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)649Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)

644 650 

6517. **Host pattern matching**:

652 

653```json theme={null}

654{ "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" }

655{ "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" }

656```

657 

658Fields: `hostPattern` (required: regex pattern to match against the marketplace host)

659 

660Use host pattern matching when you want to allow all marketplaces from a specific host without enumerating each repository individually. This is useful for organizations with internal GitHub Enterprise or GitLab servers where developers create their own marketplaces.

661 

662Host extraction by source type:

663 

664* `github`: always matches against `github.com`

665* `git`: extracts hostname from the URL (supports both HTTPS and SSH formats)

666* `url`: extracts hostname from the URL

667* `npm`, `file`, `directory`: not supported for host pattern matching

668 

645**Configuration examples**:669**Configuration examples**:

646 670 

647Example - Allow specific marketplaces only:671Example: allow specific marketplaces only:

648 672 

649```json theme={null}673```json theme={null}

650{674{


678}702}

679```703```

680 704 

705Example: allow all marketplaces from an internal git server:

706 

707```json theme={null}

708{

709 "strictKnownMarketplaces": [

710 {

711 "source": "hostPattern",

712 "hostPattern": "^github\\.example\\.com$"

713 }

714 ]

715}

716```

717 

681**Exact matching requirements**:718**Exact matching requirements**:

682 719 

683Marketplace sources must match **exactly** for a user's addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:720Marketplace sources must match **exactly** for a user's addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:


734}771}

735```772```

736 773 

774**Using both together**:

775 

776`strictKnownMarketplaces` is a policy gate: it controls what users may add but does not register any marketplaces. To both restrict and pre-register a marketplace for all users, set both in `managed-settings.json`:

777 

778```json theme={null}

779{

780 "strictKnownMarketplaces": [

781 { "source": "github", "repo": "acme-corp/plugins" }

782 ],

783 "extraKnownMarketplaces": {

784 "acme-tools": {

785 "source": { "source": "github", "repo": "acme-corp/plugins" }

786 }

787 }

788}

789```

790 

791With only `strictKnownMarketplaces` set, users can still add the allowed marketplace manually via `/plugin marketplace add`, but it is not available automatically.

792 

737**Important notes**:793**Important notes**:

738 794 

739* Restrictions are checked BEFORE any network requests or filesystem operations795* Restrictions are checked BEFORE any network requests or filesystem operations


757 813 

758## Environment variables814## Environment variables

759 815 

760Claude Code supports the following environment variables to control its behavior:816Environment variables let you control Claude Code behavior without editing settings files. Any variable can also be configured in [`settings.json`](#available-settings) under the `env` key to apply it to every session or roll it out to your team.

761 817 

762<Note>818See the [environment variables reference](/en/env-vars) for the full list.

763 All environment variables can also be configured in [`settings.json`](#available-settings). This is useful as a way to automatically set environment variables for each session, or to roll out a set of environment variables for your whole team or organization.

764</Note>

765 

766| Variable | Purpose |

767| :-------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

768| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |

769| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) |

770| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers you want to add to the request (in `Name: Value` format) |

771| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

772| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

773| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

774| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry authentication (see [Microsoft Foundry](/en/microsoft-foundry)) |

775| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) |

776| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |

777| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |

778| `AWS_BEARER_TOKEN_BEDROCK` | Bedrock API key for authentication (see [Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)) |

779| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |

780| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |

781| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |

782| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Set the percentage of context capacity (1-100) at which auto-compaction triggers. By default, auto-compaction triggers at approximately 95% capacity. Use lower values like `50` to compact earlier. Values above the default threshold have no effect. Applies to both main conversations and subagents. This percentage aligns with the `context_window.used_percentage` field available in [status line](/en/statusline) |

783| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |

784| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) |

785| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |

786| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |

787| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |

788| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to disable Anthropic API-specific `anthropic-beta` headers. Use this if experiencing issues like "Unexpected value(s) for the `anthropic-beta` header" when using an LLM gateway with third-party providers |

789| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Set to `1` to disable all background task functionality, including the `run_in_background` parameter on Bash and subagent tools, auto-backgrounding, and the Ctrl+B shortcut |

790| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | Time in milliseconds to wait after the query loop becomes idle before automatically exiting. Useful for automated workflows and scripts using SDK mode |

791| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `true` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |

792| `CLAUDE_CODE_TASK_LIST_ID` | Share a task list across sessions. Set the same ID in multiple Claude Code instances to coordinate on a shared task list. See [Task list](/en/interactive-mode#task-list) |

793| `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude/` to this path. Default: `/tmp` on Unix/macOS, `os.tmpdir()` on Windows |

794| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |

795| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |

796| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | Override the default token limit for file reads. Useful when you need to read larger files in full |

797| `CLAUDE_CODE_HIDE_ACCOUNT_INFO` | Set to `1` to hide your email address and organization name from the Claude Code UI. Useful when streaming or recording |

798| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |

799| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Default: 32,000. Maximum: 64,000. Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers. |

800| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic OpenTelemetry headers in milliseconds (default: 1740000 / 29 minutes). See [Dynamic headers](/en/monitoring-usage#dynamic-headers) |

801| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |

802| `CLAUDE_CODE_SHELL_PREFIX` | Command prefix to wrap all bash commands (for example, for logging or auditing). Example: `/path/to/logger.sh` will execute `/path/to/logger.sh <command>` |

803| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |

804| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |

805| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) |

806| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) |

807| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |

808| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) |

809| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |

810| `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files |

811| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. |

812| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |

813| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |

814| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |

815| `DISABLE_INSTALLATION_CHECKS` | Set to `1` to disable installation warnings. Use only when manually managing the installation location, as this can mask issues with standard installations |

816| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text |

817| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |

818| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

819| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

820| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

821| `DISABLE_TELEMETRY` | Set to `1` to opt out of Statsig telemetry (note that Statsig events do not include user data like code, file paths, or bash commands) |

822| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/en/mcp#scale-with-mcp-tool-search). Values: `auto` (default, enables at 10% context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `true` (always on), `false` (disabled) |

823| `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |

824| `HTTP_PROXY` | Specify HTTP proxy server for network connections |

825| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |

826| `IS_DEMO` | Set to `true` to enable demo mode: hides email and organization from the UI, skips onboarding, and hides internal commands. Useful for streaming or recording sessions |

827| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000) |

828| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) token budget. Thinking is enabled at max budget (31,999 tokens) by default. Use this to limit the budget (for example, `MAX_THINKING_TOKENS=10000`) or disable thinking entirely (`MAX_THINKING_TOKENS=0`). Extended thinking improves performance on complex reasoning and coding tasks but impacts [prompt caching efficiency](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#caching-with-thinking-blocks). |

829| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |

830| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |

831| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |

832| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Maximum number of characters for skill metadata shown to the [Skill tool](/en/skills#control-who-invokes-a-skill) (default: 15000). Legacy name kept for backwards compatibility. |

833| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code |

834| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |

835| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |

836| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |

837| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |

838| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |

839 819 

840## Tools available to Claude820## Tools available to Claude

841 821 

842Claude Code has access to a set of powerful tools that help it understand and modify your codebase:822Claude Code has access to a set of tools for reading, editing, searching, running commands, and orchestrating subagents. Tool names are the exact strings you use in permission rules and hook matchers.

843 

844| Tool | Description | Permission Required |

845| :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |

846| **AskUserQuestion** | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |

847| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes |

848| **TaskOutput** | Retrieves output from a background task (bash shell or subagent) | No |

849| **Edit** | Makes targeted edits to specific files | Yes |

850| **ExitPlanMode** | Prompts the user to exit plan mode and start coding | Yes |

851| **Glob** | Finds files based on pattern matching | No |

852| **Grep** | Searches for patterns in file contents | No |

853| **KillShell** | Kills a running background bash shell by its ID | No |

854| **MCPSearch** | Searches for and loads MCP tools when [tool search](/en/mcp#scale-with-mcp-tool-search) is enabled | No |

855| **NotebookEdit** | Modifies Jupyter notebook cells | Yes |

856| **Read** | Reads the contents of files | No |

857| **Skill** | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

858| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |

859| **TaskCreate** | Creates a new task in the task list | No |

860| **TaskGet** | Retrieves full details for a specific task | No |

861| **TaskList** | Lists all tasks with their current status | No |

862| **TaskUpdate** | Updates task status, dependencies, or details | No |

863| **WebFetch** | Fetches content from a specified URL | Yes |

864| **WebSearch** | Performs web searches with domain filtering | Yes |

865| **Write** | Creates or overwrites files | Yes |

866| **LSP** | Code intelligence via language servers. Reports type errors and warnings automatically after file edits. Also supports navigation operations: jump to definitions, find references, get type info, list symbols, find implementations, trace call hierarchies. Requires a [code intelligence plugin](/en/discover-plugins#code-intelligence) and its language server binary | No |

867 823 

868Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/iam#tool-specific-permission-rules).824See the [tools reference](/en/tools-reference) for the full list and Bash tool behavior details.

869 

870### Bash tool behavior

871 

872The Bash tool executes shell commands with the following persistence behavior:

873 

874* **Working directory persists**: When Claude changes the working directory (for example, `cd /path/to/dir`), subsequent Bash commands will execute in that directory. You can use `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1` to reset to the project directory after each command.

875* **Environment variables do NOT persist**: Environment variables set in one Bash command (for example, `export MY_VAR=value`) are **not** available in subsequent Bash commands. Each Bash command runs in a fresh shell environment.

876 

877To make environment variables available in Bash commands, you have **three options**:

878 

879**Option 1: Activate environment before starting Claude Code** (simplest approach)

880 

881Activate your virtual environment in your terminal before launching Claude Code:

882 

883```bash theme={null}

884conda activate myenv

885# or: source /path/to/venv/bin/activate

886claude

887```

888 

889This works for shell environments but environment variables set within Claude's Bash commands will not persist between commands.

890 

891**Option 2: Set CLAUDE\_ENV\_FILE before starting Claude Code** (persistent environment setup)

892 

893Export the path to a shell script containing your environment setup:

894 

895```bash theme={null}

896export CLAUDE_ENV_FILE=/path/to/env-setup.sh

897claude

898```

899 

900Where `/path/to/env-setup.sh` contains:

901 

902```bash theme={null}

903conda activate myenv

904# or: source /path/to/venv/bin/activate

905# or: export MY_VAR=value

906```

907 

908Claude Code will source this file before each Bash command, making the environment persistent across all commands.

909 

910**Option 3: Use a SessionStart hook** (project-specific configuration)

911 

912Configure in `.claude/settings.json`:

913 

914```json theme={null}

915{

916 "hooks": {

917 "SessionStart": [{

918 "matcher": "startup",

919 "hooks": [{

920 "type": "command",

921 "command": "echo 'conda activate myenv' >> \"$CLAUDE_ENV_FILE\""

922 }]

923 }]

924 }

925}

926```

927 

928The hook writes to `$CLAUDE_ENV_FILE`, which is then sourced before each Bash command. This is ideal for team-shared project configurations.

929 

930See [SessionStart hooks](/en/hooks#persisting-environment-variables) for more details on Option 3.

931 

932### Extending tools with hooks

933 

934You can run custom commands before or after any tool executes using

935[Claude Code hooks](/en/hooks-guide).

936 

937For example, you could automatically run a Python formatter after Claude

938modifies Python files, or prevent modifications to production configuration

939files by blocking Write operations to certain paths.

940 825 

941## See also826## See also

942 827 

943* [Identity and Access Management](/en/iam#configuring-permissions) - Permission system overview and how allow/ask/deny rules interact828* [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies

944* [Tool-specific permission rules](/en/iam#tool-specific-permission-rules) - Detailed patterns for Bash, Read, Edit, WebFetch, MCP, and Task tools, including security limitations829* [Authentication](/en/authentication): set up user access to Claude Code

945* [Managed settings](/en/iam#managed-settings) - Managed policy configuration for organizations830* [Troubleshooting](/en/troubleshooting): solutions for common configuration issues

946* [Troubleshooting](/en/troubleshooting) - Solutions for common configuration issues

947 

948 

949 

950> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

setup.md +210 −152

Details

1# Set up Claude Code1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Install, authenticate, and start using Claude Code on your development machine.5# Advanced setup

6 

7> System requirements, platform-specific installation, version management, and uninstallation for Claude Code.

8 

9This page covers system requirements, platform-specific installation details, updates, and uninstallation. For a guided walkthrough of your first session, see the [quickstart](/en/quickstart). If you've never used a terminal before, see the [terminal guide](/en/terminal-guide).

4 10 

5## System requirements11## System requirements

6 12 

7* **Operating Systems**: macOS 13.0+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows)13Claude Code runs on the following platforms and configurations:

14 

15* **Operating system**:

16 * macOS 13.0+

17 * Windows 10 1809+ or Windows Server 2019+

18 * Ubuntu 20.04+

19 * Debian 10+

20 * Alpine Linux 3.19+

8* **Hardware**: 4 GB+ RAM21* **Hardware**: 4 GB+ RAM

9* **Network**: Internet connection required (see [network configuration](/en/network-config#network-access-requirements))22* **Network**: internet connection required. See [network configuration](/en/network-config#network-access-requirements).

10* **Shell**: Works best in Bash or Zsh23* **Shell**: Bash, Zsh, PowerShell, or CMD. On Windows, [Git for Windows](https://git-scm.com/downloads/win) is required.

11* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)24* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)

12 25 

13### Additional dependencies26### Additional dependencies

14 27 

15* **ripgrep**: Usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues).28* **ripgrep**: usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues).

16* **[Node.js 18+](https://nodejs.org/en/download)**: Only required for [deprecated npm installation](#npm-installation-deprecated)

17 29 

18## Installation30## Install Claude Code

31 

32<Tip>

33 Prefer a graphical interface? The [Desktop app](/en/desktop-quickstart) lets you use Claude Code without the terminal. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs).

34 

35 New to the terminal? See the [terminal guide](/en/terminal-guide) for step-by-step instructions.

36</Tip>

19 37 

20To install Claude Code, use one of the following methods:38To install Claude Code, use one of the following methods:

21 39 


39 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

40 ```58 ```

41 59 

60 **Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it.

61 

42 <Info>62 <Info>

43 Native installations automatically update in the background to keep you on the latest version.63 Native installations automatically update in the background to keep you on the latest version.

44 </Info>64 </Info>

45 </Tab>65 </Tab>

46 66 

47 <Tab title="Homebrew">67 <Tab title="Homebrew">

48 ```sh theme={null}68 ```bash theme={null}

49 brew install --cask claude-code69 brew install --cask claude-code

50 ```70 ```

51 71 


65 </Tab>85 </Tab>

66</Tabs>86</Tabs>

67 87 

68After the installation process completes, navigate to your project and start Claude Code:88After installation completes, open a terminal in the project you want to work in and start Claude Code:

69 89 

70```bash theme={null}90```bash theme={null}

71cd your-awesome-project

72claude91claude

73```92```

74 93 

75If you encounter any issues during installation, consult the [troubleshooting guide](/en/troubleshooting).94If you encounter any issues during installation, see the [troubleshooting guide](/en/troubleshooting).

76 95 

77<Tip>96### Set up on Windows

78 Run `claude doctor` after installation to check your installation type and version.97 

79</Tip>98Claude Code on Windows requires [Git for Windows](https://git-scm.com/downloads/win) or WSL. You can launch `claude` from PowerShell, CMD, or Git Bash. Claude Code uses Git Bash internally to run commands. You do not need to run PowerShell as Administrator.

99 

100**Option 1: Native Windows with Git Bash**

101 

102Install [Git for Windows](https://git-scm.com/downloads/win), then run the install command from PowerShell or CMD.

103 

104If Claude Code can't find your Git Bash installation, set the path in your [settings.json file](/en/settings):

105 

106```json theme={null}

107{

108 "env": {

109 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

110 }

111}

112```

113 

114**Option 2: WSL**

115 

116Both WSL 1 and WSL 2 are supported. WSL 2 supports [sandboxing](/en/sandboxing) for enhanced security. WSL 1 does not support sandboxing.

117 

118### Alpine Linux and musl-based distributions

119 

120The native installer on Alpine and other musl/uClibc-based distributions requires `libgcc`, `libstdc++`, and `ripgrep`. Install these using your distribution's package manager, then set `USE_BUILTIN_RIPGREP=0`.

121 

122This example installs the required packages on Alpine:

123 

124```bash theme={null}

125apk add libgcc libstdc++ ripgrep

126```

127 

128Then set `USE_BUILTIN_RIPGREP` to `0` in your [`settings.json`](/en/settings#available-settings) file:

129 

130```json theme={null}

131{

132 "env": {

133 "USE_BUILTIN_RIPGREP": "0"

134 }

135}

136```

137 

138## Verify your installation

139 

140After installing, confirm Claude Code is working:

141 

142```bash theme={null}

143claude --version

144```

145 

146For a more detailed check of your installation and configuration, run [`claude doctor`](/en/troubleshooting#get-more-help):

147 

148```bash theme={null}

149claude doctor

150```

151 

152## Authenticate

153 

154Claude Code requires a Pro, Max, Teams, Enterprise, or Console account. The free Claude.ai plan does not include Claude Code access. You can also use Claude Code with a third-party API provider like [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry).

155 

156After installing, log in by running `claude` and following the browser prompts. See [Authentication](/en/authentication) for all account types and team setup options.

157 

158## Update Claude Code

159 

160Native installations automatically update in the background. You can [configure the release channel](#configure-release-channel) to control whether you receive updates immediately or on a delayed stable schedule, or [disable auto-updates](#disable-auto-updates) entirely. Homebrew and WinGet installations require manual updates.

161 

162### Auto-updates

163 

164Claude Code checks for updates on startup and periodically while running. Updates download and install in the background, then take effect the next time you start Claude Code.

80 165 

81<Note>166<Note>

82 **Alpine Linux and other musl/uClibc-based distributions**: The native installer requires `libgcc`, `libstdc++`, and `ripgrep`. For Alpine: `apk add libgcc libstdc++ ripgrep`. Set `USE_BUILTIN_RIPGREP=0`.167 Homebrew and WinGet installations do not auto-update. Use `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update manually.

168 

169 **Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.

170 

171 Homebrew keeps old versions on disk after upgrades. Run `brew cleanup claude-code` periodically to reclaim disk space.

83</Note>172</Note>

84 173 

85### Authentication174### Configure release channel

175 

176Control which release channel Claude Code follows for auto-updates and `claude update` with the `autoUpdatesChannel` setting:

86 177 

87#### For individuals178* `"latest"`, the default: receive new features as soon as they're released

179* `"stable"`: use a version that is typically about one week old, skipping releases with major regressions

88 180 

891. **Claude Pro or Max plan** (recommended): Subscribe to Claude's [Pro or Max plan](https://claude.ai/pricing) for a unified subscription that includes both Claude Code and Claude on the web. Manage your account in one place and log in with your Claude.ai account.181Configure this via `/config` **Auto-update channel**, or add it to your [settings.json file](/en/settings):

902. **Claude Console**: Connect through the [Claude Console](https://console.anthropic.com) and complete the OAuth process. Requires active billing in the Anthropic Console. A "Claude Code" workspace is automatically created for usage tracking and cost management. You can't create API keys for the Claude Code workspace; it's dedicated exclusively for Claude Code usage.

91 182 

92#### For teams and organizations183```json theme={null}

184{

185 "autoUpdatesChannel": "stable"

186}

187```

188 

189For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/permissions#managed-settings).

190 

191### Disable auto-updates

93 192 

941. **Claude for Teams or Enterprise** (recommended): Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or [Claude for Enterprise](https://anthropic.com/contact-sales) for centralized billing, team management, and access to both Claude Code and Claude on the web. Team members log in with their Claude.ai accounts.193Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](/en/settings#available-settings) file:

952. **Claude Console with team billing**: Set up a shared [Claude Console](https://console.anthropic.com) organization with team billing. Invite team members and assign roles for usage tracking.194 

963. **Cloud providers**: Configure Claude Code to use [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) for deployments with your existing cloud infrastructure.195```json theme={null}

196{

197 "env": {

198 "DISABLE_AUTOUPDATER": "1"

199 }

200}

201```

202 

203### Update manually

204 

205To apply an update immediately without waiting for the next background check, run:

206 

207```bash theme={null}

208claude update

209```

210 

211## Advanced installation options

212 

213These options are for version pinning, migrating from npm, and verifying binary integrity.

97 214 

98### Install a specific version215### Install a specific version

99 216 

100The native installer accepts either a specific version number or a release channel (`latest` or `stable`). The channel you choose at install time becomes your default for auto-updates. See [Configure release channel](#configure-release-channel) for more information.217The native installer accepts either a specific version number or a release channel (`latest` or `stable`). The channel you choose at install time becomes your default for auto-updates. See [configure release channel](#configure-release-channel) for more information.

101 218 

102To install the latest version (default):219To install the latest version (default):

103 220 


165 </Tab>282 </Tab>

166</Tabs>283</Tabs>

167 284 

168### Binary integrity and code signing285### Deprecated npm installation

169 286 

170* SHA256 checksums for all platforms are published in the release manifests, currently located at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json` (example: replace `{VERSION}` with `2.0.30`)287npm installation is deprecated. The native installer is faster, requires no dependencies, and auto-updates in the background. Use the [native installation](#install-claude-code) method when possible.

171* Signed binaries are distributed for the following platforms:

172 * macOS: Signed by "Anthropic PBC" and notarized by Apple

173 * Windows: Signed by "Anthropic, PBC"

174 288 

175## NPM installation (deprecated)289#### Migrate from npm to native

176 290 

177NPM installation is deprecated. Use the [native installation](#installation) method when possible. To migrate an existing npm installation to native, run `claude install`.291If you previously installed Claude Code with npm, switch to the native installer:

178 292 

179**Global npm installation**293```bash theme={null}

294# Install the native binary

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

180 296 

181```sh theme={null}297# Remove the old npm installation

182npm install -g @anthropic-ai/claude-code298npm uninstall -g @anthropic-ai/claude-code

183```299```

184 300 

185<Warning>301You can also run `claude install` from an existing npm installation to install the native binary alongside it, then remove the npm version.

186 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks.

187 If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshooting#command-not-found-claude-or-permission-errors) for recommended solutions.

188</Warning>

189 302 

190## Windows setup303#### Install with npm

191 304 

192**Option 1: Claude Code within WSL**305If you need npm installation for compatibility reasons, you must have [Node.js 18+](https://nodejs.org/en/download) installed. Install the package globally:

193 306 

194* Both WSL 1 and WSL 2 are supported307```bash theme={null}

195* WSL 2 supports [sandboxing](/en/sandboxing) for enhanced security. WSL 1 does not support sandboxing.308npm install -g @anthropic-ai/claude-code

196 

197**Option 2: Claude Code on native Windows with Git Bash**

198 

199* Requires [Git for Windows](https://git-scm.com/downloads/win)

200* For portable Git installations, specify the path to your `bash.exe`:

201 ```powershell theme={null}

202 $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"

203 ```

204 

205## Update Claude Code

206 

207### Auto updates

208 

209Claude Code automatically keeps itself up to date to ensure you have the latest features and security fixes.

210 

211* **Update checks**: Performed on startup and periodically while running

212* **Update process**: Downloads and installs automatically in the background

213* **Notifications**: You'll see a notification when updates are installed

214* **Applying updates**: Updates take effect the next time you start Claude Code

215 

216<Note>

217 Homebrew and WinGet installations do not auto-update. Use `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update manually.

218 

219 **Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.

220</Note>

221 

222### Configure release channel

223 

224Configure which release channel Claude Code follows for both auto-updates and `claude update` with the `autoUpdatesChannel` setting:

225 

226* `"latest"` (default): Receive new features as soon as they're released

227* `"stable"`: Use a version that is typically about one week old, skipping releases with major regressions

228 

229Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/en/settings):

230 

231```json theme={null}

232{

233 "autoUpdatesChannel": "stable"

234}

235```309```

236 310 

237For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/iam#managed-settings).311<Warning>

238 312 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshooting#permission-errors-during-installation).

239### Disable auto-updates313</Warning>

240 

241Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/settings):

242 314 

243```bash theme={null}315### Binary integrity and code signing

244export DISABLE_AUTOUPDATER=1

245```

246 316 

247### Update manually317You can verify the integrity of Claude Code binaries using SHA256 checksums and code signatures.

248 318 

249```bash theme={null}319* SHA256 checksums for all platforms are published in the release manifests at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json`. Replace `{VERSION}` with a version number such as `2.0.30`.

250claude update320* Signed binaries are distributed for the following platforms:

251```321 * **macOS**: signed by "Anthropic PBC" and notarized by Apple

322 * **Windows**: signed by "Anthropic, PBC"

252 323 

253## Uninstall Claude Code324## Uninstall Claude Code

254 325 

255If you need to uninstall Claude Code, follow the instructions for your installation method.326To remove Claude Code, follow the instructions for your installation method.

256 327 

257### Native installation328### Native installation

258 329 

259Remove the Claude Code binary and version files:330Remove the Claude Code binary and version files:

260 331 

261**macOS, Linux, WSL:**332<Tabs>

262 333 <Tab title="macOS, Linux, WSL">

263```bash theme={null}334 ```bash theme={null}

264rm -f ~/.local/bin/claude335 rm -f ~/.local/bin/claude

265rm -rf ~/.local/share/claude336 rm -rf ~/.local/share/claude

266```337 ```

267 338 </Tab>

268**Windows PowerShell:**

269 

270```powershell theme={null}

271Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force

272Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force

273```

274 

275**Windows CMD:**

276 339 

277```batch theme={null}340 <Tab title="Windows PowerShell">

278del "%USERPROFILE%\.local\bin\claude.exe"341 ```powershell theme={null}

279rmdir /s /q "%USERPROFILE%\.local\share\claude"342 Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force

280```343 Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force

344 ```

345 </Tab>

346</Tabs>

281 347 

282### Homebrew installation348### Homebrew installation

283 349 

350Remove the Homebrew cask:

351 

284```bash theme={null}352```bash theme={null}

285brew uninstall --cask claude-code353brew uninstall --cask claude-code

286```354```

287 355 

288### WinGet installation356### WinGet installation

289 357 

358Remove the WinGet package:

359 

290```powershell theme={null}360```powershell theme={null}

291winget uninstall Anthropic.ClaudeCode361winget uninstall Anthropic.ClaudeCode

292```362```

293 363 

294### NPM installation364### npm

365 

366Remove the global npm package:

295 367 

296```bash theme={null}368```bash theme={null}

297npm uninstall -g @anthropic-ai/claude-code369npm uninstall -g @anthropic-ai/claude-code

298```370```

299 371 

300### Clean up configuration files (optional)372### Remove configuration files

301 373 

302<Warning>374<Warning>

303 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.375 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.


305 377 

306To remove Claude Code settings and cached data:378To remove Claude Code settings and cached data:

307 379 

308**macOS, Linux, WSL:**380<Tabs>

309 381 <Tab title="macOS, Linux, WSL">

310```bash theme={null}382 ```bash theme={null}

311# Remove user settings and state383 # Remove user settings and state

312rm -rf ~/.claude384 rm -rf ~/.claude

313rm ~/.claude.json385 rm ~/.claude.json

314 

315# Remove project-specific settings (run from your project directory)

316rm -rf .claude

317rm -f .mcp.json

318```

319 

320**Windows PowerShell:**

321 

322```powershell theme={null}

323# Remove user settings and state

324Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force

325Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force

326 

327# Remove project-specific settings (run from your project directory)

328Remove-Item -Path ".claude" -Recurse -Force

329Remove-Item -Path ".mcp.json" -Force

330```

331 

332**Windows CMD:**

333 

334```batch theme={null}

335REM Remove user settings and state

336rmdir /s /q "%USERPROFILE%\.claude"

337del "%USERPROFILE%\.claude.json"

338 

339REM Remove project-specific settings (run from your project directory)

340rmdir /s /q ".claude"

341del ".mcp.json"

342```

343 386 

387 # Remove project-specific settings (run from your project directory)

388 rm -rf .claude

389 rm -f .mcp.json

390 ```

391 </Tab>

344 392 

393 <Tab title="Windows PowerShell">

394 ```powershell theme={null}

395 # Remove user settings and state

396 Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force

397 Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force

345 398 

346> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt399 # Remove project-specific settings (run from your project directory)

400 Remove-Item -Path ".claude" -Recurse -Force

401 Remove-Item -Path ".mcp.json" -Force

402 ```

403 </Tab>

404</Tabs>

skills.md +79 −30

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Extend Claude with skills5# Extend Claude with skills

2 6 

3> Create, manage, and share skills to extend Claude's capabilities in Claude Code. Includes custom slash commands.7> Create, manage, and share skills to extend Claude's capabilities in Claude Code. Includes custom commands and bundled skills.

4 8 

5Skills 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 `/skill-name`.9Skills 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 `/skill-name`.

6 10 

7<Note>11<Note>

8 For built-in commands like `/help` and `/compact`, see [interactive mode](/en/interactive-mode#built-in-commands).12 For built-in commands like `/help` and `/compact`, see the [built-in commands reference](/en/commands).

9 13 

10 **Custom slash commands have been merged into skills.** A file at `.claude/commands/review.md` and a skill at `.claude/skills/review/SKILL.md` both create `/review` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to [control whether you or Claude invokes them](#control-who-invokes-a-skill), and the ability for Claude to load them automatically when relevant.14 **Custom commands have been merged into skills.** A file at `.claude/commands/deploy.md` and a skill at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to [control whether you or Claude invokes them](#control-who-invokes-a-skill), and the ability for Claude to load them automatically when relevant.

11</Note>15</Note>

12 16 

13Claude Code skills follow the [Agent Skills](https://agentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like [invocation control](#control-who-invokes-a-skill), [subagent execution](#run-skills-in-a-subagent), and [dynamic context injection](#inject-dynamic-context).17Claude Code skills follow the [Agent Skills](https://agentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like [invocation control](#control-who-invokes-a-skill), [subagent execution](#run-skills-in-a-subagent), and [dynamic context injection](#inject-dynamic-context).

14 18 

19## Bundled skills

20 

21Bundled skills ship with Claude Code and are available in every session. Unlike [built-in commands](/en/commands), which execute fixed logic directly, bundled skills are prompt-based: they give Claude a detailed playbook and let it orchestrate the work using its tools. This means bundled skills can spawn parallel agents, read files, and adapt to your codebase.

22 

23You invoke bundled skills the same way as any other skill: type `/` followed by the skill name. In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

24 

25| Skill | Purpose |

26| :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

27| `/batch <instruction>` | Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one background agent per unit in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Each agent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React` |

28| `/claude-api` | Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Agent SDK reference for Python and TypeScript. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic`, `@anthropic-ai/sdk`, or `claude_agent_sdk` |

29| `/debug [description]` | Troubleshoot your current Claude Code session by reading the session debug log. Optionally describe the issue to focus the analysis |

30| `/loop [interval] <prompt>` | Run a prompt repeatedly on an interval while the session stays open. Useful for polling a deployment, babysitting a PR, or periodically re-running another skill. Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](/en/scheduled-tasks) |

31| `/simplify [focus]` | Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency` |

32 

15## Getting started33## Getting started

16 34 

17### Create your first skill35### Create your first skill


54 72 

55 **Let Claude invoke it automatically** by asking something that matches the description:73 **Let Claude invoke it automatically** by asking something that matches the description:

56 74 

57 ```75 ```text theme={null}

58 How does this code work?76 How does this code work?

59 ```77 ```

60 78 

61 **Or invoke it directly** with the skill name:79 **Or invoke it directly** with the skill name:

62 80 

63 ```81 ```text theme={null}

64 /explain-code src/auth/login.ts82 /explain-code src/auth/login.ts

65 ```83 ```

66 84 


73Where you store a skill determines who can use it:91Where you store a skill determines who can use it:

74 92 

75| Location | Path | Applies to |93| Location | Path | Applies to |

76| :--------- | :----------------------------------------------- | :----------------------------- |94| :--------- | :-------------------------------------------------- | :----------------------------- |

77| Enterprise | See [managed settings](/en/iam#managed-settings) | All users in your organization |95| Enterprise | See [managed settings](/en/settings#settings-files) | All users in your organization |

78| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |96| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |

79| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |97| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |

80| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |98| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |


87 105 

88Each skill is a directory with `SKILL.md` as the entrypoint:106Each skill is a directory with `SKILL.md` as the entrypoint:

89 107 

90```108```text theme={null}

91my-skill/109my-skill/

92├── SKILL.md # Main instructions (required)110├── SKILL.md # Main instructions (required)

93├── template.md # Template for Claude to fill in111├── template.md # Template for Claude to fill in


103 Files in `.claude/commands/` still work and support the same [frontmatter](#frontmatter-reference). Skills are recommended since they support additional features like supporting files.121 Files in `.claude/commands/` still work and support the same [frontmatter](#frontmatter-reference). Skills are recommended since they support additional features like supporting files.

104</Note>122</Note>

105 123 

124#### Skills from additional directories

125 

126Skills defined in `.claude/skills/` within directories added via `--add-dir` are loaded automatically and picked up by live change detection, so you can edit them during a session without restarting.

127 

128<Note>

129 CLAUDE.md files from `--add-dir` directories are not loaded by default. To load them, set `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`. See [Load from additional directories](/en/memory#load-from-additional-directories).

130</Note>

131 

106## Configure skills132## Configure skills

107 133 

108Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.134Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.


171| `model` | No | Model to use when this skill is active. |197| `model` | No | Model to use when this skill is active. |

172| `context` | No | Set to `fork` to run in a forked subagent context. |198| `context` | No | Set to `fork` to run in a forked subagent context. |

173| `agent` | No | Which subagent type to use when `context: fork` is set. |199| `agent` | No | Which subagent type to use when `context: fork` is set. |

174| `hooks` | No | Hooks scoped to this skill's lifecycle. See [Hooks](/en/hooks) for configuration format. |200| `hooks` | No | Hooks scoped to this skill's lifecycle. See [Hooks in skills and agents](/en/hooks#hooks-in-skills-and-agents) for configuration format. |

175 201 

176#### Available string substitutions202#### Available string substitutions

177 203 

178Skills support string substitution for dynamic values in the skill content:204Skills support string substitution for dynamic values in the skill content:

179 205 

180| Variable | Description |206| Variable | Description |

181| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |207| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

182| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |208| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |

209| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |

210| `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. |

183| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |211| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |

212| `${CLAUDE_SKILL_DIR}` | The directory containing the skill's `SKILL.md` file. For plugin skills, this is the skill's subdirectory within the plugin, not the plugin root. Use this in bash injection commands to reference scripts or files bundled with the skill, regardless of the current working directory. |

184 213 

185**Example using substitutions:**214**Example using substitutions:**

186 215 


199 228 

200Skills can include multiple files in their directory. This keeps `SKILL.md` focused on the essentials while letting Claude access detailed reference material only when needed. Large reference docs, API specifications, or example collections don't need to load into context every time the skill runs.229Skills can include multiple files in their directory. This keeps `SKILL.md` focused on the essentials while letting Claude access detailed reference material only when needed. Large reference docs, API specifications, or example collections don't need to load into context every time the skill runs.

201 230 

202```231```text theme={null}

203my-skill/232my-skill/

204├── SKILL.md (required - overview and navigation)233├── SKILL.md (required - overview and navigation)

205├── reference.md (detailed API docs - loaded when needed)234├── reference.md (detailed API docs - loaded when needed)


294 323 

295If you invoke a skill with arguments but the skill doesn't include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed.324If you invoke a skill with arguments but the skill doesn't include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed.

296 325 

326To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`:

327 

328```yaml theme={null}

329---

330name: migrate-component

331description: Migrate a component from one framework to another

332---

333 

334Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2].

335Preserve all existing behavior and tests.

336```

337 

338Running `/migrate-component SearchBar React Vue` replaces `$ARGUMENTS[0]` with `SearchBar`, `$ARGUMENTS[1]` with `React`, and `$ARGUMENTS[2]` with `Vue`. The same skill using the `$N` shorthand:

339 

340```yaml theme={null}

341---

342name: migrate-component

343description: Migrate a component from one framework to another

344---

345 

346Migrate the $0 component from $1 to $2.

347Preserve all existing behavior and tests.

348```

349 

297## Advanced patterns350## Advanced patterns

298 351 

299### Inject dynamic context352### Inject dynamic context


308description: Summarize changes in a pull request361description: Summarize changes in a pull request

309context: fork362context: fork

310agent: Explore363agent: Explore

311allowed-tools: Bash(gh:*)364allowed-tools: Bash(gh *)

312---365---

313 366 

314## Pull request context367## Pull request context


379 432 

380### Restrict Claude's skill access433### Restrict Claude's skill access

381 434 

382By default, Claude can invoke any skill that doesn't have `disable-model-invocation: true` set. Built-in commands like `/compact` and `/init` are not available through the Skill tool.435By default, Claude can invoke any skill that doesn't have `disable-model-invocation: true` set. Skills that define `allowed-tools` grant Claude access to those tools without per-use approval when the skill is active. Your [permission settings](/en/permissions) still govern baseline approval behavior for all other tools. Built-in commands like `/compact` and `/init` are not available through the Skill tool.

383 436 

384Three ways to control which skills Claude can invoke:437Three ways to control which skills Claude can invoke:

385 438 

386**Disable all skills** by denying the Skill tool in `/permissions`:439**Disable all skills** by denying the Skill tool in `/permissions`:

387 440 

388```441```text theme={null}

389# Add to deny rules:442# Add to deny rules:

390Skill443Skill

391```444```

392 445 

393**Allow or deny specific skills** using [permission rules](/en/iam):446**Allow or deny specific skills** using [permission rules](/en/permissions):

394 447 

395```448```text theme={null}

396# Allow only specific skills449# Allow only specific skills

397Skill(commit)450Skill(commit)

398Skill(review-pr:*)451Skill(review-pr *)

399 452 

400# Deny specific skills453# Deny specific skills

401Skill(deploy:*)454Skill(deploy *)

402```455```

403 456 

404Permission syntax: `Skill(name)` for exact match, `Skill(name:*)` for prefix match with any arguments.457Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments.

405 458 

406**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.459**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.

407 460 


415 468 

416* **Project skills**: Commit `.claude/skills/` to version control469* **Project skills**: Commit `.claude/skills/` to version control

417* **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins)470* **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins)

418* **Managed**: Deploy organization-wide through [managed settings](/en/iam#managed-settings)471* **Managed**: Deploy organization-wide through [managed settings](/en/settings#settings-files)

419 472 

420### Generate visual output473### Generate visual output

421 474 


435---488---

436name: codebase-visualizer489name: codebase-visualizer

437description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.490description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.

438allowed-tools: Bash(python:*)491allowed-tools: Bash(python *)

439---492---

440 493 

441# Codebase Visualizer494# Codebase Visualizer


448 501 

449```bash502```bash

450python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .503python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .

451```504```text

452 505 

453This creates `codebase-map.html` in the current directory and opens it in your default browser.506This creates `codebase-map.html` in the current directory and opens it in your default browser.

454 507 


626 679 

627### Claude doesn't see all my skills680### Claude doesn't see all my skills

628 681 

629Skill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget (default 15,000 characters). Run `/context` to check for a warning about excluded skills.682Skill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget. The budget scales dynamically at 2% of the context window, with a fallback of 16,000 characters. Run `/context` to check for a warning about excluded skills.

630 683 

631To increase the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.684To override the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.

632 685 

633## Related resources686## Related resources

634 687 


636* **[Plugins](/en/plugins)**: package and distribute skills with other extensions689* **[Plugins](/en/plugins)**: package and distribute skills with other extensions

637* **[Hooks](/en/hooks)**: automate workflows around tool events690* **[Hooks](/en/hooks)**: automate workflows around tool events

638* **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context691* **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context

639* **[Interactive mode](/en/interactive-mode#built-in-commands)**: built-in commands and shortcuts692* **[Built-in commands](/en/commands)**: reference for built-in `/` commands

640* **[Permissions](/en/iam)**: control tool and skill access693* **[Permissions](/en/permissions)**: control tool and skill access

641 

642 

643 

644> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

slack.md +32 −7

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code in Slack5# Claude Code in Slack

2 6 

3> Delegate coding tasks directly from your Slack workspace7> Delegate coding tasks directly from your Slack workspace


19 23 

20| Requirement | Details |24| Requirement | Details |

21| :--------------------- | :----------------------------------------------------------------------------- |25| :--------------------- | :----------------------------------------------------------------------------- |

22| Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats) |26| Claude Plan | Pro, Max, Teams, or Enterprise with Claude Code access (premium seats) |

23| Claude Code on the web | Access to [Claude Code on the web](/en/claude-code-on-the-web) must be enabled |27| Claude Code on the web | Access to [Claude Code on the web](/en/claude-code-on-the-web) must be enabled |

24| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |28| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |

25| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |29| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |


60 In Code + Chat mode, if Claude routes a message to Chat but you wanted a coding session, you can click "Retry as Code" to create a Claude Code session instead. Similarly, if it's routed to Code but you wanted a Chat session, you can choose that option in that thread.64 In Code + Chat mode, if Claude routes a message to Chat but you wanted a coding session, you can click "Retry as Code" to create a Claude Code session instead. Similarly, if it's routed to Code but you wanted a Chat session, you can choose that option in that thread.

61 </Note>65 </Note>

62 </Step>66 </Step>

67 

68 <Step title="Add Claude to channels">

69 Claude is not automatically added to any channels after installation. To use Claude in a channel, invite it by typing `/invite @Claude` in that channel. Claude can only respond to @mentions in channels where it has been added.

70 </Step>

63</Steps>71</Steps>

64 72 

65## How it works73## How it works


123| Repository Access | Users can only access repositories they've personally connected |131| Repository Access | Users can only access repositories they've personally connected |

124| Session History | Sessions appear in your Claude Code history on claude.ai/code |132| Session History | Sessions appear in your Claude Code history on claude.ai/code |

125 133 

126### Workspace admin permissions134### Workspace-level access

135 

136Slack workspace administrators control whether the Claude app is available in their workspace:

137 

138| Control | Description |

139| :--------------------------- | :---------------------------------------------------------------------------------------------------------------- |

140| App installation | Workspace admins decide whether to install the Claude app from the Slack App Marketplace |

141| Enterprise Grid distribution | For Enterprise Grid organizations, organization admins can control which workspaces have access to the Claude app |

142| App removal | Removing the app from a workspace immediately revokes access for all users in that workspace |

143 

144### Channel-based access control

127 145 

128Slack workspace administrators control whether the Claude app can be installed in the workspace. Individual users then authenticate with their own Claude accounts to use the integration.146Claude is not automatically added to any channels after installation. Users must explicitly invite Claude to channels where they want to use it:

147 

148* **Invite required**: Type `/invite @Claude` in any channel to add Claude to that channel

149* **Channel membership controls access**: Claude can only respond to @mentions in channels where it has been added

150* **Access gating through channels**: Admins can control who uses Claude Code by managing which channels Claude is invited to and who has access to those channels

151* **Private channel support**: Claude works in both public and private channels, giving teams flexibility in controlling visibility

152 

153This channel-based model allows teams to restrict Claude Code usage to specific channels, providing an additional layer of access control beyond workspace-level permissions.

129 154 

130## What's accessible where155## What's accessible where

131 156 


133 158 

134**On the web**: The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests.159**On the web**: The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests.

135 160 

161For Enterprise and Teams accounts, sessions created from Claude in Slack are

162automatically visible to the organization. See [Claude Code on the Web sharing](/en/claude-code-on-the-web#sharing-sessions)

163for more details.

164 

136## Best practices165## Best practices

137 166 

138### Writing effective requests167### Writing effective requests


204 Get additional support233 Get additional support

205 </Card>234 </Card>

206</CardGroup>235</CardGroup>

207 

208 

209 

210> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

statusline.md +815 −166

Details

1# Status line configuration1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Create a custom status line for Claude Code to display contextual information5# Customize your status line

4 6 

5Make Claude Code your own with a custom status line that displays at the bottom of the Claude Code interface, similar to how terminal prompts (PS1) work in shells like Oh-my-zsh.7> Configure a custom status bar to monitor context window usage, costs, and git status in Claude Code

6 8 

7## Create a custom status line9The status line is a customizable bar at the bottom of Claude Code that runs any shell script you configure. It receives JSON session data on stdin and displays whatever your script prints, giving you a persistent, at-a-glance view of context usage, costs, git status, or anything else you want to track.

8 10 

9You can either:11Status lines are useful when you:

10 12 

11* Run `/statusline` to ask Claude Code to help you set up a custom status line. By default, it will try to reproduce your terminal's prompt, but you can provide additional instructions about the behavior you want to Claude Code, such as `/statusline show the model name in orange`13* Want to monitor context window usage as you work

14* Need to track session costs

15* Work across multiple sessions and need to distinguish them

16* Want git branch and status always visible

12 17 

13* Directly add a `statusLine` command to your `.claude/settings.json`:18Here's an example of a [multi-line status line](#display-multiple-lines) that displays git info on the first line and a color-coded context bar on the second.

19 

20<Frame>

21 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="A multi-line status line showing model name, directory, git branch on the first line, and a context usage progress bar with cost and duration on the second line" width="776" height="212" data-path="images/statusline-multiline.png" />

22</Frame>

23 

24This page walks through [setting up a basic status line](#set-up-a-status-line), explains [how the data flows](#how-status-lines-work) from Claude Code to your script, lists [all the fields you can display](#available-data), and provides [ready-to-use examples](#examples) for common patterns like git status, cost tracking, and progress bars.

25 

26## Set up a status line

27 

28Use the [`/statusline` command](#use-the-statusline-command) to have Claude Code generate a script for you, or [manually create a script](#manually-configure-a-status-line) and add it to your settings.

29 

30### Use the /statusline command

31 

32The `/statusline` command accepts natural language instructions describing what you want displayed. Claude Code generates a script file in `~/.claude/` and updates your settings automatically:

33 

34```text theme={null}

35/statusline show model name and context percentage with a progress bar

36```

37 

38### Manually configure a status line

39 

40Add a `statusLine` field to your user settings (`~/.claude/settings.json`, where `~` is your home directory) or [project settings](/en/settings#settings-files). Set `type` to `"command"` and point `command` to a script path or an inline shell command. For a full walkthrough of creating a script, see [Build a status line step by step](#build-a-status-line-step-by-step).

14 41 

15```json theme={null}42```json theme={null}

16{43{

17 "statusLine": {44 "statusLine": {

18 "type": "command",45 "type": "command",

19 "command": "~/.claude/statusline.sh",46 "command": "~/.claude/statusline.sh",

20 "padding": 0 // Optional: set to 0 to let status line go to edge47 "padding": 2

48 }

49}

50```

51 

52The `command` field runs in a shell, so you can also use inline commands instead of a script file. This example uses `jq` to parse the JSON input and display the model name and context percentage:

53 

54```json theme={null}

55{

56 "statusLine": {

57 "type": "command",

58 "command": "jq -r '\"[\\(.model.display_name)] \\(.context_window.used_percentage // 0)% context\"'"

21 }59 }

22}60}

23```61```

24 62 

25## How it Works63The optional `padding` field adds extra horizontal spacing (in characters) to the status line content. Defaults to `0`. This padding is in addition to the interface's built-in spacing, so it controls relative indentation rather than absolute distance from the terminal edge.

26 64 

27* The status line is updated when the conversation messages update65### Disable the status line

28* Updates run at most every 300 ms

29* The first line of stdout from your command becomes the status line text

30* ANSI color codes are supported for styling your status line

31* Claude Code passes contextual information about the current session (model, directories, etc.) as JSON to your script via stdin

32 66 

33## JSON Input Structure67Run `/statusline` and ask it to remove or clear your status line (e.g., `/statusline delete`, `/statusline clear`, `/statusline remove it`). You can also manually delete the `statusLine` field from your settings.json.

34 68 

35Your status line command receives structured data via stdin in JSON format:69## Build a status line step by step

36 70 

37```json theme={null}71This walkthrough shows what's happening under the hood by manually creating a status line that displays the current model, working directory, and context window usage percentage.

38{72 

39 "hook_event_name": "Status",73<Note>Running [`/statusline`](#use-the-statusline-command) with a description of what you want configures all of this for you automatically.</Note>

40 "session_id": "abc123...",74 

41 "transcript_path": "/path/to/transcript.json",75These examples use Bash scripts, which work on macOS and Linux. On Windows, see [Windows configuration](#windows-configuration) for PowerShell and Git Bash examples.

76 

77<Frame>

78 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=696445e59ca0059213250651ad23db6b" alt="A status line showing model name, directory, and context percentage" width="726" height="164" data-path="images/statusline-quickstart.png" />

79</Frame>

80 

81<Steps>

82 <Step title="Create a script that reads JSON and prints output">

83 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.github.io/jq/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.

84 

85 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):

86 

87 ```bash theme={null}

88 #!/bin/bash

89 # Read JSON data that Claude Code sends to stdin

90 input=$(cat)

91 

92 # Extract fields using jq

93 MODEL=$(echo "$input" | jq -r '.model.display_name')

94 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

95 # The "// 0" provides a fallback if the field is null

96 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

97 

98 # Output the status line - ${DIR##*/} extracts just the folder name

99 echo "[$MODEL] 📁 ${DIR##*/} | ${PCT}% context"

100 ```

101 </Step>

102 

103 <Step title="Make it executable">

104 Mark the script as executable so your shell can run it:

105 

106 ```bash theme={null}

107 chmod +x ~/.claude/statusline.sh

108 ```

109 </Step>

110 

111 <Step title="Add to settings">

112 Tell Claude Code to run your script as the status line. Add this configuration to `~/.claude/settings.json`, which sets `type` to `"command"` (meaning "run this shell command") and points `command` to your script:

113 

114 ```json theme={null}

115 {

116 "statusLine": {

117 "type": "command",

118 "command": "~/.claude/statusline.sh"

119 }

120 }

121 ```

122 

123 Your status line appears at the bottom of the interface. Settings reload automatically, but changes won't appear until your next interaction with Claude Code.

124 </Step>

125</Steps>

126 

127## How status lines work

128 

129Claude Code runs your script and pipes [JSON session data](#available-data) to it via stdin. Your script reads the JSON, extracts what it needs, and prints text to stdout. Claude Code displays whatever your script prints.

130 

131**When it updates**

132 

133Your script runs after each new assistant message, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won't appear until your next interaction with Claude Code triggers an update.

134 

135**What your script can output**

136 

137* **Multiple lines**: each `echo` or `print` statement displays as a separate row. See the [multi-line example](#display-multiple-lines).

138* **Colors**: use [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) like `\033[32m` for green (terminal must support them). See the [git status example](#git-status-with-colors).

139* **Links**: use [OSC 8 escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code#OSC) to make text clickable (Cmd+click on macOS, Ctrl+click on Windows/Linux). Requires a terminal that supports hyperlinks like iTerm2, Kitty, or WezTerm. See the [clickable links example](#clickable-links).

140 

141<Note>The status line runs locally and does not consume API tokens. It temporarily hides during certain UI interactions, including autocomplete suggestions, the help menu, and permission prompts.</Note>

142 

143## Available data

144 

145Claude Code sends the following JSON fields to your script via stdin:

146 

147| Field | Description |

148| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

149| `model.id`, `model.display_name` | Current model identifier and display name |

150| `cwd`, `workspace.current_dir` | Current working directory. Both fields contain the same value; `workspace.current_dir` is preferred for consistency with `workspace.project_dir`. |

151| `workspace.project_dir` | Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session |

152| `cost.total_cost_usd` | Total session cost in USD |

153| `cost.total_duration_ms` | Total wall-clock time since the session started, in milliseconds |

154| `cost.total_api_duration_ms` | Total time spent waiting for API responses in milliseconds |

155| `cost.total_lines_added`, `cost.total_lines_removed` | Lines of code changed |

156| `context_window.total_input_tokens`, `context_window.total_output_tokens` | Cumulative token counts across the session |

157| `context_window.context_window_size` | Maximum context window size in tokens. 200000 by default, or 1000000 for models with extended context. |

158| `context_window.used_percentage` | Pre-calculated percentage of context window used |

159| `context_window.remaining_percentage` | Pre-calculated percentage of context window remaining |

160| `context_window.current_usage` | Token counts from the last API call, described in [context window fields](#context-window-fields) |

161| `exceeds_200k_tokens` | Whether the total token count (input, cache, and output tokens combined) from the most recent API response exceeds 200k. This is a fixed threshold regardless of actual context window size. |

162| `session_id` | Unique session identifier |

163| `transcript_path` | Path to conversation transcript file |

164| `version` | Claude Code version |

165| `output_style.name` | Name of the current output style |

166| `vim.mode` | Current vim mode (`NORMAL` or `INSERT`) when [vim mode](/en/interactive-mode#vim-editor-mode) is enabled |

167| `agent.name` | Agent name when running with the `--agent` flag or agent settings configured |

168| `worktree.name` | Name of the active worktree. Present only during `--worktree` sessions |

169| `worktree.path` | Absolute path to the worktree directory |

170| `worktree.branch` | Git branch name for the worktree (for example, `"worktree-my-feature"`). Absent for hook-based worktrees |

171| `worktree.original_cwd` | The directory Claude was in before entering the worktree |

172| `worktree.original_branch` | Git branch checked out before entering the worktree. Absent for hook-based worktrees |

173 

174<Accordion title="Full JSON schema">

175 Your status line command receives this JSON structure via stdin:

176 

177 ```json theme={null}

178 {

42 "cwd": "/current/working/directory",179 "cwd": "/current/working/directory",

180 "session_id": "abc123...",

181 "transcript_path": "/path/to/transcript.jsonl",

43 "model": {182 "model": {

44 "id": "claude-opus-4-1",183 "id": "claude-opus-4-6",

45 "display_name": "Opus"184 "display_name": "Opus"

46 },185 },

47 "workspace": {186 "workspace": {


63 "total_input_tokens": 15234,202 "total_input_tokens": 15234,

64 "total_output_tokens": 4521,203 "total_output_tokens": 4521,

65 "context_window_size": 200000,204 "context_window_size": 200000,

66 "used_percentage": 42.5,205 "used_percentage": 8,

67 "remaining_percentage": 57.5,206 "remaining_percentage": 92,

68 "current_usage": {207 "current_usage": {

69 "input_tokens": 8500,208 "input_tokens": 8500,

70 "output_tokens": 1200,209 "output_tokens": 1200,

71 "cache_creation_input_tokens": 5000,210 "cache_creation_input_tokens": 5000,

72 "cache_read_input_tokens": 2000211 "cache_read_input_tokens": 2000

73 }212 }

213 },

214 "exceeds_200k_tokens": false,

215 "vim": {

216 "mode": "NORMAL"

217 },

218 "agent": {

219 "name": "security-reviewer"

220 },

221 "worktree": {

222 "name": "my-feature",

223 "path": "/path/to/.claude/worktrees/my-feature",

224 "branch": "worktree-my-feature",

225 "original_cwd": "/path/to/project",

226 "original_branch": "main"

74 }227 }

75}228 }

76```229 ```

77 230 

78## Example Scripts231 **Fields that may be absent** (not present in JSON):

79 232 

80### Simple Status Line233 * `vim`: appears only when vim mode is enabled

234 * `agent`: appears only when running with the `--agent` flag or agent settings configured

235 * `worktree`: appears only during `--worktree` sessions. When present, `branch` and `original_branch` may also be absent for hook-based worktrees

81 236 

82```bash theme={null}237 **Fields that may be `null`**:

83#!/bin/bash

84# Read JSON input from stdin

85input=$(cat)

86 238 

87# Extract values using jq239 * `context_window.current_usage`: `null` before the first API call in a session

88MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')240 * `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session

89CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

90 241 

91echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}"242 Handle missing fields with conditional access and null values with fallback defaults in your scripts.

92```243</Accordion>

244 

245### Context window fields

246 

247The `context_window` object provides two ways to track context usage:

248 

249* **Cumulative totals** (`total_input_tokens`, `total_output_tokens`): sum of all tokens across the entire session, useful for tracking total consumption

250* **Current usage** (`current_usage`): token counts from the most recent API call, use this for accurate context percentage since it reflects the actual context state

251 

252The `current_usage` object contains:

253 

254* `input_tokens`: input tokens in current context

255* `output_tokens`: output tokens generated

256* `cache_creation_input_tokens`: tokens written to cache

257* `cache_read_input_tokens`: tokens read from cache

93 258 

94### Git-Aware Status Line259The `used_percentage` field is calculated from input tokens only: `input_tokens + cache_creation_input_tokens + cache_read_input_tokens`. It does not include `output_tokens`.

95 260 

96```bash theme={null}261If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.

97#!/bin/bash

98# Read JSON input from stdin

99input=$(cat)

100 262 

101# Extract values using jq263The `current_usage` object is `null` before the first API call in a session.

102MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')

103CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

104 264 

105# Show git branch if in a git repo265## Examples

106GIT_BRANCH=""266 

107if git rev-parse --git-dir > /dev/null 2>&1; then267These examples show common status line patterns. To use any example:

268 

2691. Save the script to a file like `~/.claude/statusline.sh` (or `.py`/`.js`)

2702. Make it executable: `chmod +x ~/.claude/statusline.sh`

2713. Add the path to your [settings](#manually-configure-a-status-line)

272 

273The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.

274 

275### Context window usage

276 

277Display the current model and context window usage with a visual progress bar. Each script reads JSON from stdin, extracts the `used_percentage` field, and builds a 10-character bar where filled blocks (▓) represent usage:

278 

279<Frame>

280 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=15b58ab3602f036939145dde3165c6f7" alt="A status line showing model name and a progress bar with percentage" width="448" height="152" data-path="images/statusline-context-window-usage.png" />

281</Frame>

282 

283<CodeGroup>

284 ```bash Bash theme={null}

285 #!/bin/bash

286 # Read all of stdin into a variable

287 input=$(cat)

288 

289 # Extract fields with jq, "// 0" provides fallback for null

290 MODEL=$(echo "$input" | jq -r '.model.display_name')

291 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

292 

293 # Build progress bar: printf -v creates a run of spaces, then

294 # ${var// /▓} replaces each space with a block character

295 BAR_WIDTH=10

296 FILLED=$((PCT * BAR_WIDTH / 100))

297 EMPTY=$((BAR_WIDTH - FILLED))

298 BAR=""

299 [ "$FILLED" -gt 0 ] && printf -v FILL "%${FILLED}s" && BAR="${FILL// /▓}"

300 [ "$EMPTY" -gt 0 ] && printf -v PAD "%${EMPTY}s" && BAR="${BAR}${PAD// /░}"

301 

302 echo "[$MODEL] $BAR $PCT%"

303 ```

304 

305 ```python Python theme={null}

306 #!/usr/bin/env python3

307 import json, sys

308 

309 # json.load reads and parses stdin in one step

310 data = json.load(sys.stdin)

311 model = data['model']['display_name']

312 # "or 0" handles null values

313 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

314 

315 # String multiplication builds the bar

316 filled = pct * 10 // 100

317 bar = '▓' * filled + '░' * (10 - filled)

318 

319 print(f"[{model}] {bar} {pct}%")

320 ```

321 

322 ```javascript Node.js theme={null}

323 #!/usr/bin/env node

324 // Node.js reads stdin asynchronously with events

325 let input = '';

326 process.stdin.on('data', chunk => input += chunk);

327 process.stdin.on('end', () => {

328 const data = JSON.parse(input);

329 const model = data.model.display_name;

330 // Optional chaining (?.) safely handles null fields

331 const pct = Math.floor(data.context_window?.used_percentage || 0);

332 

333 // String.repeat() builds the bar

334 const filled = Math.floor(pct * 10 / 100);

335 const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);

336 

337 console.log(`[${model}] ${bar} ${pct}%`);

338 });

339 ```

340</CodeGroup>

341 

342### Git status with colors

343 

344Show git branch with color-coded indicators for staged and modified files. This script uses [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) for terminal colors: `\033[32m` is green, `\033[33m` is yellow, and `\033[0m` resets to default.

345 

346<Frame>

347 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e656f34f90d1d9a1d0e220988914345f" alt="A status line showing model, directory, git branch, and colored indicators for staged and modified files" width="742" height="178" data-path="images/statusline-git-context.png" />

348</Frame>

349 

350Each script checks if the current directory is a git repository, counts staged and modified files, and displays color-coded indicators:

351 

352<CodeGroup>

353 ```bash Bash theme={null}

354 #!/bin/bash

355 input=$(cat)

356 

357 MODEL=$(echo "$input" | jq -r '.model.display_name')

358 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

359 

360 GREEN='\033[32m'

361 YELLOW='\033[33m'

362 RESET='\033[0m'

363 

364 if git rev-parse --git-dir > /dev/null 2>&1; then

108 BRANCH=$(git branch --show-current 2>/dev/null)365 BRANCH=$(git branch --show-current 2>/dev/null)

109 if [ -n "$BRANCH" ]; then366 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

110 GIT_BRANCH=" | 🌿 $BRANCH"367 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

111 fi

112fi

113 368 

114echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH"369 GIT_STATUS=""

115```370 [ "$STAGED" -gt 0 ] && GIT_STATUS="${GREEN}+${STAGED}${RESET}"

371 [ "$MODIFIED" -gt 0 ] && GIT_STATUS="${GIT_STATUS}${YELLOW}~${MODIFIED}${RESET}"

116 372 

117### Python Example373 echo -e "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH $GIT_STATUS"

374 else

375 echo "[$MODEL] 📁 ${DIR##*/}"

376 fi

377 ```

118 378 

119```python theme={null}379 ```python Python theme={null}

120#!/usr/bin/env python3380 #!/usr/bin/env python3

121import json381 import json, sys, subprocess, os

122import sys

123import os

124 382 

125# Read JSON from stdin383 data = json.load(sys.stdin)

126data = json.load(sys.stdin)384 model = data['model']['display_name']

385 directory = os.path.basename(data['workspace']['current_dir'])

127 386 

128# Extract values387 GREEN, YELLOW, RESET = '\033[32m', '\033[33m', '\033[0m'

129model = data['model']['display_name']

130current_dir = os.path.basename(data['workspace']['current_dir'])

131 388 

132# Check for git branch

133git_branch = ""

134if os.path.exists('.git'):

135 try:389 try:

136 with open('.git/HEAD', 'r') as f:390 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

137 ref = f.read().strip()391 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

138 if ref.startswith('ref: refs/heads/'):392 staged_output = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

139 git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}"393 modified_output = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

394 staged = len(staged_output.split('\n')) if staged_output else 0

395 modified = len(modified_output.split('\n')) if modified_output else 0

396 

397 git_status = f"{GREEN}+{staged}{RESET}" if staged else ""

398 git_status += f"{YELLOW}~{modified}{RESET}" if modified else ""

399 

400 print(f"[{model}] 📁 {directory} | 🌿 {branch} {git_status}")

140 except:401 except:

141 pass402 print(f"[{model}] 📁 {directory}")

403 ```

142 404 

143print(f"[{model}] 📁 {current_dir}{git_branch}")405 ```javascript Node.js theme={null}

144```406 #!/usr/bin/env node

407 const { execSync } = require('child_process');

408 const path = require('path');

409 

410 let input = '';

411 process.stdin.on('data', chunk => input += chunk);

412 process.stdin.on('end', () => {

413 const data = JSON.parse(input);

414 const model = data.model.display_name;

415 const dir = path.basename(data.workspace.current_dir);

416 

417 const GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RESET = '\x1b[0m';

418 

419 try {

420 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

421 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

422 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

423 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

424 

425 let gitStatus = staged ? `${GREEN}+${staged}${RESET}` : '';

426 gitStatus += modified ? `${YELLOW}~${modified}${RESET}` : '';

427 

428 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} ${gitStatus}`);

429 } catch {

430 console.log(`[${model}] 📁 ${dir}`);

431 }

432 });

433 ```

434</CodeGroup>

435 

436### Cost and duration tracking

437 

438Track your session's API costs and elapsed time. The `cost.total_cost_usd` field accumulates the cost of all API calls in the current session. The `cost.total_duration_ms` field measures total elapsed time since the session started, while `cost.total_api_duration_ms` tracks only the time spent waiting for API responses.

439 

440Each script formats cost as currency and converts milliseconds to minutes and seconds:

441 

442<Frame>

443 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e3444a51fe6f3440c134bd5f1f08ad29" alt="A status line showing model name, session cost, and duration" width="588" height="180" data-path="images/statusline-cost-tracking.png" />

444</Frame>

445 

446<CodeGroup>

447 ```bash Bash theme={null}

448 #!/bin/bash

449 input=$(cat)

450 

451 MODEL=$(echo "$input" | jq -r '.model.display_name')

452 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

453 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

454 

455 COST_FMT=$(printf '$%.2f' "$COST")

456 DURATION_SEC=$((DURATION_MS / 1000))

457 MINS=$((DURATION_SEC / 60))

458 SECS=$((DURATION_SEC % 60))

145 459 

146### Node.js Example460 echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"

461 ```

147 462 

148```javascript theme={null}463 ```python Python theme={null}

149#!/usr/bin/env node464 #!/usr/bin/env python3

465 import json, sys

150 466 

151const fs = require('fs');467 data = json.load(sys.stdin)

152const path = require('path');468 model = data['model']['display_name']

469 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

470 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

153 471 

154// Read JSON from stdin472 duration_sec = duration_ms // 1000

155let input = '';473 mins, secs = duration_sec // 60, duration_sec % 60

156process.stdin.on('data', chunk => input += chunk);474 

157process.stdin.on('end', () => {475 print(f"[{model}] 💰 ${cost:.2f} | ⏱️ {mins}m {secs}s")

476 ```

477 

478 ```javascript Node.js theme={null}

479 #!/usr/bin/env node

480 let input = '';

481 process.stdin.on('data', chunk => input += chunk);

482 process.stdin.on('end', () => {

158 const data = JSON.parse(input);483 const data = JSON.parse(input);

484 const model = data.model.display_name;

485 const cost = data.cost?.total_cost_usd || 0;

486 const durationMs = data.cost?.total_duration_ms || 0;

487 

488 const durationSec = Math.floor(durationMs / 1000);

489 const mins = Math.floor(durationSec / 60);

490 const secs = durationSec % 60;

491 

492 console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`);

493 });

494 ```

495</CodeGroup>

496 

497### Display multiple lines

498 

499Your script can output multiple lines to create a richer display. Each `echo` statement produces a separate row in the status area.

500 

501<Frame>

502 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="A multi-line status line showing model name, directory, git branch on the first line, and a context usage progress bar with cost and duration on the second line" width="776" height="212" data-path="images/statusline-multiline.png" />

503</Frame>

504 

505This example combines several techniques: threshold-based colors (green under 70%, yellow 70-89%, red 90%+), a progress bar, and git branch info. Each `print` or `echo` statement creates a separate row:

506 

507<CodeGroup>

508 ```bash Bash theme={null}

509 #!/bin/bash

510 input=$(cat)

511 

512 MODEL=$(echo "$input" | jq -r '.model.display_name')

513 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

514 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

515 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

516 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

517 

518 CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

519 

520 # Pick bar color based on context usage

521 if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"

522 elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"

523 else BAR_COLOR="$GREEN"; fi

524 

525 FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))

526 printf -v FILL "%${FILLED}s"; printf -v PAD "%${EMPTY}s"

527 BAR="${FILL// /█}${PAD// /░}"

528 

529 MINS=$((DURATION_MS / 60000)); SECS=$(((DURATION_MS % 60000) / 1000))

530 

531 BRANCH=""

532 git rev-parse --git-dir > /dev/null 2>&1 && BRANCH=" | 🌿 $(git branch --show-current 2>/dev/null)"

533 

534 echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"

535 COST_FMT=$(printf '$%.2f' "$COST")

536 echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"

537 ```

538 

539 ```python Python theme={null}

540 #!/usr/bin/env python3

541 import json, sys, subprocess, os

542 

543 data = json.load(sys.stdin)

544 model = data['model']['display_name']

545 directory = os.path.basename(data['workspace']['current_dir'])

546 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

547 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

548 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

549 

550 CYAN, GREEN, YELLOW, RED, RESET = '\033[36m', '\033[32m', '\033[33m', '\033[31m', '\033[0m'

551 

552 bar_color = RED if pct >= 90 else YELLOW if pct >= 70 else GREEN

553 filled = pct // 10

554 bar = '█' * filled + '░' * (10 - filled)

555 

556 mins, secs = duration_ms // 60000, (duration_ms % 60000) // 1000

557 

558 try:

559 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True, stderr=subprocess.DEVNULL).strip()

560 branch = f" | 🌿 {branch}" if branch else ""

561 except:

562 branch = ""

563 

564 print(f"{CYAN}[{model}]{RESET} 📁 {directory}{branch}")

565 print(f"{bar_color}{bar}{RESET} {pct}% | {YELLOW}${cost:.2f}{RESET} | ⏱️ {mins}m {secs}s")

566 ```

159 567 

160 // Extract values568 ```javascript Node.js theme={null}

569 #!/usr/bin/env node

570 const { execSync } = require('child_process');

571 const path = require('path');

572 

573 let input = '';

574 process.stdin.on('data', chunk => input += chunk);

575 process.stdin.on('end', () => {

576 const data = JSON.parse(input);

161 const model = data.model.display_name;577 const model = data.model.display_name;

162 const currentDir = path.basename(data.workspace.current_dir);578 const dir = path.basename(data.workspace.current_dir);

579 const cost = data.cost?.total_cost_usd || 0;

580 const pct = Math.floor(data.context_window?.used_percentage || 0);

581 const durationMs = data.cost?.total_duration_ms || 0;

582 

583 const CYAN = '\x1b[36m', GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RED = '\x1b[31m', RESET = '\x1b[0m';

584 

585 const barColor = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;

586 const filled = Math.floor(pct / 10);

587 const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);

163 588 

164 // Check for git branch589 const mins = Math.floor(durationMs / 60000);

165 let gitBranch = '';590 const secs = Math.floor((durationMs % 60000) / 1000);

591 

592 let branch = '';

166 try {593 try {

167 const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim();594 branch = execSync('git branch --show-current', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

168 if (headContent.startsWith('ref: refs/heads/')) {595 branch = branch ? ` | 🌿 ${branch}` : '';

169 gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`;596 } catch {}

597 

598 console.log(`${CYAN}[${model}]${RESET} 📁 ${dir}${branch}`);

599 console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`);

600 });

601 ```

602</CodeGroup>

603 

604### Clickable links

605 

606This example creates a clickable link to your GitHub repository. It reads the git remote URL, converts SSH format to HTTPS with `sed`, and wraps the repo name in OSC 8 escape codes. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser.

607 

608<Frame>

609 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=4bcc6e7deb7cf52f41ab85a219b52661" alt="A status line showing a clickable link to a GitHub repository" width="726" height="198" data-path="images/statusline-links.png" />

610</Frame>

611 

612Each script gets the git remote URL, converts SSH format to HTTPS, and wraps the repo name in OSC 8 escape codes. The Bash version uses `printf '%b'` which interprets backslash escapes more reliably than `echo -e` across different shells:

613 

614<CodeGroup>

615 ```bash Bash theme={null}

616 #!/bin/bash

617 input=$(cat)

618 

619 MODEL=$(echo "$input" | jq -r '.model.display_name')

620 

621 # Convert git SSH URL to HTTPS

622 REMOTE=$(git remote get-url origin 2>/dev/null | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//')

623 

624 if [ -n "$REMOTE" ]; then

625 REPO_NAME=$(basename "$REMOTE")

626 # OSC 8 format: \e]8;;URL\a then TEXT then \e]8;;\a

627 # printf %b interprets escape sequences reliably across shells

628 printf '%b' "[$MODEL] 🔗 \e]8;;${REMOTE}\a${REPO_NAME}\e]8;;\a\n"

629 else

630 echo "[$MODEL]"

631 fi

632 ```

633 

634 ```python Python theme={null}

635 #!/usr/bin/env python3

636 import json, sys, subprocess, re, os

637 

638 data = json.load(sys.stdin)

639 model = data['model']['display_name']

640 

641 # Get git remote URL

642 try:

643 remote = subprocess.check_output(

644 ['git', 'remote', 'get-url', 'origin'],

645 stderr=subprocess.DEVNULL, text=True

646 ).strip()

647 # Convert SSH to HTTPS format

648 remote = re.sub(r'^git@github\.com:', 'https://github.com/', remote)

649 remote = re.sub(r'\.git$', '', remote)

650 repo_name = os.path.basename(remote)

651 # OSC 8 escape sequences

652 link = f"\033]8;;{remote}\a{repo_name}\033]8;;\a"

653 print(f"[{model}] 🔗 {link}")

654 except:

655 print(f"[{model}]")

656 ```

657 

658 ```javascript Node.js theme={null}

659 #!/usr/bin/env node

660 const { execSync } = require('child_process');

661 const path = require('path');

662 

663 let input = '';

664 process.stdin.on('data', chunk => input += chunk);

665 process.stdin.on('end', () => {

666 const data = JSON.parse(input);

667 const model = data.model.display_name;

668 

669 try {

670 let remote = execSync('git remote get-url origin', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

671 // Convert SSH to HTTPS format

672 remote = remote.replace(/^git@github\.com:/, 'https://github.com/').replace(/\.git$/, '');

673 const repoName = path.basename(remote);

674 // OSC 8 escape sequences

675 const link = `\x1b]8;;${remote}\x07${repoName}\x1b]8;;\x07`;

676 console.log(`[${model}] 🔗 ${link}`);

677 } catch {

678 console.log(`[${model}]`);

170 }679 }

171 } catch (e) {680 });

172 // Not a git repo or can't read HEAD681 ```

682</CodeGroup>

683 

684### Cache expensive operations

685 

686Your status line script runs frequently during active sessions. Commands like `git status` or `git diff` can be slow, especially in large repositories. This example caches git information to a temp file and only refreshes it every 5 seconds.

687 

688Use a stable, fixed filename for the cache file like `/tmp/statusline-git-cache`. Each status line invocation runs as a new process, so process-based identifiers like `$$`, `os.getpid()`, or `process.pid` produce a different value every time and the cache is never reused.

689 

690Each script checks if the cache file is missing or older than 5 seconds before running git commands:

691 

692<CodeGroup>

693 ```bash Bash theme={null}

694 #!/bin/bash

695 input=$(cat)

696 

697 MODEL=$(echo "$input" | jq -r '.model.display_name')

698 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

699 

700 CACHE_FILE="/tmp/statusline-git-cache"

701 CACHE_MAX_AGE=5 # seconds

702 

703 cache_is_stale() {

704 [ ! -f "$CACHE_FILE" ] || \

705 # stat -f %m is macOS, stat -c %Y is Linux

706 [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0))) -gt $CACHE_MAX_AGE ]

173 }707 }

174 708 

175 console.log(`[${model}] 📁 ${currentDir}${gitBranch}`);709 if cache_is_stale; then

176});710 if git rev-parse --git-dir > /dev/null 2>&1; then

177```711 BRANCH=$(git branch --show-current 2>/dev/null)

712 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

713 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

714 echo "$BRANCH|$STAGED|$MODIFIED" > "$CACHE_FILE"

715 else

716 echo "||" > "$CACHE_FILE"

717 fi

718 fi

178 719 

179### Helper Function Approach720 IFS='|' read -r BRANCH STAGED MODIFIED < "$CACHE_FILE"

180 721 

181For more complex bash scripts, you can create helper functions:722 if [ -n "$BRANCH" ]; then

182 723 echo "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH +$STAGED ~$MODIFIED"

183```bash theme={null}724 else

184#!/bin/bash725 echo "[$MODEL] 📁 ${DIR##*/}"

185# Read JSON input once726 fi

186input=$(cat)727 ```

187 

188# Helper functions for common extractions

189get_model_name() { echo "$input" | jq -r '.model.display_name'; }

190get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; }

191get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; }

192get_version() { echo "$input" | jq -r '.version'; }

193get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; }

194get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; }

195get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; }

196get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; }

197get_input_tokens() { echo "$input" | jq -r '.context_window.total_input_tokens'; }

198get_output_tokens() { echo "$input" | jq -r '.context_window.total_output_tokens'; }

199get_context_window_size() { echo "$input" | jq -r '.context_window.context_window_size'; }

200 

201# Use the helpers

202MODEL=$(get_model_name)

203DIR=$(get_current_dir)

204echo "[$MODEL] 📁 ${DIR##*/}"

205```

206 728 

207### Context Window Usage729 ```python Python theme={null}

730 #!/usr/bin/env python3

731 import json, sys, subprocess, os, time

208 732 

209Display the percentage of context window consumed. The `context_window` object contains:733 data = json.load(sys.stdin)

734 model = data['model']['display_name']

735 directory = os.path.basename(data['workspace']['current_dir'])

210 736 

211* `total_input_tokens` / `total_output_tokens`: Cumulative totals across the entire session737 CACHE_FILE = "/tmp/statusline-git-cache"

212* `used_percentage`: Pre-calculated percentage of context window used (0-100)738 CACHE_MAX_AGE = 5 # seconds

213* `remaining_percentage`: Pre-calculated percentage of context window remaining (0-100)

214* `current_usage`: Current context window usage from the last API call (may be `null` if no messages yet)

215 * `input_tokens`: Input tokens in current context

216 * `output_tokens`: Output tokens generated

217 * `cache_creation_input_tokens`: Tokens written to cache

218 * `cache_read_input_tokens`: Tokens read from cache

219 739 

220You can use the pre-calculated `used_percentage` and `remaining_percentage` fields directly, or calculate from `current_usage` for more control.740 def cache_is_stale():

741 if not os.path.exists(CACHE_FILE):

742 return True

743 return time.time() - os.path.getmtime(CACHE_FILE) > CACHE_MAX_AGE

221 744 

222**Simple approach using pre-calculated percentages:**745 if cache_is_stale():

746 try:

747 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

748 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

749 staged = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

750 modified = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

751 staged_count = len(staged.split('\n')) if staged else 0

752 modified_count = len(modified.split('\n')) if modified else 0

753 with open(CACHE_FILE, 'w') as f:

754 f.write(f"{branch}|{staged_count}|{modified_count}")

755 except:

756 with open(CACHE_FILE, 'w') as f:

757 f.write("||")

758 

759 with open(CACHE_FILE) as f:

760 branch, staged, modified = f.read().strip().split('|')

761 

762 if branch:

763 print(f"[{model}] 📁 {directory} | 🌿 {branch} +{staged} ~{modified}")

764 else:

765 print(f"[{model}] 📁 {directory}")

766 ```

767 

768 ```javascript Node.js theme={null}

769 #!/usr/bin/env node

770 const { execSync } = require('child_process');

771 const fs = require('fs');

772 const path = require('path');

773 

774 let input = '';

775 process.stdin.on('data', chunk => input += chunk);

776 process.stdin.on('end', () => {

777 const data = JSON.parse(input);

778 const model = data.model.display_name;

779 const dir = path.basename(data.workspace.current_dir);

223 780 

224```bash theme={null}781 const CACHE_FILE = '/tmp/statusline-git-cache';

225#!/bin/bash782 const CACHE_MAX_AGE = 5; // seconds

226input=$(cat)

227 783 

228MODEL=$(echo "$input" | jq -r '.model.display_name')784 const cacheIsStale = () => {

229PERCENT_USED=$(echo "$input" | jq -r '.context_window.used_percentage // 0')785 if (!fs.existsSync(CACHE_FILE)) return true;

786 return (Date.now() / 1000) - fs.statSync(CACHE_FILE).mtimeMs / 1000 > CACHE_MAX_AGE;

787 };

230 788 

231echo "[$MODEL] Context: ${PERCENT_USED}%"789 if (cacheIsStale()) {

232```790 try {

791 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

792 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

793 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

794 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

795 fs.writeFileSync(CACHE_FILE, `${branch}|${staged}|${modified}`);

796 } catch {

797 fs.writeFileSync(CACHE_FILE, '||');

798 }

799 }

233 800 

234**Advanced approach with manual calculation:**801 const [branch, staged, modified] = fs.readFileSync(CACHE_FILE, 'utf8').trim().split('|');

235 802 

236```bash theme={null}803 if (branch) {

237#!/bin/bash804 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} +${staged} ~${modified}`);

238input=$(cat)805 } else {

806 console.log(`[${model}] 📁 ${dir}`);

807 }

808 });

809 ```

810</CodeGroup>

239 811 

240MODEL=$(echo "$input" | jq -r '.model.display_name')812### Windows configuration

241CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size')

242USAGE=$(echo "$input" | jq '.context_window.current_usage')

243 813 

244if [ "$USAGE" != "null" ]; then814On Windows, Claude Code runs status line commands through Git Bash. You can invoke PowerShell from that shell:

245 # Calculate current context from current_usage fields815 

246 CURRENT_TOKENS=$(echo "$USAGE" | jq '.input_tokens + .cache_creation_input_tokens + .cache_read_input_tokens')816<CodeGroup>

247 PERCENT_USED=$((CURRENT_TOKENS * 100 / CONTEXT_SIZE))817 ```json settings.json theme={null}

248 echo "[$MODEL] Context: ${PERCENT_USED}%"818 {

249else819 "statusLine": {

250 echo "[$MODEL] Context: 0%"820 "type": "command",

251fi821 "command": "powershell -NoProfile -File C:/Users/username/.claude/statusline.ps1"

252```822 }

823 }

824 ```

825 

826 ```powershell statusline.ps1 theme={null}

827 $input_json = $input | Out-String | ConvertFrom-Json

828 $cwd = $input_json.cwd

829 $model = $input_json.model.display_name

830 $used = $input_json.context_window.used_percentage

831 $dirname = Split-Path $cwd -Leaf

832 

833 if ($used) {

834 Write-Host "$dirname [$model] ctx: $used%"

835 } else {

836 Write-Host "$dirname [$model]"

837 }

838 ```

839</CodeGroup>

840 

841Or run a Bash script directly:

842 

843<CodeGroup>

844 ```json settings.json theme={null}

845 {

846 "statusLine": {

847 "type": "command",

848 "command": "~/.claude/statusline.sh"

849 }

850 }

851 ```

852 

853 ```bash statusline.sh theme={null}

854 #!/usr/bin/env bash

855 input=$(cat)

856 cwd=$(echo "$input" | grep -o '"cwd":"[^"]*"' | cut -d'"' -f4)

857 model=$(echo "$input" | grep -o '"display_name":"[^"]*"' | cut -d'"' -f4)

858 dirname="${cwd##*[/\\]}"

859 echo "$dirname [$model]"

860 ```

861</CodeGroup>

253 862 

254## Tips863## Tips

255 864 

256* Keep your status line concise - it should fit on one line865* **Test with mock input**: `echo '{"model":{"display_name":"Opus"},"context_window":{"used_percentage":25}}' | ./statusline.sh`

257* Use emojis (if your terminal supports them) and colors to make information scannable866* **Keep output short**: the status bar has limited width, so long output may get truncated or wrap awkwardly

258* Use `jq` for JSON parsing in Bash (see examples above)867* **Cache slow operations**: your script runs frequently during active sessions, so commands like `git status` can cause lag. See the [caching example](#cache-expensive-operations) for how to handle this.

259* Test your script by running it manually with mock JSON input: `echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/test"}}' | ./statusline.sh`868 

260* Consider caching expensive operations (like git status) if needed869Community projects like [ccstatusline](https://github.com/sirmalloc/ccstatusline) and [starship-claude](https://github.com/martinemde/starship-claude) provide pre-built configurations with themes and additional features.

261 870 

262## Troubleshooting871## Troubleshooting

263 872 

264* If your status line doesn't appear, check that your script is executable (`chmod +x`)873**Status line not appearing**

265* Ensure your script outputs to stdout (not stderr)874 

875* Verify your script is executable: `chmod +x ~/.claude/statusline.sh`

876* Check that your script outputs to stdout, not stderr

877* Run your script manually to verify it produces output

878* If `disableAllHooks` is set to `true` in your settings, the status line is also disabled. Remove this setting or set it to `false` to re-enable.

879* Run `claude --debug` to log the exit code and stderr from the first status line invocation in a session

880* Ask Claude to read your settings file and execute the `statusLine` command directly to surface errors

881 

882**Status line shows `--` or empty values**

883 

884* Fields may be `null` before the first API response completes

885* Handle null values in your script with fallbacks such as `// 0` in jq

886* Restart Claude Code if values remain empty after multiple messages

887 

888**Context percentage shows unexpected values**

889 

890* Use `used_percentage` for accurate context state rather than cumulative totals

891* The `total_input_tokens` and `total_output_tokens` are cumulative across the session and may exceed the context window size

892* Context percentage may differ from `/context` output due to when each is calculated

893 

894**OSC 8 links not clickable**

895 

896* Verify your terminal supports OSC 8 hyperlinks (iTerm2, Kitty, WezTerm)

897* Terminal.app does not support clickable links

898* SSH and tmux sessions may strip OSC sequences depending on configuration

899* If escape sequences appear as literal text like `\e]8;;`, use `printf '%b'` instead of `echo -e` for more reliable escape handling

900 

901**Display glitches with escape sequences**

902 

903* Complex escape sequences (ANSI colors, OSC 8 links) can occasionally cause garbled output if they overlap with other UI updates

904* If you see corrupted text, try simplifying your script to plain text output

905* Multi-line status lines with escape codes are more prone to rendering issues than single-line plain text

906 

907**Script errors or hangs**

266 908 

909* Scripts that exit with non-zero codes or produce no output cause the status line to go blank

910* Slow scripts block the status line from updating until they complete. Keep scripts fast to avoid stale output.

911* If a new update triggers while a slow script is running, the in-flight script is cancelled

912* Test your script independently with mock input before configuring it

267 913 

914**Notifications share the status line row**

268 915 

269> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt916* System notifications like MCP server errors, auto-updates, and token warnings display on the right side of the same row as your status line

917* Enabling verbose mode adds a token counter to this area

918* On narrow terminals, these notifications may truncate your status line output

sub-agents.md +153 −34

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Create custom subagents5# Create custom subagents

2 6 

3> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.7> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.

4 8 

5Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results.9Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results.

6 10 

11<Note>

12 If you need multiple agents working in parallel and communicating with each other, see [agent teams](/en/agent-teams) instead. Subagents work within a single session; agent teams coordinate across separate sessions.

13</Note>

14 

7Subagents help you:15Subagents help you:

8 16 

9* **Preserve context** by keeping exploration and implementation out of your main conversation17* **Preserve context** by keeping exploration and implementation out of your main conversation


76 <Step title="Open the subagents interface">84 <Step title="Open the subagents interface">

77 In Claude Code, run:85 In Claude Code, run:

78 86 

79 ```87 ```text theme={null}

80 /agents88 /agents

81 ```89 ```

82 </Step>90 </Step>


88 <Step title="Generate with Claude">96 <Step title="Generate with Claude">

89 Select **Generate with Claude**. When prompted, describe the subagent:97 Select **Generate with Claude**. When prompted, describe the subagent:

90 98 

91 ```99 ```text theme={null}

92 A code improvement agent that scans files and suggests improvements100 A code improvement agent that scans files and suggests improvements

93 for readability, performance, and best practices. It should explain101 for readability, performance, and best practices. It should explain

94 each issue, show the current code, and provide an improved version.102 each issue, show the current code, and provide an improved version.


112 <Step title="Save and try it out">120 <Step title="Save and try it out">

113 Save the subagent. It's available immediately (no restart needed). Try it:121 Save the subagent. It's available immediately (no restart needed). Try it:

114 122 

115 ```123 ```text theme={null}

116 Use the code-improver agent to suggest improvements in this project124 Use the code-improver agent to suggest improvements in this project

117 ```125 ```

118 126 


138 146 

139This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.147This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.

140 148 

149To list all configured subagents from the command line without starting an interactive session, run `claude agents`. This shows agents grouped by source and indicates which are overridden by higher-priority definitions.

150 

141### Choose the subagent scope151### Choose the subagent scope

142 152 

143Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.153Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.


153 163 

154**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.164**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.

155 165 

156**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts:166**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call:

157 167 

158```bash theme={null}168```bash theme={null}

159claude --agents '{169claude --agents '{


162 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",172 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",

163 "tools": ["Read", "Grep", "Glob", "Bash"],173 "tools": ["Read", "Grep", "Glob", "Bash"],

164 "model": "sonnet"174 "model": "sonnet"

175 },

176 "debugger": {

177 "description": "Debugging specialist for errors and test failures.",

178 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."

165 }179 }

166}'180}'

167```181```

168 182 

169The `--agents` flag accepts JSON with the same fields as [frontmatter](#supported-frontmatter-fields). Use `prompt` for the system prompt (equivalent to the markdown body in file-based subagents). See the [CLI reference](/en/cli-reference#agents-flag-format) for the full JSON format.183The `--agents` flag accepts JSON with the same [frontmatter](#supported-frontmatter-fields) fields as file-based subagents: `description`, `prompt`, `tools`, `disallowedTools`, `model`, `permissionMode`, `mcpServers`, `hooks`, `maxTurns`, `skills`, and `memory`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents.

170 184 

171**Plugin subagents** come from [plugins](/en/plugins) you've installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.185**Plugin subagents** come from [plugins](/en/plugins) you've installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.

172 186 

187<Note>

188 For security reasons, plugin subagents do not support the `hooks`, `mcpServers`, or `permissionMode` frontmatter fields. These fields are ignored when loading agents from a plugin. If you need them, copy the agent file into `.claude/agents/` or `~/.claude/agents/`. You can also add rules to [`permissions.allow`](/en/settings#permission-settings) in `settings.json` or `settings.local.json`, but these rules apply to the entire session, not just the plugin subagent.

189</Note>

190 

173### Write subagent files191### Write subagent files

174 192 

175Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:193Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:


197The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.215The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.

198 216 

199| Field | Required | Description |217| Field | Required | Description |

200| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |218| :---------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

201| `name` | Yes | Unique identifier using lowercase letters and hyphens |219| `name` | Yes | Unique identifier using lowercase letters and hyphens |

202| `description` | Yes | When Claude should delegate to this subagent |220| `description` | Yes | When Claude should delegate to this subagent |

203| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |221| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |

204| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |222| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |

205| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `inherit` |223| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, a full model ID (for example, `claude-opus-4-6`), or `inherit`. Defaults to `inherit` |

206| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |224| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |

225| `maxTurns` | No | Maximum number of agentic turns before the subagent stops |

207| `skills` | No | [Skills](/en/skills) to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation |226| `skills` | No | [Skills](/en/skills) to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation |

227| `mcpServers` | No | [MCP servers](/en/mcp) available to this subagent. Each entry is either a server name referencing an already-configured server (e.g., `"slack"`) or an inline definition with the server name as key and a full [MCP server config](/en/mcp#configure-mcp-servers) as value |

208| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |228| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |

229| `memory` | No | [Persistent memory scope](#enable-persistent-memory): `user`, `project`, or `local`. Enables cross-session learning |

230| `background` | No | Set to `true` to always run this subagent as a [background task](#run-subagents-in-foreground-or-background). Default: `false` |

231| `isolation` | No | Set to `worktree` to run the subagent in a temporary [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees), giving it an isolated copy of the repository. The worktree is automatically cleaned up if the subagent makes no changes |

209 232 

210### Choose a model233### Choose a model

211 234 

212The `model` field controls which [AI model](/en/model-config) the subagent uses:235The `model` field controls which [AI model](/en/model-config) the subagent uses:

213 236 

214* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`237* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`

238* **Full model ID**: Use a full model ID such as `claude-opus-4-6` or `claude-sonnet-4-6`. Accepts the same values as the `--model` flag

215* **inherit**: Use the same model as the main conversation239* **inherit**: Use the same model as the main conversation

216* **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation)240* **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation)

217 241 


221 245 

222#### Available tools246#### Available tools

223 247 

224Subagents can use any of Claude Code's [internal tools](/en/settings#tools-available-to-claude). By default, subagents inherit all tools from the main conversation, including MCP tools.248Subagents can use any of Claude Code's [internal tools](/en/tools-reference). By default, subagents inherit all tools from the main conversation, including MCP tools.

225 249 

226To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist):250To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist):

227 251 


234---258---

235```259```

236 260 

261#### Restrict which subagents can be spawned

262 

263When an agent runs as the main thread with `claude --agent`, it can spawn subagents using the Agent tool. To restrict which subagent types it can spawn, use `Agent(agent_type)` syntax in the `tools` field.

264 

265<Note>In version 2.1.63, the Task tool was renamed to Agent. Existing `Task(...)` references in settings and agent definitions still work as aliases.</Note>

266 

267```yaml theme={null}

268---

269name: coordinator

270description: Coordinates work across specialized agents

271tools: Agent(worker, researcher), Read, Bash

272---

273```

274 

275This is an allowlist: only the `worker` and `researcher` subagents can be spawned. If the agent tries to spawn any other type, the request fails and the agent sees only the allowed types in its prompt. To block specific agents while allowing all others, use [`permissions.deny`](#disable-specific-subagents) instead.

276 

277To allow spawning any subagent without restrictions, use `Agent` without parentheses:

278 

279```yaml theme={null}

280tools: Agent, Read, Bash

281```

282 

283If `Agent` is omitted from the `tools` list entirely, the agent cannot spawn any subagents. This restriction only applies to agents running as the main thread with `claude --agent`. Subagents cannot spawn other subagents, so `Agent(agent_type)` has no effect in subagent definitions.

284 

285#### Scope MCP servers to a subagent

286 

287Use the `mcpServers` field to give a subagent access to [MCP](/en/mcp) servers that aren't available in the main conversation. Inline servers defined here are connected when the subagent starts and disconnected when it finishes. String references share the parent session's connection.

288 

289Each entry in the list is either an inline server definition or a string referencing an MCP server already configured in your session:

290 

291```yaml theme={null}

292---

293name: browser-tester

294description: Tests features in a real browser using Playwright

295mcpServers:

296 # Inline definition: scoped to this subagent only

297 - playwright:

298 type: stdio

299 command: npx

300 args: ["-y", "@playwright/mcp@latest"]

301 # Reference by name: reuses an already-configured server

302 - github

303---

304 

305Use the Playwright tools to navigate, screenshot, and interact with pages.

306```

307 

308Inline definitions use the same schema as `.mcp.json` server entries (`stdio`, `http`, `sse`, `ws`), keyed by the server name.

309 

310To keep an MCP server out of the main conversation entirely and avoid its tool descriptions consuming context there, define it inline here rather than in `.mcp.json`. The subagent gets the tools; the parent conversation does not.

311 

237#### Permission modes312#### Permission modes

238 313 

239The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.314The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.


274 This is the inverse of [running a skill in a subagent](/en/skills#run-skills-in-a-subagent). With `skills` in a subagent, the subagent controls the system prompt and loads skill content. With `context: fork` in a skill, the skill content is injected into the agent you specify. Both use the same underlying system.349 This is the inverse of [running a skill in a subagent](/en/skills#run-skills-in-a-subagent). With `skills` in a subagent, the subagent controls the system prompt and loads skill content. With `context: fork` in a skill, the skill content is injected into the agent you specify. Both use the same underlying system.

275</Note>350</Note>

276 351 

352#### Enable persistent memory

353 

354The `memory` field gives the subagent a persistent directory that survives across conversations. The subagent uses this directory to build up knowledge over time, such as codebase patterns, debugging insights, and architectural decisions.

355 

356```yaml theme={null}

357---

358name: code-reviewer

359description: Reviews code for quality and best practices

360memory: user

361---

362 

363You are a code reviewer. As you review code, update your agent memory with

364patterns, conventions, and recurring issues you discover.

365```

366 

367Choose a scope based on how broadly the memory should apply:

368 

369| Scope | Location | Use when |

370| :-------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------ |

371| `user` | `~/.claude/agent-memory/<name-of-agent>/` | the subagent should remember learnings across all projects |

372| `project` | `.claude/agent-memory/<name-of-agent>/` | the subagent's knowledge is project-specific and shareable via version control |

373| `local` | `.claude/agent-memory-local/<name-of-agent>/` | the subagent's knowledge is project-specific but should not be checked into version control |

374 

375When memory is enabled:

376 

377* The subagent's system prompt includes instructions for reading and writing to the memory directory.

378* The subagent's system prompt also includes the first 200 lines of `MEMORY.md` in the memory directory, with instructions to curate `MEMORY.md` if it exceeds 200 lines.

379* Read, Write, and Edit tools are automatically enabled so the subagent can manage its memory files.

380 

381##### Persistent memory tips

382 

383* `user` is the recommended default scope. Use `project` or `local` when the subagent's knowledge is only relevant to a specific codebase.

384* Ask the subagent to consult its memory before starting work: "Review this PR, and check your memory for patterns you've seen before."

385* Ask the subagent to update its memory after completing a task: "Now that you're done, save what you learned to your memory." Over time, this builds a knowledge base that makes the subagent more effective.

386* Include memory instructions directly in the subagent's markdown file so it proactively maintains its own knowledge base:

387 

388 ```markdown theme={null}

389 Update your agent memory as you discover codepaths, patterns, library

390 locations, and key architectural decisions. This builds up institutional

391 knowledge across conversations. Write concise notes about what you found

392 and where.

393 ```

394 

277#### Conditional rules with hooks395#### Conditional rules with hooks

278 396 

279For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.397For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.


294---412---

295```413```

296 414 

297Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and [exits with code 2](/en/hooks#exit-code-2-behavior) to block write operations:415Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and [exits with code 2](/en/hooks#exit-code-2-behavior-per-event) to block write operations:

298 416 

299```bash theme={null}417```bash theme={null}

300#!/bin/bash418#!/bin/bash


312exit 0430exit 0

313```431```

314 432 

315See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/en/hooks#simple-exit-code) for how exit codes affect behavior.433See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/en/hooks#exit-code-output) for how exit codes affect behavior.

316 434 

317#### Disable specific subagents435#### Disable specific subagents

318 436 

319You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Task(subagent-name)` where `subagent-name` matches the subagent's name field.437You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Agent(subagent-name)` where `subagent-name` matches the subagent's name field.

320 438 

321```json theme={null}439```json theme={null}

322{440{

323 "permissions": {441 "permissions": {

324 "deny": ["Task(Explore)", "Task(my-custom-agent)"]442 "deny": ["Agent(Explore)", "Agent(my-custom-agent)"]

325 }443 }

326}444}

327```445```


329This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:447This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:

330 448 

331```bash theme={null}449```bash theme={null}

332claude --disallowedTools "Task(Explore)"450claude --disallowedTools "Agent(Explore)"

333```451```

334 452 

335See [IAM documentation](/en/iam#tool-specific-permission-rules) for more details on permission rules.453See [Permissions documentation](/en/permissions#tool-specific-permission-rules) for more details on permission rules.

336 454 

337### Define hooks for subagents455### Define hooks for subagents

338 456 


345 463 

346Define hooks directly in the subagent's markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes.464Define hooks directly in the subagent's markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes.

347 465 

466All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are:

467 

348| Event | Matcher input | When it fires |468| Event | Matcher input | When it fires |

349| :------------ | :------------ | :------------------------------ |469| :------------ | :------------ | :------------------------------------------------------------------ |

350| `PreToolUse` | Tool name | Before the subagent uses a tool |470| `PreToolUse` | Tool name | Before the subagent uses a tool |

351| `PostToolUse` | Tool name | After the subagent uses a tool |471| `PostToolUse` | Tool name | After the subagent uses a tool |

352| `Stop` | (none) | When the subagent finishes |472| `Stop` | (none) | When the subagent finishes (converted to `SubagentStop` at runtime) |

353 473 

354This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:474This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:

355 475 


375 495 

376#### Project-level hooks for subagent events496#### Project-level hooks for subagent events

377 497 

378Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. Use the `matcher` field to target specific agent types by name.498Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session.

379 499 

380| Event | Matcher input | When it fires |500| Event | Matcher input | When it fires |

381| :-------------- | :-------------- | :------------------------------- |501| :-------------- | :-------------- | :------------------------------- |

382| `SubagentStart` | Agent type name | When a subagent begins execution |502| `SubagentStart` | Agent type name | When a subagent begins execution |

383| `SubagentStop` | Agent type name | When a subagent completes |503| `SubagentStop` | Agent type name | When a subagent completes |

384 504 

385This example runs setup and cleanup scripts only when the `db-agent` subagent starts and stops:505Both events support matchers to target specific agent types by name. This example runs a setup script only when the `db-agent` subagent starts, and a cleanup script when any subagent stops:

386 506 

387```json theme={null}507```json theme={null}

388{508{


397 ],517 ],

398 "SubagentStop": [518 "SubagentStop": [

399 {519 {

400 "matcher": "db-agent",

401 "hooks": [520 "hooks": [

402 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }521 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }

403 ]522 ]


417 536 

418You can also request a specific subagent explicitly:537You can also request a specific subagent explicitly:

419 538 

420```539```text theme={null}

421Use the test-runner subagent to fix failing tests540Use the test-runner subagent to fix failing tests

422Have the code-reviewer subagent look at my recent changes541Have the code-reviewer subagent look at my recent changes

423```542```


426 545 

427Subagents can run in the foreground (blocking) or background (concurrent):546Subagents can run in the foreground (blocking) or background (concurrent):

428 547 

429* **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/settings#tools-available-to-claude)) are passed through to you.548* **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/tools-reference)) are passed through to you.

430* **Background subagents** run concurrently while you continue working. They inherit the parent's permissions and auto-deny anything not pre-approved. If a background subagent needs a permission it doesn't have or needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents.549* **Background subagents** run concurrently while you continue working. Before launching, Claude Code prompts for any tool permissions the subagent will need, ensuring it has the necessary approvals upfront. Once running, the subagent inherits these permissions and auto-denies anything not pre-approved. If a background subagent needs to ask clarifying questions, that tool call fails but the subagent continues.

431 550 

432If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.551If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.

433 552 


436* Ask Claude to "run this in the background"555* Ask Claude to "run this in the background"

437* Press **Ctrl+B** to background a running task556* Press **Ctrl+B** to background a running task

438 557 

439To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables).558To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars).

440 559 

441### Common patterns560### Common patterns

442 561 


444 563 

445One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation.564One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation.

446 565 

447```566```text theme={null}

448Use a subagent to run the test suite and report only the failing tests with their error messages567Use a subagent to run the test suite and report only the failing tests with their error messages

449```568```

450 569 


452 571 

453For independent investigations, spawn multiple subagents to work simultaneously:572For independent investigations, spawn multiple subagents to work simultaneously:

454 573 

455```574```text theme={null}

456Research the authentication, database, and API modules in parallel using separate subagents575Research the authentication, database, and API modules in parallel using separate subagents

457```576```

458 577 


462 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.581 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.

463</Warning>582</Warning>

464 583 

584For tasks that need sustained parallelism or exceed your context window, [agent teams](/en/agent-teams) give each worker its own independent context.

585 

465#### Chain subagents586#### Chain subagents

466 587 

467For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.588For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.

468 589 

469```590```text theme={null}

470Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them591Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

471```592```

472 593 


487 608 

488Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.609Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.

489 610 

611For a quick question about something already in your conversation, use [`/btw`](/en/interactive-mode#side-questions-with-btw) instead of a subagent. It sees your full context but has no tool access, and the answer is discarded rather than added to history.

612 

490<Note>613<Note>

491 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.614 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.

492</Note>615</Note>


501 624 

502When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:625When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:

503 626 

504```627```text theme={null}

505Use the code-reviewer subagent to review the authentication module628Use the code-reviewer subagent to review the authentication module

506[Agent completes]629[Agent completes]

507 630 


519 642 

520#### Auto-compaction643#### Auto-compaction

521 644 

522Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` to a lower percentage (for example, `50`). See [environment variables](/en/settings#environment-variables) for details.645Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` to a lower percentage (for example, `50`). See [environment variables](/en/env-vars) for details.

523 646 

524Compaction events are logged in subagent transcript files:647Compaction events are logged in subagent transcript files:

525 648 


687You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.810You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.

688```811```

689 812 

690Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script [exits with code 2](/en/hooks#exit-code-2-behavior) to block execution and returns an error message to Claude via stderr.813Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script [exits with code 2](/en/hooks#exit-code-2-behavior-per-event) to block execution and returns an error message to Claude via stderr.

691 814 

692Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:815Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:

693 816 


720chmod +x ./scripts/validate-readonly-query.sh843chmod +x ./scripts/validate-readonly-query.sh

721```844```

722 845 

723The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/en/hooks#simple-exit-code) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema.846The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/en/hooks#exit-code-output) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema.

724 847 

725## Next steps848## Next steps

726 849 


729* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects852* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects

730* [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation853* [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation

731* [Use MCP servers](/en/mcp) to give subagents access to external tools and data854* [Use MCP servers](/en/mcp) to give subagents access to external tools and data

732 

733 

734 

735> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

terminal-config.md +15 −14

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Optimize your terminal setup5# Optimize your terminal setup

2 6 

3> Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience.7> Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience.


38 42 

39### Notification setup43### Notification setup

40 44 

41Never miss when Claude completes a task with proper notification configuration:45When Claude finishes working and is waiting for your input, it fires a notification event. You can surface this event as a desktop notification through your terminal or run custom logic with [notification hooks](/en/hooks#notification).

46 

47#### Terminal notifications

42 48 

43#### iTerm 2 system notifications49Kitty and Ghostty support desktop notifications without additional configuration. iTerm 2 requires setup:

44 50 

45For iTerm 2 alerts when tasks complete:511. Open iTerm 2 Settings Profiles → Terminal

522. Enable "Notification Center Alerts"

533. Click "Filter Alerts" and check "Send escape sequence-generated alerts"

46 54 

471. Open iTerm 2 Preferences55If notifications aren't appearing, verify that your terminal app has notification permissions in your OS settings.

482. Navigate to Profiles → Terminal

493. Enable "Silence bell" and Filter Alerts → "Send escape sequence-generated alerts"

504. Set your preferred notification delay

51 56 

52Note that these notifications are specific to iTerm 2 and not available in the default macOS Terminal.57Other terminals, including the default macOS Terminal, do not support native notifications. Use [notification hooks](/en/hooks#notification) instead.

53 58 

54#### Custom notification hooks59#### Notification hooks

55 60 

56For advanced notification handling, you can create [notification hooks](/en/hooks#notification) to run your own logic.61To add custom behavior when notifications fire, such as playing a sound or sending a message, configure a [notification hook](/en/hooks#notification). Hooks run alongside terminal notifications, not as a replacement.

57 62 

58### Handling large inputs63### Handling large inputs

59 64 


78* Line operations: `J` (join lines)83* Line operations: `J` (join lines)

79 84 

80See [Interactive mode](/en/interactive-mode#vim-editor-mode) for the complete reference.85See [Interactive mode](/en/interactive-mode#vim-editor-mode) for the complete reference.

81 

82 

83 

84> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Enterprise deployment overview5# Enterprise deployment overview

2 6 

3> Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements.7> Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements.


40 44 

41 <tr>45 <tr>

42 <td>Billing</td>46 <td>Billing</td>

43 <td><strong>Teams:</strong> \$150/seat (Premium) with PAYG available<br /><strong>Enterprise:</strong> <a href="https://claude.com/contact-sales">Contact Sales</a></td>47 <td><strong>Teams:</strong> \$150/seat (Premium) with PAYG available<br /><strong>Enterprise:</strong> <a href="https://claude.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=third_party_enterprise">Contact Sales</a></td>

44 <td>PAYG</td>48 <td>PAYG</td>

45 <td>PAYG through AWS</td>49 <td>PAYG through AWS</td>

46 <td>PAYG through GCP</td>50 <td>PAYG through GCP</td>


105 109 

106Select a deployment option to view setup instructions:110Select a deployment option to view setup instructions:

107 111 

108* [Claude for Teams or Enterprise](/en/iam#claude-for-teams-or-enterprise-recommended)112* [Claude for Teams or Enterprise](/en/authentication#claude-for-teams-or-enterprise)

109* [Anthropic Console](/en/iam#claude-console-authentication)113* [Anthropic Console](/en/authentication#claude-console-authentication)

110* [Amazon Bedrock](/en/amazon-bedrock)114* [Amazon Bedrock](/en/amazon-bedrock)

111* [Google Vertex AI](/en/google-vertex-ai)115* [Google Vertex AI](/en/google-vertex-ai)

112* [Microsoft Foundry](/en/microsoft-foundry)116* [Microsoft Foundry](/en/microsoft-foundry)


124 128 

125<Tabs>129<Tabs>

126 <Tab title="Corporate proxy">130 <Tab title="Corporate proxy">

127 Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables):131 Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/en/env-vars):

128 132 

129 ```bash theme={null}133 ```bash theme={null}

130 # Enable Bedrock134 # Enable Bedrock


137 </Tab>141 </Tab>

138 142 

139 <Tab title="LLM Gateway">143 <Tab title="LLM Gateway">

140 Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables):144 Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/en/env-vars):

141 145 

142 ```bash theme={null}146 ```bash theme={null}

143 # Enable Bedrock147 # Enable Bedrock


154 158 

155<Tabs>159<Tabs>

156 <Tab title="Corporate proxy">160 <Tab title="Corporate proxy">

157 Route Foundry traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables):161 Route Foundry traffic through your corporate proxy by setting the following [environment variables](/en/env-vars):

158 162 

159 ```bash theme={null}163 ```bash theme={null}

160 # Enable Microsoft Foundry164 # Enable Microsoft Foundry


168 </Tab>172 </Tab>

169 173 

170 <Tab title="LLM Gateway">174 <Tab title="LLM Gateway">

171 Route Foundry traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables):175 Route Foundry traffic through your LLM gateway by setting the following [environment variables](/en/env-vars):

172 176 

173 ```bash theme={null}177 ```bash theme={null}

174 # Enable Microsoft Foundry178 # Enable Microsoft Foundry


185 189 

186<Tabs>190<Tabs>

187 <Tab title="Corporate proxy">191 <Tab title="Corporate proxy">

188 Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables):192 Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/en/env-vars):

189 193 

190 ```bash theme={null}194 ```bash theme={null}

191 # Enable Vertex195 # Enable Vertex


199 </Tab>203 </Tab>

200 204 

201 <Tab title="LLM Gateway">205 <Tab title="LLM Gateway">

202 Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables):206 Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/en/env-vars):

203 207 

204 ```bash theme={null}208 ```bash theme={null}

205 # Enable Vertex209 # Enable Vertex


235 239 

236Encourage new users to try Claude Code for codebase Q\&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude's suggestions and give feedback if it's off-track. Over time, as users understand this new paradigm better, then they'll be more effective at letting Claude Code run more agentically.240Encourage new users to try Claude Code for codebase Q\&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude's suggestions and give feedback if it's off-track. Over time, as users understand this new paradigm better, then they'll be more effective at letting Claude Code run more agentically.

237 241 

242### Pin model versions for cloud providers

243 

244If you deploy through [Bedrock](/en/amazon-bedrock), [Vertex AI](/en/google-vertex-ai), or [Foundry](/en/microsoft-foundry), pin specific model versions using `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL`. Without pinning, Claude Code aliases resolve to the latest version, which can break users when Anthropic releases a new model that isn't yet enabled in your account. See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for details.

245 

238### Configure security policies246### Configure security policies

239 247 

240Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](/en/security).248Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](/en/security).


2521. **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/en/setup) and authenticate with their credentials.2601. **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/en/setup) and authenticate with their credentials.

2532. **Set up shared configuration**: Create a [CLAUDE.md file](/en/memory) in your repositories to help Claude Code understand your codebase and coding standards.2612. **Set up shared configuration**: Create a [CLAUDE.md file](/en/memory) in your repositories to help Claude Code understand your codebase and coding standards.

2543. **Configure permissions**: Review [security settings](/en/security) to define what Claude Code can and cannot do in your environment.2623. **Configure permissions**: Review [security settings](/en/security) to define what Claude Code can and cannot do in your environment.

255 

256 

257 

258> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

tools-reference.md +59 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Tools reference

6 

7> Complete reference for the tools Claude Code can use, including permission requirements.

8 

9Claude Code has access to a set of tools that help it understand and modify your codebase. The tool names below are the exact strings you use in [permission rules](/en/permissions#tool-specific-permission-rules), [subagent tool lists](/en/sub-agents), and [hook matchers](/en/hooks).

10 

11| Tool | Description | Permission Required |

12| :--------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |

13| `Agent` | Spawns a [subagent](/en/sub-agents) with its own context window to handle a task | No |

14| `AskUserQuestion` | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |

15| `Bash` | Executes shell commands in your environment. See [Bash tool behavior](#bash-tool-behavior) | Yes |

16| `CronCreate` | Schedules a recurring or one-shot prompt within the current session (gone when Claude exits). See [scheduled tasks](/en/scheduled-tasks) | No |

17| `CronDelete` | Cancels a scheduled task by ID | No |

18| `CronList` | Lists all scheduled tasks in the session | No |

19| `Edit` | Makes targeted edits to specific files | Yes |

20| `EnterPlanMode` | Switches to plan mode to design an approach before coding | No |

21| `EnterWorktree` | Creates an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) and switches into it | No |

22| `ExitPlanMode` | Presents a plan for approval and exits plan mode | Yes |

23| `ExitWorktree` | Exits a worktree session and returns to the original directory | No |

24| `Glob` | Finds files based on pattern matching | No |

25| `Grep` | Searches for patterns in file contents | No |

26| `ListMcpResourcesTool` | Lists resources exposed by connected [MCP servers](/en/mcp) | No |

27| `LSP` | Code intelligence via language servers. Reports type errors and warnings automatically after file edits. Also supports navigation operations: jump to definitions, find references, get type info, list symbols, find implementations, trace call hierarchies. Requires a [code intelligence plugin](/en/discover-plugins#code-intelligence) and its language server binary | No |

28| `NotebookEdit` | Modifies Jupyter notebook cells | Yes |

29| `Read` | Reads the contents of files | No |

30| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |

31| `Skill` | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

32| `TaskCreate` | Creates a new task in the task list | No |

33| `TaskGet` | Retrieves full details for a specific task | No |

34| `TaskList` | Lists all tasks with their current status | No |

35| `TaskOutput` | Retrieves output from a background task | No |

36| `TaskStop` | Kills a running background task by ID | No |

37| `TaskUpdate` | Updates task status, dependencies, details, or deletes tasks | No |

38| `TodoWrite` | Manages the session task checklist. Available in non-interactive mode and the [Agent SDK](/en/headless); interactive sessions use TaskCreate, TaskGet, TaskList, and TaskUpdate instead | No |

39| `ToolSearch` | Searches for and loads deferred tools when [tool search](/en/mcp#scale-with-mcp-tool-search) is enabled | No |

40| `WebFetch` | Fetches content from a specified URL | Yes |

41| `WebSearch` | Performs web searches | Yes |

42| `Write` | Creates or overwrites files | Yes |

43 

44Permission rules can be configured using `/permissions` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/permissions#tool-specific-permission-rules).

45 

46## Bash tool behavior

47 

48The Bash tool runs each command in a separate process with the following persistence behavior:

49 

50* Working directory persists across commands. Set `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1` to reset to the project directory after each command.

51* Environment variables do not persist. An `export` in one command will not be available in the next.

52 

53Activate your virtualenv or conda environment before launching Claude Code. To make environment variables persist across Bash commands, set [`CLAUDE_ENV_FILE`](/en/env-vars) to a shell script before launching Claude Code, or use a [SessionStart hook](/en/hooks#persist-environment-variables) to populate it dynamically.

54 

55## See also

56 

57* [Permissions](/en/permissions): permission system, rule syntax, and tool-specific patterns

58* [Subagents](/en/sub-agents): configure tool access for subagents

59* [Hooks](/en/hooks-guide): run custom commands before or after tool execution

troubleshooting.md +588 −121

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Troubleshooting5# Troubleshooting

2 6 

3> Discover solutions to common issues with Claude Code installation and usage.7> Discover solutions to common issues with Claude Code installation and usage.

4 8 

9## Troubleshoot installation issues

10 

11<Tip>

12 If you'd rather skip the terminal entirely, the [Claude Code Desktop app](/en/desktop-quickstart) lets you install and use Claude Code through a graphical interface. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs) and start coding without any command-line setup.

13</Tip>

14 

15Find the error message or symptom you're seeing:

16 

17| What you see | Solution |

18| :---------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------- |

19| `command not found: claude` or `'claude' is not recognized` | [Fix your PATH](#command-not-found-claude-after-installation) |

20| `syntax error near unexpected token '<'` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

21| `curl: (56) Failure writing output to destination` | [Download script first, then run it](#curl-56-failure-writing-output-to-destination) |

22| `Killed` during install on Linux | [Add swap space for low-memory servers](#install-killed-on-low-memory-linux-servers) |

23| `TLS connect error` or `SSL/TLS secure channel` | [Update CA certificates](#tls-or-ssl-connection-errors) |

24| `Failed to fetch version` or can't reach download server | [Check network and proxy settings](#check-network-connectivity) |

25| `irm is not recognized` or `&& is not valid` | [Use the right command for your shell](#windows-irm-or--not-recognized) |

26| `Claude Code on Windows requires git-bash` | [Install or configure Git Bash](#windows-claude-code-on-windows-requires-git-bash) |

27| `Error loading shared library` | [Wrong binary variant for your system](#linux-wrong-binary-variant-installed-muslglibc-mismatch) |

28| `Illegal instruction` on Linux | [Architecture mismatch](#illegal-instruction-on-linux) |

29| `dyld: cannot load` or `Abort trap` on macOS | [Binary incompatibility](#dyld-cannot-load-on-macos) |

30| `Invoke-Expression: Missing argument in parameter list` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

31| `App unavailable in region` | Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries). |

32| `unable to get local issuer certificate` | [Configure corporate CA certificates](#tls-or-ssl-connection-errors) |

33| `OAuth error` or `403 Forbidden` | [Fix authentication](#authentication-issues) |

34 

35If your issue isn't listed, work through these diagnostic steps.

36 

37## Debug installation problems

38 

39### Check network connectivity

40 

41The installer downloads from `storage.googleapis.com`. Verify you can reach it:

42 

43```bash theme={null}

44curl -sI https://storage.googleapis.com

45```

46 

47If this fails, your network may be blocking the connection. Common causes:

48 

49* Corporate firewalls or proxies blocking Google Cloud Storage

50* Regional network restrictions: try a VPN or alternative network

51* TLS/SSL issues: update your system's CA certificates, or check if `HTTPS_PROXY` is configured

52 

53If you're behind a corporate proxy, set `HTTPS_PROXY` and `HTTP_PROXY` to your proxy's address before installing. Ask your IT team for the proxy URL if you don't know it, or check your browser's proxy settings.

54 

55This example sets both proxy variables, then runs the installer through your proxy:

56 

57```bash theme={null}

58export HTTP_PROXY=http://proxy.example.com:8080

59export HTTPS_PROXY=http://proxy.example.com:8080

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

61```

62 

63### Verify your PATH

64 

65If installation succeeded but you get a `command not found` or `not recognized` error when running `claude`, the install directory isn't in your PATH. Your shell searches for programs in directories listed in PATH, and the installer places `claude` at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows.

66 

67Check if the install directory is in your PATH by listing your PATH entries and filtering for `local/bin`:

68 

69<Tabs>

70 <Tab title="macOS/Linux">

71 ```bash theme={null}

72 echo $PATH | tr ':' '\n' | grep local/bin

73 ```

74 

75 If there's no output, the directory is missing. Add it to your shell configuration:

76 

77 ```bash theme={null}

78 # Zsh (macOS default)

79 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

80 source ~/.zshrc

81 

82 # Bash (Linux default)

83 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

84 source ~/.bashrc

85 ```

86 

87 Alternatively, close and reopen your terminal.

88 

89 Verify the fix worked:

90 

91 ```bash theme={null}

92 claude --version

93 ```

94 </Tab>

95 

96 <Tab title="Windows PowerShell">

97 ```powershell theme={null}

98 $env:PATH -split ';' | Select-String 'local\\bin'

99 ```

100 

101 If there's no output, add the install directory to your User PATH:

102 

103 ```powershell theme={null}

104 $currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')

105 [Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User')

106 ```

107 

108 Restart your terminal for the change to take effect.

109 

110 Verify the fix worked:

111 

112 ```powershell theme={null}

113 claude --version

114 ```

115 </Tab>

116 

117 <Tab title="Windows CMD">

118 ```batch theme={null}

119 echo %PATH% | findstr /i "local\bin"

120 ```

121 

122 If there's no output, open System Settings, go to Environment Variables, and add `%USERPROFILE%\.local\bin` to your User PATH variable. Restart your terminal.

123 

124 Verify the fix worked:

125 

126 ```batch theme={null}

127 claude --version

128 ```

129 </Tab>

130</Tabs>

131 

132### Check for conflicting installations

133 

134Multiple Claude Code installations can cause version mismatches or unexpected behavior. Check what's installed:

135 

136<Tabs>

137 <Tab title="macOS/Linux">

138 List all `claude` binaries found in your PATH:

139 

140 ```bash theme={null}

141 which -a claude

142 ```

143 

144 Check whether the native installer and npm versions are present:

145 

146 ```bash theme={null}

147 ls -la ~/.local/bin/claude

148 ```

149 

150 ```bash theme={null}

151 ls -la ~/.claude/local/

152 ```

153 

154 ```bash theme={null}

155 npm -g ls @anthropic-ai/claude-code 2>/dev/null

156 ```

157 </Tab>

158 

159 <Tab title="Windows PowerShell">

160 ```powershell theme={null}

161 where.exe claude

162 Test-Path "$env:LOCALAPPDATA\Claude Code\claude.exe"

163 ```

164 </Tab>

165</Tabs>

166 

167If you find multiple installations, keep only one. The native install at `~/.local/bin/claude` is recommended. Remove any extra installations:

168 

169Uninstall an npm global install:

170 

171```bash theme={null}

172npm uninstall -g @anthropic-ai/claude-code

173```

174 

175Remove a Homebrew install on macOS:

176 

177```bash theme={null}

178brew uninstall --cask claude-code

179```

180 

181### Check directory permissions

182 

183The installer needs write access to `~/.local/bin/` and `~/.claude/`. If installation fails with permission errors, check whether these directories are writable:

184 

185```bash theme={null}

186test -w ~/.local/bin && echo "writable" || echo "not writable"

187test -w ~/.claude && echo "writable" || echo "not writable"

188```

189 

190If either directory isn't writable, create the install directory and set your user as the owner:

191 

192```bash theme={null}

193sudo mkdir -p ~/.local/bin

194sudo chown -R $(whoami) ~/.local

195```

196 

197### Verify the binary works

198 

199If `claude` is installed but crashes or hangs on startup, run these checks to narrow down the cause.

200 

201Confirm the binary exists and is executable:

202 

203```bash theme={null}

204ls -la $(which claude)

205```

206 

207On Linux, check for missing shared libraries. If `ldd` shows missing libraries, you may need to install system packages. On Alpine Linux and other musl-based distributions, see [Alpine Linux setup](/en/setup#alpine-linux-and-musl-based-distributions).

208 

209```bash theme={null}

210ldd $(which claude) | grep "not found"

211```

212 

213Run a quick sanity check that the binary can execute:

214 

215```bash theme={null}

216claude --version

217```

218 

5## Common installation issues219## Common installation issues

6 220 

221These are the most frequently encountered installation problems and their solutions.

222 

223### Install script returns HTML instead of a shell script

224 

225When running the install command, you may see one of these errors:

226 

227```text theme={null}

228bash: line 1: syntax error near unexpected token `<'

229bash: line 1: `<!DOCTYPE html>'

230```

231 

232On PowerShell, the same problem appears as:

233 

234```text theme={null}

235Invoke-Expression: Missing argument in parameter list.

236```

237 

238This means the install URL returned an HTML page instead of the install script. If the HTML page says "App unavailable in region," Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries).

239 

240Otherwise, this can happen due to network issues, regional routing, or a temporary service disruption.

241 

242**Solutions:**

243 

2441. **Use an alternative install method**:

245 

246 On macOS or Linux, install via Homebrew:

247 

248 ```bash theme={null}

249 brew install --cask claude-code

250 ```

251 

252 On Windows, install via WinGet:

253 

254 ```powershell theme={null}

255 winget install Anthropic.ClaudeCode

256 ```

257 

2582. **Retry after a few minutes**: the issue is often temporary. Wait and try the original command again.

259 

260### `command not found: claude` after installation

261 

262The install finished but `claude` doesn't work. The exact error varies by platform:

263 

264| Platform | Error message |

265| :---------- | :--------------------------------------------------------------------- |

266| macOS | `zsh: command not found: claude` |

267| Linux | `bash: claude: command not found` |

268| Windows CMD | `'claude' is not recognized as an internal or external command` |

269| PowerShell | `claude : The term 'claude' is not recognized as the name of a cmdlet` |

270 

271This means the install directory isn't in your shell's search path. See [Verify your PATH](#verify-your-path) for the fix on each platform.

272 

273### `curl: (56) Failure writing output to destination`

274 

275The `curl ... | bash` command downloads the script and passes it directly to Bash for execution using a pipe (`|`). This error means the connection broke before the script finished downloading. Common causes include network interruptions, the download being blocked mid-stream, or system resource limits.

276 

277**Solutions:**

278 

2791. **Check network stability**: Claude Code binaries are hosted on Google Cloud Storage. Test that you can reach it:

280 ```bash theme={null}

281 curl -fsSL https://storage.googleapis.com -o /dev/null

282 ```

283 If the command completes silently, your connection is fine and the issue is likely intermittent. Retry the install command. If you see an error, your network may be blocking the download.

284 

2852. **Try an alternative install method**:

286 

287 On macOS or Linux:

288 

289 ```bash theme={null}

290 brew install --cask claude-code

291 ```

292 

293 On Windows:

294 

295 ```powershell theme={null}

296 winget install Anthropic.ClaudeCode

297 ```

298 

299### TLS or SSL connection errors

300 

301Errors like `curl: (35) TLS connect error`, `schannel: next InitializeSecurityContext failed`, or PowerShell's `Could not establish trust relationship for the SSL/TLS secure channel` indicate TLS handshake failures.

302 

303**Solutions:**

304 

3051. **Update your system CA certificates**:

306 

307 On Ubuntu/Debian:

308 

309 ```bash theme={null}

310 sudo apt-get update && sudo apt-get install ca-certificates

311 ```

312 

313 On macOS via Homebrew:

314 

315 ```bash theme={null}

316 brew install ca-certificates

317 ```

318 

3192. **On Windows, enable TLS 1.2** in PowerShell before running the installer:

320 ```powershell theme={null}

321 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

322 irm https://claude.ai/install.ps1 | iex

323 ```

324 

3253. **Check for proxy or firewall interference**: corporate proxies that perform TLS inspection can cause these errors, including `unable to get local issuer certificate`. Set `NODE_EXTRA_CA_CERTS` to your corporate CA certificate bundle:

326 ```bash theme={null}

327 export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem

328 ```

329 Ask your IT team for the certificate file if you don't have it. You can also try on a direct connection to confirm the proxy is the cause.

330 

331### `Failed to fetch version from storage.googleapis.com`

332 

333The installer couldn't reach the download server. This typically means `storage.googleapis.com` is blocked on your network.

334 

335**Solutions:**

336 

3371. **Test connectivity directly**:

338 ```bash theme={null}

339 curl -sI https://storage.googleapis.com

340 ```

341 

3422. **If behind a proxy**, set `HTTPS_PROXY` so the installer can route through it. See [proxy configuration](/en/network-config#proxy-configuration) for details.

343 ```bash theme={null}

344 export HTTPS_PROXY=http://proxy.example.com:8080

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

346 ```

347 

3483. **If on a restricted network**, try a different network or VPN, or use an alternative install method:

349 

350 On macOS or Linux:

351 

352 ```bash theme={null}

353 brew install --cask claude-code

354 ```

355 

356 On Windows:

357 

358 ```powershell theme={null}

359 winget install Anthropic.ClaudeCode

360 ```

361 

362### Windows: `irm` or `&&` not recognized

363 

364If you see `'irm' is not recognized` or `The token '&&' is not valid`, you're running the wrong command for your shell.

365 

366* **`irm` not recognized**: you're in CMD, not PowerShell. You have two options:

367 

368 Open PowerShell by searching for "PowerShell" in the Start menu, then run the original install command:

369 

370 ```powershell theme={null}

371 irm https://claude.ai/install.ps1 | iex

372 ```

373 

374 Or stay in CMD and use the CMD installer instead:

375 

376 ```batch theme={null}

377 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

378 ```

379 

380* **`&&` not valid**: you're in PowerShell but ran the CMD installer command. Use the PowerShell installer:

381 ```powershell theme={null}

382 irm https://claude.ai/install.ps1 | iex

383 ```

384 

385### Install killed on low-memory Linux servers

386 

387If you see `Killed` during installation on a VPS or cloud instance:

388 

389```text theme={null}

390Setting up Claude Code...

391Installing Claude Code native build latest...

392bash: line 142: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}

393```

394 

395The Linux OOM killer terminated the process because the system ran out of memory. Claude Code requires at least 4 GB of available RAM.

396 

397**Solutions:**

398 

3991. **Add swap space** if your server has limited RAM. Swap uses disk space as overflow memory, letting the install complete even with low physical RAM.

400 

401 Create a 2 GB swap file and enable it:

402 

403 ```bash theme={null}

404 sudo fallocate -l 2G /swapfile

405 sudo chmod 600 /swapfile

406 sudo mkswap /swapfile

407 sudo swapon /swapfile

408 ```

409 

410 Then retry the installation:

411 

412 ```bash theme={null}

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

414 ```

415 

4162. **Close other processes** to free memory before installing.

417 

4183. **Use a larger instance** if possible. Claude Code requires at least 4 GB of RAM.

419 

420### Install hangs in Docker

421 

422When installing Claude Code in a Docker container, installing as root into `/` can cause hangs.

423 

424**Solutions:**

425 

4261. **Set a working directory** before running the installer. When run from `/`, the installer scans the entire filesystem, which causes excessive memory usage. Setting `WORKDIR` limits the scan to a small directory:

427 ```dockerfile theme={null}

428 WORKDIR /tmp

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

430 ```

431 

4322. **Increase Docker memory limits** if using Docker Desktop:

433 ```bash theme={null}

434 docker build --memory=4g .

435 ```

436 

437### Windows: Claude Desktop overrides `claude` CLI command

438 

439If you installed an older version of Claude Desktop, it may register a `Claude.exe` in the `WindowsApps` directory that takes PATH priority over Claude Code CLI. Running `claude` opens the Desktop app instead of the CLI.

440 

441Update Claude Desktop to the latest version to fix this issue.

442 

443### Windows: "Claude Code on Windows requires git-bash"

444 

445Claude Code on native Windows needs [Git for Windows](https://git-scm.com/downloads/win), which includes Git Bash.

446 

447**If Git is not installed**, download and install it from [git-scm.com/downloads/win](https://git-scm.com/downloads/win). During setup, select "Add to PATH." Restart your terminal after installing.

448 

449**If Git is already installed** but Claude Code still can't find it, set the path in your [settings.json file](/en/settings):

450 

451```json theme={null}

452{

453 "env": {

454 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

455 }

456}

457```

458 

459If your Git is installed somewhere else, find the path by running `where.exe git` in PowerShell and use the `bin\bash.exe` path from that directory.

460 

461### Linux: wrong binary variant installed (musl/glibc mismatch)

462 

463If you see errors about missing shared libraries like `libstdc++.so.6` or `libgcc_s.so.1` after installation, the installer may have downloaded the wrong binary variant for your system.

464 

465```text theme={null}

466Error loading shared library libstdc++.so.6: No such file or directory

467```

468 

469This can happen on glibc-based systems that have musl cross-compilation packages installed, causing the installer to misdetect the system as musl.

470 

471**Solutions:**

472 

4731. **Check which libc your system uses**:

474 ```bash theme={null}

475 ldd /bin/ls | head -1

476 ```

477 If it shows `linux-vdso.so` or references to `/lib/x86_64-linux-gnu/`, you're on glibc. If it shows `musl`, you're on musl.

478 

4792. **If you're on glibc but got the musl binary**, remove the installation and reinstall. You can also manually download the correct binary from the GCS bucket at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json`. File a [GitHub issue](https://github.com/anthropics/claude-code/issues) with the output of `ldd /bin/ls` and `ls /lib/libc.musl*`.

480 

4813. **If you're actually on musl** (Alpine Linux), install the required packages:

482 ```bash theme={null}

483 apk add libgcc libstdc++ ripgrep

484 ```

485 

486### `Illegal instruction` on Linux

487 

488If the installer prints `Illegal instruction` instead of the OOM `Killed` message, the downloaded binary doesn't match your CPU architecture. This commonly happens on ARM servers that receive an x86 binary, or on older CPUs that lack required instruction sets.

489 

490```text theme={null}

491bash: line 142: 2238232 Illegal instruction "$binary_path" install ${TARGET:+"$TARGET"}

492```

493 

494**Solutions:**

495 

4961. **Verify your architecture**:

497 ```bash theme={null}

498 uname -m

499 ```

500 `x86_64` means 64-bit Intel/AMD, `aarch64` means ARM64. If the binary doesn't match, [file a GitHub issue](https://github.com/anthropics/claude-code/issues) with the output.

501 

5022. **Try an alternative install method** while the architecture issue is resolved:

503 ```bash theme={null}

504 brew install --cask claude-code

505 ```

506 

507### `dyld: cannot load` on macOS

508 

509If you see `dyld: cannot load` or `Abort trap: 6` during installation, the binary is incompatible with your macOS version or hardware.

510 

511```text theme={null}

512dyld: cannot load 'claude-2.1.42-darwin-x64' (load command 0x80000034 is unknown)

513Abort trap: 6

514```

515 

516**Solutions:**

517 

5181. **Check your macOS version**: Claude Code requires macOS 13.0 or later. Open the Apple menu and select About This Mac to check your version.

519 

5202. **Update macOS** if you're on an older version. The binary uses load commands that older macOS versions don't support.

521 

5223. **Try Homebrew** as an alternative install method:

523 ```bash theme={null}

524 brew install --cask claude-code

525 ```

526 

7### Windows installation issues: errors in WSL527### Windows installation issues: errors in WSL

8 528 

9You might encounter the following issues in WSL:529You might encounter the following issues in WSL:

10 530 

11**OS/platform detection issues**: If you receive an error during installation, WSL may be using Windows `npm`. Try:531**OS/platform detection issues**: if you receive an error during installation, WSL may be using Windows `npm`. Try:

12 532 

13* Run `npm config set os linux` before installation533* Run `npm config set os linux` before installation

14* Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check` (Do NOT use `sudo`)534* Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check`. Do not use `sudo`.

15 535 

16**Node not found errors**: If you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).536**Node not found errors**: if you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).

17 537 

18**nvm version conflicts**: If you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation.538**nvm version conflicts**: if you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation.

19 539 

20You can identify this issue by:540You can identify this issue by:

21 541 


50```570```

51 571 

52<Warning>572<Warning>

53 Avoid disabling Windows PATH importing (`appendWindowsPath = false`) as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.573 Avoid disabling Windows PATH importing via `appendWindowsPath = false` as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.

54</Warning>574</Warning>

55 575 

56### WSL2 sandbox setup576### WSL2 sandbox setup


73 593 

74WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing.594WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing.

75 595 

76### Linux and Mac installation issues: permission or command not found errors596### Permission errors during installation

77 

78When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.

79You may also encounter permission errors if your npm global prefix is not user writable (for example, `/usr`, or `/usr/local`).

80 597 

81#### Recommended solution: Native Claude Code installation598If the native installer fails with permission errors, the target directory may not be writable. See [Check directory permissions](#check-directory-permissions).

82 599 

83Claude Code has a native installation that doesn't depend on npm or Node.js.600If you previously installed with npm and are hitting npm-specific permission errors, switch to the native installer:

84 

85Use the following command to run the native installer.

86 

87**macOS, Linux, WSL:**

88 601 

89```bash theme={null}602```bash theme={null}

90# Install stable version (default)

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

92 

93# Install latest version

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

95 

96# Install specific version number

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

98```604```

99 605 

100**Windows PowerShell:**606## Permissions and authentication

101 

102```powershell theme={null}

103# Install stable version (default)

104irm https://claude.ai/install.ps1 | iex

105 

106# Install latest version

107& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest

108 607 

109# Install specific version number608These sections address login failures, token issues, and permission prompt behavior.

110& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58

111 609 

112```610### Repeated permission prompts

113 611 

114This command installs the appropriate build of Claude Code for your operating system and architecture and adds a symlink to the installation at `~/.local/bin/claude` (or `%USERPROFILE%\.local\bin\claude.exe` on Windows).612If you find yourself repeatedly approving the same commands, you can allow specific tools

613to run without approval using the `/permissions` command. See [Permissions docs](/en/permissions#manage-permissions).

115 614 

116<Tip>615### Authentication issues

117 Make sure that you have the installation directory in your system PATH.

118</Tip>

119 616 

120### Windows: "Claude Code on Windows requires git-bash"617If you're experiencing authentication problems:

121 618 

122Claude Code on native Windows requires [Git for Windows](https://git-scm.com/downloads/win) which includes Git Bash. If Git is installed but not detected:6191. Run `/logout` to sign out completely

6202. Close Claude Code

6213. Restart with `claude` and complete the authentication process again

123 622 

1241. Set the path explicitly in PowerShell before running Claude:623If the browser doesn't open automatically during login, press `c` to copy the OAuth URL to your clipboard, then paste it into your browser manually.

125 ```powershell theme={null}

126 $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"

127 ```

128 624 

1292. Or add it to your system environment variables permanently through System Properties Environment Variables.625### OAuth error: Invalid code

130 626 

131If Git is installed in a non-standard location, adjust the path accordingly.627If you see `OAuth error: Invalid code. Please make sure the full code was copied`, the login code expired or was truncated during copy-paste.

132 628 

133### Windows: "installMethod is native, but claude command not found"629**Solutions:**

134 630 

135If you see this error after installation, the `claude` command isn't in your PATH. Add it manually:631* Press Enter to retry and complete the login quickly after the browser opens

632* Type `c` to copy the full URL if the browser doesn't open automatically

633* If using a remote/SSH session, the browser may open on the wrong machine. Copy the URL displayed in the terminal and open it in your local browser instead.

136 634 

137<Steps>635### 403 Forbidden after login

138 <Step title="Open Environment Variables">

139 Press `Win + R`, type `sysdm.cpl`, and press Enter. Click **Advanced** → **Environment Variables**.

140 </Step>

141 636 

142 <Step title="Edit User PATH">637If you see `API Error: 403 {"error":{"type":"forbidden","message":"Request not allowed"}}` after logging in:

143 Under "User variables", select **Path** and click **Edit**. Click **New** and add:

144 638 

145 ```639* **Claude Pro/Max users**: verify your subscription is active at [claude.ai/settings](https://claude.ai/settings)

146 %USERPROFILE%\.local\bin640* **Console users**: confirm your account has the "Claude Code" or "Developer" role assigned by your admin

147 ```641* **Behind a proxy**: corporate proxies can interfere with API requests. See [network configuration](/en/network-config) for proxy setup.

148 </Step>

149 642 

150 <Step title="Restart your terminal">643### OAuth login fails in WSL2

151 Close and reopen PowerShell or CMD for changes to take effect.

152 </Step>

153</Steps>

154 644 

155Verify installation:645Browser-based login in WSL2 may fail if WSL can't open your Windows browser. Set the `BROWSER` environment variable:

156 646 

157```bash theme={null}647```bash theme={null}

158claude doctor # Check installation health648export BROWSER="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe"

649claude

159```650```

160 651 

161## Permissions and authentication652Or copy the URL manually: when the login prompt appears, press `c` to copy the OAuth URL, then paste it into your Windows browser.

162 

163### Repeated permission prompts

164 

165If you find yourself repeatedly approving the same commands, you can allow specific tools

166to run without approval using the `/permissions` command. See [Permissions docs](/en/iam#configuring-permissions).

167 

168### Authentication issues

169 653 

170If you're experiencing authentication problems:654### "Not logged in" or token expired

171 655 

1721. Run `/logout` to sign out completely656If Claude Code prompts you to log in again after a session, your OAuth token may have expired.

1732. Close Claude Code

1743. Restart with `claude` and complete the authentication process again

175 657 

176If the browser doesn't open automatically during login, press `c` to copy the OAuth URL to your clipboard, then paste it into your browser manually.658Run `/login` to re-authenticate. If this happens frequently, check that your system clock is accurate, as token validation depends on correct timestamps.

177 

178If problems persist, try:

179 

180```bash theme={null}

181rm -rf ~/.config/claude-code/auth.json

182claude

183```

184 

185This removes your stored authentication information and forces a clean login.

186 659 

187## Configuration file locations660## Configuration file locations

188 661 

189Claude Code stores configuration in several locations:662Claude Code stores configuration in several locations:

190 663 

191| File | Purpose |664| File | Purpose |

192| :---------------------------- | :------------------------------------------------------- |665| :---------------------------- | :----------------------------------------------------------------------------------------------------- |

193| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |666| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |

194| `.claude/settings.json` | Project settings (checked into source control) |667| `.claude/settings.json` | Project settings (checked into source control) |

195| `.claude/settings.local.json` | Local project settings (not committed) |668| `.claude/settings.local.json` | Local project settings (not committed) |

196| `~/.claude.json` | Global state (theme, OAuth, MCP servers) |669| `~/.claude.json` | Global state (theme, OAuth, MCP servers) |

197| `.mcp.json` | Project MCP servers (checked into source control) |670| `.mcp.json` | Project MCP servers (checked into source control) |

198| `managed-settings.json` | [Managed settings](/en/settings#settings-files) |

199| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |671| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |

672| Managed settings | [Managed settings](/en/settings#settings-files) (server-managed, MDM/OS-level policies, or file-based) |

200 673 

201On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`.674On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`.

202 675 

203**Managed file locations:**

204 

205* macOS: `/Library/Application Support/ClaudeCode/`

206* Linux/WSL: `/etc/claude-code/`

207* Windows: `C:\Program Files\ClaudeCode\`

208 

209For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp).676For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp).

210 677 

211### Resetting configuration678### Resetting configuration


228 695 

229## Performance and stability696## Performance and stability

230 697 

698These sections cover issues related to resource usage, responsiveness, and search behavior.

699 

231### High CPU or memory usage700### High CPU or memory usage

232 701 

233Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you're experiencing performance issues:702Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you're experiencing performance issues:


264pacman -S ripgrep733pacman -S ripgrep

265```734```

266 735 

267Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/settings#environment-variables).736Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/env-vars).

268 737 

269### Slow or incomplete search results on WSL738### Slow or incomplete search results on WSL

270 739 

271Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches (but not a complete lack of search functionality) when using Claude Code on WSL.740Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches when using Claude Code on WSL. Search still functions, but returns fewer results than on a native filesystem.

272 741 

273<Note>742<Note>

274 `/doctor` will show Search as OK in this case.743 `/doctor` will show Search as OK in this case.


276 745 

277**Solutions:**746**Solutions:**

278 747 

2791. **Submit more specific searches**: Reduce the number of files searched by specifying directories or file types: "Search for JWT validation logic in the auth-service package" or "Find use of md5 hash in JS files".7481. **Submit more specific searches**: reduce the number of files searched by specifying directories or file types: "Search for JWT validation logic in the auth-service package" or "Find use of md5 hash in JS files".

280 749 

2812. **Move project to Linux filesystem**: If possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`).7502. **Move project to Linux filesystem**: if possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`).

282 751 

2833. **Use native Windows instead**: Consider running Claude Code natively on Windows instead of through WSL, for better file system performance.7523. **Use native Windows instead**: consider running Claude Code natively on Windows instead of through WSL, for better file system performance.

284 753 

285## IDE integration issues754## IDE integration issues

286 755 

756If Claude Code does not connect to your IDE or behaves unexpectedly within an IDE terminal, try the solutions below.

757 

287### JetBrains IDE not detected on WSL2758### JetBrains IDE not detected on WSL2

288 759 

289If you're using Claude Code on WSL2 with JetBrains IDEs and getting "No available IDEs detected" errors, this is likely due to WSL2's networking configuration or Windows Firewall blocking the connection.760If you're using Claude Code on WSL2 with JetBrains IDEs and getting "No available IDEs detected" errors, this is likely due to WSL2's networking configuration or Windows Firewall blocking the connection.


2971. Find your WSL2 IP address:7681. Find your WSL2 IP address:

298 ```bash theme={null}769 ```bash theme={null}

299 wsl hostname -I770 wsl hostname -I

300 # Example output: 172.21.123.456771 # Example output: 172.21.123.45

301 ```772 ```

302 773 

3032. Open PowerShell as Administrator and create a firewall rule:7742. Open PowerShell as Administrator and create a firewall rule:

304 ```powershell theme={null}775 ```powershell theme={null}

305 New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16776 New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16

306 ```777 ```

307 (Adjust the IP range based on your WSL2 subnet from step 1)778 Adjust the IP range based on your WSL2 subnet from step 1.

308 779 

3093. Restart both your IDE and Claude Code7803. Restart both your IDE and Claude Code

310 781 


323 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.794 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.

324</Note>795</Note>

325 796 

326For additional JetBrains configuration tips, see our [JetBrains IDE guide](/en/jetbrains#plugin-settings).797For additional JetBrains configuration tips, see the [JetBrains IDE guide](/en/jetbrains#plugin-settings).

327 798 

328### Reporting Windows IDE integration issues (both native and WSL)799### Report Windows IDE integration issues

329 800 

330If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information:801If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information:

331 802 

332* Environment type: native Windows (Git Bash) or WSL1/WSL2803* Environment type: native Windows (Git Bash) or WSL1/WSL2

333* WSL networking mode (if applicable): NAT or mirrored804* WSL networking mode, if applicable: NAT or mirrored

334* IDE name and version805* IDE name and version

335* Claude Code extension/plugin version806* Claude Code extension/plugin version

336* Shell type: Bash, Zsh, PowerShell, etc.807* Shell type: Bash, Zsh, PowerShell, etc.

337 808 

338### Escape key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals809### Escape key not working in JetBrains IDE terminals

339 810 

340If you're using Claude Code in JetBrains terminals and the `Esc` key doesn't interrupt the agent as expected, this is likely due to a keybinding clash with JetBrains' default shortcuts.811If you're using Claude Code in JetBrains terminals and the `Esc` key doesn't interrupt the agent as expected, this is likely due to a keybinding clash with JetBrains' default shortcuts.

341 812 


362function example() {833function example() {

363 return "hello";834 return "hello";

364}835}

365```836```text

366````837````

367 838 

368Instead of properly tagged blocks like:839Instead of properly tagged blocks like:


372function example() {843function example() {

373 return "hello";844 return "hello";

374}845}

375```846```text

376````847````

377 848 

378**Solutions:**849**Solutions:**

379 850 

3801. **Ask Claude to add language tags**: Request "Add appropriate language tags to all code blocks in this markdown file."8511. **Ask Claude to add language tags**: request "Add appropriate language tags to all code blocks in this markdown file."

381 852 

3822. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See the [markdown formatting hook example](/en/hooks-guide#markdown-formatting-hook) for implementation details.8532. **Use post-processing hooks**: set up automatic formatting hooks to detect and add missing language tags. See [Auto-format code after edits](/en/hooks-guide#auto-format-code-after-edits) for an example of a PostToolUse formatting hook.

383 854 

3843. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.8553. **Manual verification**: after generating markdown files, review them for proper code block formatting and request corrections if needed.

385 856 

386### Inconsistent spacing and formatting857### Inconsistent spacing and formatting

387 858 


389 860 

390**Solutions:**861**Solutions:**

391 862 

3921. **Request formatting corrections**: Ask Claude to "Fix spacing and formatting issues in this markdown file."8631. **Request formatting corrections**: ask Claude to "Fix spacing and formatting issues in this markdown file."

393 864 

3942. **Use formatting tools**: Set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files.8652. **Use formatting tools**: set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files.

395 866 

3963. **Specify formatting preferences**: Include formatting requirements in your prompts or project [memory](/en/memory) files.8673. **Specify formatting preferences**: include formatting requirements in your prompts or project [memory](/en/memory) files.

397 868 

398### Best practices for markdown generation869### Reduce markdown formatting issues

399 870 

400To minimize formatting issues:871To minimize formatting issues:

401 872 

402* **Be explicit in requests**: Ask for "properly formatted markdown with language-tagged code blocks"873* **Be explicit in requests**: ask for "properly formatted markdown with language-tagged code blocks"

403* **Use project conventions**: Document your preferred markdown style in [`CLAUDE.md`](/en/memory)874* **Use project conventions**: document your preferred markdown style in [`CLAUDE.md`](/en/memory)

404* **Set up validation hooks**: Use post-processing hooks to automatically verify and fix common formatting issues875* **Set up validation hooks**: use post-processing hooks to automatically verify and fix common formatting issues

405 876 

406## Getting more help877## Get more help

407 878 

408If you're experiencing issues not covered here:879If you're experiencing issues not covered here:

409 880 


418 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)889 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)

419 * Plugin and agent loading errors890 * Plugin and agent loading errors

4204. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation8914. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation

421 

422 

423 

424> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

vs-code.md +77 −47

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Use Claude Code in VS Code5# Use Claude Code in VS Code

2 6 

3> Install and configure the Claude Code extension for VS Code. Get AI coding assistance with inline diffs, @-mentions, plan review, and keyboard shortcuts.7> Install and configure the Claude Code extension for VS Code. Get AI coding assistance with inline diffs, @-mentions, plan review, and keyboard shortcuts.

4 8 

5<img src="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=300652d5678c63905e6b0ea9e50835f8" alt="VS Code editor with the Claude Code extension panel open on the right side, showing a conversation with Claude" data-og-width="2500" width="2500" data-og-height="1155" height="1155" data-path="images/vs-code-extension-interface.jpg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=280&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=87630c671517a3d52e9aee627041696e 280w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=560&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=716b093879204beec8d952649ef75292 560w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=840&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=c1525d1a01513acd9d83d8b5a8fe2fc8 840w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=1100&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=1d90021d58bbb51f871efec13af955c3 1100w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=1650&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=7babdd25440099886f193cfa99af88ae 1650w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=2500&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=08c92eedfb56fe61a61e480fb63784b6 2500w" />9<img src="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=300652d5678c63905e6b0ea9e50835f8" alt="VS Code editor with the Claude Code extension panel open on the right side, showing a conversation with Claude" width="2500" height="1155" data-path="images/vs-code-extension-interface.jpg" />

6 10 

7The VS Code extension provides a native graphical interface for Claude Code, integrated directly into your IDE. This is the recommended way to use Claude Code in VS Code.11The VS Code extension provides a native graphical interface for Claude Code, integrated directly into your IDE. This is the recommended way to use Claude Code in VS Code.

8 12 


10 14 

11## Prerequisites15## Prerequisites

12 16 

17Before installing, make sure you have:

18 

13* VS Code 1.98.0 or higher19* VS Code 1.98.0 or higher

14* An Anthropic account (you'll sign in when you first open the extension). If you're using a third-party provider like Amazon Bedrock or Google Vertex AI, see [Use third-party providers](#use-third-party-providers) instead.20* An Anthropic account (you'll sign in when you first open the extension). If you're using a third-party provider like Amazon Bedrock or Google Vertex AI, see [Use third-party providers](#use-third-party-providers) instead.

15 21 


34 40 

35<Steps>41<Steps>

36 <Step title="Open the Claude Code panel">42 <Step title="Open the Claude Code panel">

37 Throughout VS Code, the Spark icon indicates Claude Code: <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=a734d84e785140016672f08e0abb236c" alt="Spark icon" style={{display: "inline", height: "0.85em", verticalAlign: "middle"}} data-og-width="16" width="16" data-og-height="16" height="16" data-path="images/vs-code-spark-icon.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=280&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=9a45aad9a84b9fa1701ac99a1f9aa4e9 280w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=560&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=3f4cb9254c4d4e93989c4b6bf9292f4b 560w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=840&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=e75ccc9faa3e572db8f291ceb65bb264 840w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=1100&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=f147bd81a381a62539a4ce361fac41c7 1100w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=1650&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=78fe68efaee5d6e844bbacab1b442ed5 1650w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=2500&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=efb8dbe1dfa722d094edc6ad2ad4bedb 2500w" />43 Throughout VS Code, the Spark icon indicates Claude Code: <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/vs-code-spark-icon.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=3ca45e00deadec8c8f4b4f807da94505" alt="Spark icon" style={{display: "inline", height: "0.85em", verticalAlign: "middle"}} width="16" height="16" data-path="images/vs-code-spark-icon.svg" />

38 44 

39 The quickest way to open Claude is to click the Spark icon in the **Editor Toolbar** (top-right corner of the editor). The icon only appears when you have a file open.45 The quickest way to open Claude is to click the Spark icon in the **Editor Toolbar** (top-right corner of the editor). The icon only appears when you have a file open.

40 46 

41 <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=eb4540325d94664c51776dbbfec4cf02" alt="VS Code editor showing the Spark icon in the Editor Toolbar" data-og-width="2796" width="2796" data-og-height="734" height="734" data-path="images/vs-code-editor-icon.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=280&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=56f218d5464359d6480cfe23f70a923e 280w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=560&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=344a8db024b196c795a80dc85cacb8d1 560w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=840&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=f30bf834ee0625b2a4a635d552d87163 840w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=1100&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=81fdf984840e43a9f08ae42729d1484d 1100w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=1650&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=8b60fb32de54717093d512afaa99785c 1650w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=2500&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=893e6bda8f2e9d42c8a294d394f0b736 2500w" />47 <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=eb4540325d94664c51776dbbfec4cf02" alt="VS Code editor showing the Spark icon in the Editor Toolbar" width="2796" height="734" data-path="images/vs-code-editor-icon.png" />

42 48 

43 Other ways to open Claude Code:49 Other ways to open Claude Code:

44 50 

51 * **Activity Bar**: click the Spark icon in the left sidebar to open the sessions list. Click any session to open it as a full editor tab, or start a new one. This icon is always visible in the Activity Bar.

45 * **Command Palette**: `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux), type "Claude Code", and select an option like "Open in New Tab"52 * **Command Palette**: `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux), type "Claude Code", and select an option like "Open in New Tab"

46 * **Status Bar**: Click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open.53 * **Status Bar**: click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open.

54 

55 When you first open the panel, a **Learn Claude Code** checklist appears. Work through each item by clicking **Show me**, or dismiss it with the X. To reopen it later, uncheck **Hide Onboarding** in VS Code settings under Extensions → Claude Code.

47 56 

48 You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.57 You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.

49 </Step>58 </Step>


55 64 

56 Here's an example of asking about a particular line in a file:65 Here's an example of asking about a particular line in a file:

57 66 

58 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ede3ed8d8d5f940e01c5de636d009cfd" alt="VS Code editor with lines 2-3 selected in a Python file, and the Claude Code panel showing a question about those lines with an @-mention reference" data-og-width="3288" width="3288" data-og-height="1876" height="1876" data-path="images/vs-code-send-prompt.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=280&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=f40bde7b2c245fe8f0f5b784e8106492 280w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=560&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=fad66a27a9a6faa23b05370aa4f398b2 560w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=840&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=4539c8a3823ca80a5c8771f6c088ce9e 840w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=1100&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=fae8ebf300c7853409a562ffa46d9c71 1100w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=1650&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=22e4462bb8cf0c0ca20f8102bc4c971a 1650w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=2500&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=739bfd045f70fe7be1a109a53494590e 2500w" />67 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ede3ed8d8d5f940e01c5de636d009cfd" alt="VS Code editor with lines 2-3 selected in a Python file, and the Claude Code panel showing a question about those lines with an @-mention reference" width="3288" height="1876" data-path="images/vs-code-send-prompt.png" />

59 </Step>68 </Step>

60 69 

61 <Step title="Review changes">70 <Step title="Review changes">

62 When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead.71 When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead.

63 72 

64 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" data-og-width="3292" width="3292" data-og-height="1876" height="1876" data-path="images/vs-code-edits.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=280&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=cb5d41b81087f79b842a56b5a3304660 280w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=560&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=90bb691960decdc06393c3c21cd62c75 560w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=840&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=9a11bf878ba619e850380904ff4f38e8 840w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=1100&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=6dddbf596b4f69ec6245bdc5eb6dd487 1100w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=1650&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ef2713b8cbfd2cee97af817d813d64c7 1650w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=2500&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=1f7e1c52919cdfddf295f32a2ec7ae59 2500w" />73 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" width="3292" height="1876" data-path="images/vs-code-edits.png" />

65 </Step>74 </Step>

66</Steps>75</Steps>

67 76 

68For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows).77For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows).

69 78 

70<Tip>79<Tip>

71 The extension includes two built-in tutorials:80 Run "Claude Code: Open Walkthrough" from the Command Palette for a guided tour of the basics.

72 

73 * **VS Code walkthrough**: Run "Claude Code: Open Walkthrough" from the Command Palette for a guided tour of the basics.

74 * **Interactive checklist**: Click the graduation cap icon in the Claude panel header to work through features like writing code, using Plan mode, and setting up rules.

75</Tip>81</Tip>

76 82 

77## Use the prompt box83## Use the prompt box

78 84 

79The prompt box supports several features:85The prompt box supports several features:

80 86 

81* **Permission modes**: Click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`.87* **Permission modes**: click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. VS Code automatically opens the plan as a full markdown document where you can add inline comments to give feedback before Claude begins. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`.

82* **Command menu**: Click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, and viewing plan usage (`/usage`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal.88* **Command menu**: click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, and viewing plan usage (`/usage`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal.

83* **Context indicator**: The prompt box shows how much of Claude's context window you're using. Claude automatically compacts when needed, or you can run `/compact` manually.89* **Context indicator**: the prompt box shows how much of Claude's context window you're using. Claude automatically compacts when needed, or you can run `/compact` manually.

84* **Extended thinking**: Lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). See [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) for details.90* **Extended thinking**: lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). See [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) for details.

85* **Multi-line input**: Press `Shift+Enter` to add a new line without sending.91* **Multi-line input**: press `Shift+Enter` to add a new line without sending. This also works in the "Other" free-text input of question dialogs.

86 92 

87### Reference files and folders93### Reference files and folders

88 94 

89Use @-mentions to give Claude context about specific files or folders. When you type `@` followed by a file or folder name, Claude reads that content and can answer questions about it or make changes to it. Claude Code supports fuzzy matching, so you can type partial names to find what you need:95Use @-mentions to give Claude context about specific files or folders. When you type `@` followed by a file or folder name, Claude reads that content and can answer questions about it or make changes to it. Claude Code supports fuzzy matching, so you can type partial names to find what you need:

90 96 

91```97```text theme={null}

92> Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.)98> Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.)

93> What's in @src/components/ (include a trailing slash for folders)99> What's in @src/components/ (include a trailing slash for folders)

94```100```

95 101 

102For large PDFs, you can ask Claude to read specific pages instead of the whole file: a single page, a range like pages 1-10, or an open-ended range like page 3 onward.

103 

96When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to insert an @-mention with the file path and line numbers (e.g., `@app.ts#5-10`). Click the selection indicator to toggle whether Claude can see your highlighted text - the eye-slash icon means the selection is hidden from Claude.104When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to insert an @-mention with the file path and line numbers (e.g., `@app.ts#5-10`). Click the selection indicator to toggle whether Claude can see your highlighted text - the eye-slash icon means the selection is hidden from Claude.

97 105 

98You can also hold `Shift` while dragging files into the prompt box to add them as attachments. Click the X on any attachment to remove it from context.106You can also hold `Shift` while dragging files into the prompt box to add them as attachments. Click the X on any attachment to remove it from context.

99 107 

100### Resume past conversations108### Resume past conversations

101 109 

102Click the dropdown at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. For more on resuming sessions, see [Common workflows](/en/common-workflows#resume-previous-conversations).110Click the dropdown at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. Hover over a session to reveal rename and remove actions: rename to give it a descriptive title, or remove to delete it from the list. For more on resuming sessions, see [Common workflows](/en/common-workflows#resume-previous-conversations).

103 111 

104### Resume remote sessions from Claude.ai112### Resume remote sessions from Claude.ai

105 113 


131 139 

132You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel's tab or title bar and drag it to:140You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel's tab or title bar and drag it to:

133 141 

134* **Secondary sidebar**: The right side of the window. Keeps Claude visible while you code.142* **Secondary sidebar**: the right side of the window. Keeps Claude visible while you code.

135* **Primary sidebar**: The left sidebar with icons for Explorer, Search, etc.143* **Primary sidebar**: the left sidebar with icons for Explorer, Search, etc.

136* **Editor area**: Opens Claude as a tab alongside your files. Useful for side tasks.144* **Editor area**: opens Claude as a tab alongside your files. Useful for side tasks.

137 145 

138<Tip>146<Tip>

139 Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. Note that the Spark icon only appears in the Activity Bar when the Claude panel is docked to the left. Since Claude defaults to the right side, use the Editor Toolbar icon to open Claude.147 Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. The Activity Bar sessions list icon is separate from the Claude panel: the sessions list is always visible in the Activity Bar, while the Claude panel icon only appears there when the panel is docked to the left sidebar.

140</Tip>148</Tip>

141 149 

142### Run multiple conversations150### Run multiple conversations


168 176 

169When you install a plugin, choose the installation scope:177When you install a plugin, choose the installation scope:

170 178 

171* **Install for you**: Available in all your projects (user scope)179* **Install for you**: available in all your projects (user scope)

172* **Install for this project**: Shared with project collaborators (project scope)180* **Install for this project**: shared with project collaborators (project scope)

173* **Install locally**: Only for you, only in this repository (local scope)181* **Install locally**: only for you, only in this repository (local scope)

174 182 

175### Manage marketplaces183### Manage marketplaces

176 184 


188 196 

189For more about the plugin system, see [Plugins](/en/plugins) and [Plugin marketplaces](/en/plugin-marketplaces).197For more about the plugin system, see [Plugins](/en/plugins) and [Plugin marketplaces](/en/plugin-marketplaces).

190 198 

199## Automate browser tasks with Chrome

200 

201Connect Claude to your Chrome browser to test web apps, debug with console logs, and automate browser workflows without leaving VS Code. This requires the [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher.

202 

203Type `@browser` in the prompt box followed by what you want Claude to do:

204 

205```text theme={null}

206@browser go to localhost:3000 and check the console for errors

207```

208 

209You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content.

210 

211Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into.

212 

213For setup instructions, the full list of capabilities, and troubleshooting, see [Use Claude Code with Chrome](/en/chrome).

214 

191## VS Code commands and shortcuts215## VS Code commands and shortcuts

192 216 

193Open the Command Palette (`Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows/Linux) and type "Claude Code" to see all available VS Code commands for the Claude Code extension.217Open the Command Palette (`Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows/Linux) and type "Claude Code" to see all available VS Code commands for the Claude Code extension.


214 238 

215The extension has two types of settings:239The extension has two types of settings:

216 240 

217* **Extension settings** in VS Code: Control the extension's behavior within VS Code. Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions → Claude Code. You can also type `/` and select **General Config** to open settings.241* **Extension settings** in VS Code: control the extension's behavior within VS Code. Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions → Claude Code. You can also type `/` and select **General Config** to open settings.

218* **Claude Code settings** in `~/.claude/settings.json`: Shared between the extension and CLI. Use for allowed commands, environment variables, hooks, and MCP servers. See [Settings](/en/settings) for details.242* **Claude Code settings** in `~/.claude/settings.json`: shared between the extension and CLI. Use for allowed commands, environment variables, hooks, and MCP servers. See [Settings](/en/settings) for details.

243 

244<Tip>

245 Add `"$schema": "https://json.schemastore.org/claude-code-settings.json"` to your `settings.json` to get autocomplete and inline validation for all available settings directly in VS Code.

246</Tip>

219 247 

220### Extension settings248### Extension settings

221 249 


240Claude Code is available as both a VS Code extension (graphical panel) and a CLI (command-line interface in the terminal). Some features are only available in the CLI. If you need a CLI-only feature, run `claude` in VS Code's integrated terminal.268Claude Code is available as both a VS Code extension (graphical panel) and a CLI (command-line interface in the terminal). Some features are only available in the CLI. If you need a CLI-only feature, run `claude` in VS Code's integrated terminal.

241 269 

242| Feature | CLI | VS Code Extension |270| Feature | CLI | VS Code Extension |

243| ------------------- | --------------------------------------------- | ---------------------------------------- |271| ------------------- | ------------------- | ------------------------------------------------------------------------------------ |

244| Commands and skills | [All](/en/interactive-mode#built-in-commands) | Subset (type `/` to see available) |272| Commands and skills | [All](/en/commands) | Subset (type `/` to see available) |

245| MCP server config | Yes | No (configure via CLI, use in extension) |273| MCP server config | Yes | Partial (add servers via CLI; manage existing servers with `/mcp` in the chat panel) |

246| Checkpoints | Yes | Coming soon |274| Checkpoints | Yes | Yes |

247| `!` bash shortcut | Yes | No |275| `!` bash shortcut | Yes | No |

248| Tab completion | Yes | No |276| Tab completion | Yes | No |

249 277 

278### Rewind with checkpoints

279 

280The VS Code extension supports checkpoints, which track Claude's file edits and let you rewind to a previous state. Hover over any message to reveal the rewind button, then choose from three options:

281 

282* **Fork conversation from here**: start a new conversation branch from this message while keeping all code changes intact

283* **Rewind code to here**: revert file changes back to this point in the conversation while keeping the full conversation history

284* **Fork conversation and rewind code**: start a new conversation branch and revert file changes to this point

285 

286For full details on how checkpoints work and their limitations, see [Checkpointing](/en/checkpointing).

287 

250### Run CLI in VS Code288### Run CLI in VS Code

251 289 

252To use the CLI while staying in VS Code, open the integrated terminal (`` Ctrl+` `` on Windows/Linux or `` Cmd+` `` on Mac) and run `claude`. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing.290To use the CLI while staying in VS Code, open the integrated terminal (`` Ctrl+` `` on Windows/Linux or `` Cmd+` `` on Mac) and run `claude`. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing.


267 305 

268### Connect to external tools with MCP306### Connect to external tools with MCP

269 307 

270MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs. Configure them via CLI, then use them in both extension and CLI.308MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs.

271 309 

272To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run:310To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run:

273 311 


275claude mcp add --transport http github https://api.githubcopilot.com/mcp/313claude mcp add --transport http github https://api.githubcopilot.com/mcp/

276```314```

277 315 

278Once configured, ask Claude to use the tools (e.g., "Review PR #456"). Some servers require authentication: run `claude` in the terminal, then type `/mcp` to authenticate. See the [MCP documentation](/en/mcp) for available servers.316Once configured, ask Claude to use the tools (e.g., "Review PR #456").

317 

318To manage MCP servers without leaving VS Code, type `/mcp` in the chat panel. The MCP management dialog lets you enable or disable servers, reconnect to a server, and manage OAuth authentication. See the [MCP documentation](/en/mcp) for available servers.

279 319 

280## Work with git320## Work with git

281 321 


285 325 

286Claude can stage changes, write commit messages, and create pull requests based on your work:326Claude can stage changes, write commit messages, and create pull requests based on your work:

287 327 

288```328```text theme={null}

289> commit my changes with a descriptive message329> commit my changes with a descriptive message

290> create a pr for this feature330> create a pr for this feature

291> summarize the changes I've made to the auth module331> summarize the changes I've made to the auth module


295 335 

296### Use git worktrees for parallel tasks336### Use git worktrees for parallel tasks

297 337 

298Git worktrees allow multiple Claude Code sessions to work on separate branches simultaneously, each with isolated files:338Use the `--worktree` (`-w`) flag to start Claude in an isolated worktree with its own files and branch:

299 339 

300```bash theme={null}340```bash theme={null}

301# Create a worktree for a new feature341claude --worktree feature-auth

302git worktree add ../project-feature-a -b feature-a

303 

304# Run Claude Code in each worktree

305cd ../project-feature-a && claude

306```342```

307 343 

308Each worktree maintains independent file state while sharing git history. This prevents Claude instances from interfering with each other when working on different tasks.344Each worktree maintains independent file state while sharing git history. This prevents Claude instances from interfering with each other when working on different tasks. For more details, see [Run parallel sessions with Git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees).

309 

310For detailed git workflows including PR reviews and branch management, see [Common workflows](/en/common-workflows#create-pull-requests).

311 345 

312## Use third-party providers346## Use third-party providers

313 347 


392Now that you have Claude Code set up in VS Code:426Now that you have Claude Code set up in VS Code:

393 427 

394* [Explore common workflows](/en/common-workflows) to get the most out of Claude Code428* [Explore common workflows](/en/common-workflows) to get the most out of Claude Code

395* [Set up MCP servers](/en/mcp) to extend Claude's capabilities with external tools. Configure servers using the CLI, then use them in the extension.429* [Set up MCP servers](/en/mcp) to extend Claude's capabilities with external tools. Add servers using the CLI, then manage them with `/mcp` in the chat panel.

396* [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.430* [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.

397 

398 

399 

400> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

zero-data-retention.md +66 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Zero data retention

6 

7> Learn about Zero Data Retention (ZDR) for Claude Code on Claude for Enterprise, including scope, disabled features, and how to request enablement.

8 

9Zero Data Retention (ZDR) is available for Claude Code when used through Claude for Enterprise. When ZDR is enabled, prompts and model responses generated during Claude Code sessions are processed in real time and not stored by Anthropic after the response is returned, except where needed to comply with law or combat misuse.

10 

11ZDR on Claude for Enterprise gives enterprise customers the ability to use Claude Code with zero data retention and access administrative capabilities:

12 

13* Cost controls per user

14* [Analytics](/en/analytics) dashboard

15* [Server-managed settings](/en/server-managed-settings)

16* Audit logs

17 

18ZDR for Claude Code on Claude for Enterprise applies only to Anthropic's direct platform. For Claude deployments on AWS Bedrock, Google Vertex AI, or Microsoft Foundry, refer to those platforms' data retention policies.

19 

20## ZDR scope

21 

22ZDR covers Claude Code inference on Claude for Enterprise.

23 

24<Warning>

25 ZDR is enabled on a per-organization basis. Each new organization requires ZDR to be enabled separately by your Anthropic account team. ZDR does not automatically apply to new organizations created under the same account. Contact your account team to enable ZDR for any new organizations.

26</Warning>

27 

28### What ZDR covers

29 

30ZDR covers model inference calls made through Claude Code on Claude for Enterprise. When you use Claude Code in your terminal, the prompts you send and the responses Claude generates are not retained by Anthropic. This applies regardless of which Claude model is used.

31 

32### What ZDR does not cover

33 

34ZDR does not extend to the following, even for organizations with ZDR enabled. These features follow [standard data retention policies](/en/data-usage#data-retention):

35 

36| Feature | Details |

37| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

38| Chat on claude.ai | Chat conversations through the Claude for Enterprise web interface are not covered by ZDR. |

39| Cowork | Cowork sessions are not covered by ZDR. |

40| Claude Code Analytics | Does not store prompts or model responses, but collects productivity metadata such as account emails and usage statistics. Contribution metrics are not available for ZDR organizations; the [analytics dashboard](/en/analytics) shows usage metrics only. |

41| User and seat management | Administrative data such as account emails and seat assignments is retained under standard policies. |

42| Third-party integrations | Data processed by third-party tools, MCP servers, or other external integrations is not covered by ZDR. Review those services' data handling practices independently. |

43 

44## Features disabled under ZDR

45 

46When ZDR is enabled for a Claude Code organization on Claude for Enterprise, certain features that require storing prompts or completions are automatically disabled at the backend level:

47 

48| Feature | Reason |

49| ------------------------------------------------------------------- | ----------------------------------------------------------------------- |

50| [Claude Code on the Web](/en/claude-code-on-the-web) | Requires server-side storage of conversation history. |

51| [Remote sessions](/en/desktop#remote-sessions) from the Desktop app | Requires persistent session data that includes prompts and completions. |

52| Feedback submission (`/feedback`) | Submitting feedback sends conversation data to Anthropic. |

53 

54These features are blocked in the backend regardless of client-side display. If you see a disabled feature in the Claude Code terminal during startup, attempting to use it returns an error indicating the organization's policies do not allow that action.

55 

56Future features may also be disabled if they require storing prompts or completions.

57 

58## Data retention for policy violations

59 

60Even with ZDR enabled, Anthropic may retain data where required by law or to address Usage Policy violations. If a session is flagged for a policy violation, Anthropic may retain the associated inputs and outputs for up to 2 years, consistent with Anthropic's standard ZDR policy.

61 

62## Request ZDR

63 

64To request ZDR for Claude Code on Claude for Enterprise, contact your Anthropic account team. Your account team will submit the request internally, and Anthropic will review and enable ZDR on your organization after confirming eligibility. All enablement actions are audit-logged.

65 

66If you are currently using ZDR for Claude Code via pay-as-you-go API keys, you can transition to Claude for Enterprise to gain access to administrative features while maintaining ZDR for Claude Code. Contact your account team to coordinate the migration.