SpyBara
Go Premium Account
2026
22 Jan 2026, 15:05
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
20 Feb 2026, 06:14
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 18:02 Sun 1 21:03 Tue 3 03:46 Tue 3 09:10 Tue 3 18:14 Tue 3 21:08 Wed 4 00:06 Wed 4 03:45 Wed 4 18:11 Wed 4 21:07 Thu 5 00:07 Thu 5 03:46 Thu 5 18:13 Thu 5 21:06 Fri 6 00:05 Fri 6 21:06 Sat 7 03:43 Sat 7 18:03 Sat 7 21:05 Mon 9 00:08 Mon 9 15:17 Tue 10 00:11 Tue 10 03:56 Tue 10 21:13 Wed 11 00:11 Wed 11 21:10 Thu 12 00:06 Fri 13 21:09 Sat 14 03:44 Mon 16 21:05 Tue 17 00:08 Tue 17 21:08 Wed 18 03:48 Thu 19 00:08 Thu 19 03:48 Thu 19 21:06 Fri 20 00:07 Fri 20 06:14 Fri 20 21:03 Sat 21 06:08 Sat 21 18:03 Mon 23 21:13 Tue 24 18:15 Tue 24 21:08 Wed 25 00:09 Wed 25 03:47 Thu 26 00:07 Thu 26 06:17 Thu 26 09:14 Thu 26 18:12 Thu 26 21:08 Fri 27 00:08 Fri 27 06:13 Fri 27 09:11 Fri 27 18:07 Fri 27 21:05 Sat 28 00:05 Sat 28 21:01

agent-teams.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# 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 

17This page covers:

18 

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

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

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

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

23 

24## When to use agent teams

25 

26Agent 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:

27 

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

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

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

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

32 

33Agent 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.

34 

35### Compare with subagents

36 

37Both 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:

38 

39<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.">

40 <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." data-og-width="4245" width="4245" data-og-height="1615" height="1615" data-path="images/subagents-vs-agent-teams-light.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?w=280&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=a2cfe413c2084b477be40ac8723d9d40 280w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?w=560&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=c642c09a4c211b10b35eee7d7d0d149f 560w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?w=840&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=40d286f77c8a4075346b4fcaa2b36248 840w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?w=1100&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=923986caa23c0ef2c27d7e45f4dce6d1 1100w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?w=1650&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=17a730a070db6d71d029a98b074c68e8 1650w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-light.png?w=2500&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=e402533fc9e8b5e8d26a835cc4aa1742 2500w" />

41 

42 <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." data-og-width="4245" width="4245" data-og-height="1615" height="1615" data-path="images/subagents-vs-agent-teams-dark.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?w=280&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=06ca5b18b232855acc488357d8d01fa7 280w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?w=560&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=3d34daee83994781eb74b74d1ed511c4 560w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?w=840&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=82ea35ac837de7d674002de69689b9cf 840w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?w=1100&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=3653085214a9fc65d1f589044894a296 1100w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?w=1650&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=8e74b42694e428570e876d34f29e6ad6 1650w, https://mintcdn.com/claude-code/nsvRFSDNfpSU5nT7/images/subagents-vs-agent-teams-dark.png?w=2500&fit=max&auto=format&n=nsvRFSDNfpSU5nT7&q=85&s=3be00c56c6a0dcccbe15640020be0128 2500w" />

43</Frame>

44 

45| | Subagents | Agent teams |

46| :---------------- | :----------------------------------------------- | :-------------------------------------------------- |

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

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

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

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

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

52 

53Use 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.

54 

55## Enable agent teams

56 

57Agent 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):

58 

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

60{

61 "env": {

62 "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"

63 }

64}

65```

66 

67## Start your first agent team

68 

69After 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.

70 

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

72 

73```

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

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

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

77```

78 

79From 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.

80 

81The 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.

82 

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

84 

85## Control your agent team

86 

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

88 

89### Choose a display mode

90 

91Agent teams support two display modes:

92 

93* **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.

94* **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.

95 

96<Note>

97 `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`.

98</Note>

99 

100The 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):

101 

102```json theme={null}

103{

104 "teammateMode": "in-process"

105}

106```

107 

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

109 

110```bash theme={null}

111claude --teammate-mode in-process

112```

113 

114Split-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:

115 

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

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

118 

119### Specify teammates and models

120 

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

122 

123```

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

125Use Sonnet for each teammate.

126```

127 

128### Require plan approval for teammates

129 

130For 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:

131 

132```

133Spawn an architect teammate to refactor the authentication module.

134Require plan approval before they make any changes.

135```

136 

137When 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.

138 

139The 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."

140 

141### Talk to teammates directly

142 

143Each 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.

144 

145* **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.

146* **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.

147 

148### Assign and claim tasks

149 

150The 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.

151 

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

153 

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

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

156 

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

158 

159### Shut down teammates

160 

161To gracefully end a teammate's session:

162 

163```

164Ask the researcher teammate to shut down

165```

166 

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

168 

169### Clean up the team

170 

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

172 

173```

174Clean up the team

175```

176 

177This 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.

178 

179<Warning>

180 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.

181</Warning>

182 

183### Enforce quality gates with hooks

184 

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

186 

187* [`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.

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

189 

190## How agent teams work

191 

192This 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.

193 

194### How Claude starts agent teams

195 

196There are two ways agent teams get started:

197 

198* **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.

199* **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.

200 

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

202 

203### Architecture

204 

205An agent team consists of:

206 

207| Component | Role |

208| :------------ | :----------------------------------------------------------------------------------------- |

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

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

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

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

213 

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

215 

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

217 

218Teams and tasks are stored locally:

219 

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

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

222 

223The 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.

224 

225### Permissions

226 

227Teammates 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.

228 

229### Context and communication

230 

231Each 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.

232 

233**How teammates share information:**

234 

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

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

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

238 

239**Teammate messaging:**

240 

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

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

243 

244### Token usage

245 

246Agent 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.

247 

248## Use case examples

249 

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

251 

252### Run a parallel code review

253 

254A 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:

255 

256```

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

258- One focused on security implications

259- One checking performance impact

260- One validating test coverage

261Have them each review and report findings.

262```

263 

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

265 

266### Investigate with competing hypotheses

267 

268When 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'.

269 

270```

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

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

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

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

275```

276 

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

278 

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

280 

281## Best practices

282 

283### Give teammates enough context

284 

285Teammates 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:

286 

287```

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

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

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

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

292```

293 

294### Size tasks appropriately

295 

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

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

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

299 

300<Tip>

301 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.

302</Tip>

303 

304### Wait for teammates to finish

305 

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

307 

308```

309Wait for your teammates to complete their tasks before proceeding

310```

311 

312### Start with research and review

313 

314If 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.

315 

316### Avoid file conflicts

317 

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

319 

320### Monitor and steer

321 

322Check 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.

323 

324## Troubleshooting

325 

326### Teammates not appearing

327 

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

329 

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

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

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

333 ```bash theme={null}

334 which tmux

335 ```

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

337 

338### Too many permission prompts

339 

340Teammate 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.

341 

342### Teammates stopping on errors

343 

344Teammates 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:

345 

346* Give them additional instructions directly

347* Spawn a replacement teammate to continue the work

348 

349### Lead shuts down before work is done

350 

351The 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.

352 

353### Orphaned tmux sessions

354 

355If 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:

356 

357```bash theme={null}

358tmux ls

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

360```

361 

362## Limitations

363 

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

365 

366* **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.

367* **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.

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

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

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

371* **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.

372* **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.

373* **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.

374 

375<Tip>

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

377</Tip>

378 

379## Next steps

380 

381Explore related approaches for parallel work and delegation:

382 

383* **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

384* **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

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

amazon-bedrock.md +31 −33

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 

150These are the recommended token settings for Claude Code with Amazon Bedrock:

151 

152```bash theme={null}

153# Recommended output token settings for Bedrock

154export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096

155export MAX_THINKING_TOKENS=1024

156```

157 

158**Why these values:**

159 

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.

161 

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.

163 165 

164## IAM configuration166## IAM configuration

165 167 


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

207 209 

208<Note>210<Note>

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

210</Note>212</Note>

211 213 

212## AWS Guardrails214## AWS Guardrails


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

244* [Bedrock inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html)246* [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)247* [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/data-usage#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 +104 −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> Learn how to configure user authentication and credential management for Claude Code in your organization.

8 

9## Authentication methods

10 

11Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of these ways:

12 

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

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

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

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

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

18 

19### Claude for Teams or Enterprise

20 

21[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.

22 

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

24* **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.

25 

26<Steps>

27 <Step title="Subscribe">

28 Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales).

29 </Step>

30 

31 <Step title="Invite team members">

32 Invite team members from the admin dashboard.

33 </Step>

34 

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

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

37 </Step>

38</Steps>

39 

40### Claude Console authentication

41 

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

43 

44<Steps>

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

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

47 </Step>

48 

49 <Step title="Add users">

50 You can add users through either method:

51 

52 * Bulk invite users from within the Console (Console -> Settings -> Members -> Invite)

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

54 </Step>

55 

56 <Step title="Assign roles">

57 When inviting users, assign one of:

58 

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

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

61 </Step>

62 

63 <Step title="Users complete setup">

64 Each invited user needs to:

65 

66 * Accept the Console invite

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

68 * [Install Claude Code](/en/setup#installation)

69 * Log in with Console account credentials

70 </Step>

71</Steps>

72 

73### Cloud provider authentication

74 

75For teams using Amazon Bedrock, Google Vertex AI, or Microsoft Azure:

76 

77<Steps>

78 <Step title="Follow provider setup">

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

80 </Step>

81 

82 <Step title="Distribute configuration">

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

84 </Step>

85 

86 <Step title="Install Claude Code">

87 Users can [install Claude Code](/en/setup#installation).

88 </Step>

89</Steps>

90 

91## Credential management

92 

93Claude Code securely manages your authentication credentials:

94 

95* **Storage location**: on macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain.

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

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

98* **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.

99 

100## See also

101 

102* [Permissions](/en/permissions): configure what Claude Code can access and do

103* [Settings](/en/settings): complete configuration reference

104* [Security](/en/security): security safeguards and best practices

best-practices.md +16 −12

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">


316 Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.322 Run `/plugin` to browse the marketplace. Plugins add skills, tools, and integrations without configuration.

317</Tip>323</Tip>

318 324 

319[Plugins](/en/plugins) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic.325[Plugins](/en/plugins) bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a [code intelligence plugin](/en/discover-plugins#code-intelligence) to give Claude precise symbol navigation and automatic error detection after edits.

320 326 

321For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).327For guidance on choosing between skills, subagents, hooks, and MCP, see [Extend Claude Code](/en/features-overview#match-features-to-your-goal).

322 328 


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 


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

398 405 

399### Use subagents for investigation406### Use subagents for investigation


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

424</Tip>431</Tip>

425 432 

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.433Claude 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 434 

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.435Instead 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 436 


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

480</Tip>487</Tip>

481 488 

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

483 490 

484* [Claude Desktop](/en/desktop): Manage multiple local sessions visually. Each session gets its own isolated worktree.491* [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.492* [Claude Code on the web](/en/claude-code-on-the-web): Run on Anthropic's secure cloud infrastructure in isolated VMs.

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

486 494 

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.495Beyond 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 496 


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

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

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

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

517 done525 done

518 ```526 ```

519 </Step>527 </Step>


589 Store project conventions and persistent context597 Store project conventions and persistent context

590 </Card>598 </Card>

591</CardGroup>599</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 +33 −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# 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 


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/interactive-mode#built-in-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


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 


135| Branch available | The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out. |139| 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. |140| Same account | You must be authenticated to the same Claude.ai account used in the web session. |

137 141 

142### Sharing sessions

143 

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

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

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

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

148 

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

150 

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

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

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

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

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

156sessions are automatically shared with Team visibility.

157 

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

159 

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

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

162into claude.ai.

163 

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

165code and credentials from private GitHub repositories. Repository access

166verification is not enabled by default.

167 

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

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

170 

138## Cloud environment171## Cloud environment

139 172 

140### Default image173### Default image


212 245 

213### Dependency management246### Dependency management

214 247 

215Configure automatic dependency installation using [SessionStart hooks](/en/hooks#sessionstart). This can be configured in your repository's `.claude/settings.json` file:248Custom environment images and snapshots are not yet supported. As a workaround, you can use [SessionStart hooks](/en/hooks#sessionstart) to install packages when a session starts. This approach has [known limitations](#dependency-management-limitations).

249 

250To configure automatic dependency installation, add a SessionStart hook to your repository's `.claude/settings.json` file:

216 251 

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

218{253{


236 271 

237```bash theme={null}272```bash theme={null}

238#!/bin/bash273#!/bin/bash

239npm install

240pip install -r requirements.txt

241exit 0

242```

243 

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

245 274 

246#### Local vs remote execution275# Only run in remote environments

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}

251#!/bin/bash

252 

253# Example: Only run in remote environments

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

255 exit 0277 exit 0

256fi278fi

257 279 

258npm install280npm install

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

282exit 0

260```283```

261 284 

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

286 

287#### Persist environment variables

263 288 

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.289SessionStart 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.

290 

291#### Dependency management limitations

292 

293* **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.

294* **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.

295* **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.

296* **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 297 

266## Network access and security298## Network access and security

267 299 


297 329 

298* api.anthropic.com330* api.anthropic.com

299* statsig.anthropic.com331* statsig.anthropic.com

332* platform.claude.com

333* code.claude.com

300* claude.ai334* claude.ai

301 335 

302#### Version Control336#### Version Control


304* github.com338* github.com

305* [www.github.com](http://www.github.com)339* [www.github.com](http://www.github.com)

306* api.github.com340* api.github.com

341* npm.pkg.github.com

307* raw\.githubusercontent.com342* raw\.githubusercontent.com

343* pkg-npm.githubusercontent.com

308* objects.githubusercontent.com344* objects.githubusercontent.com

309* codeload.github.com345* codeload.github.com

310* avatars.githubusercontent.com346* avatars.githubusercontent.com


326* [www.docker.com](http://www.docker.com)362* [www.docker.com](http://www.docker.com)

327* production.cloudflare.docker.com363* production.cloudflare.docker.com

328* download.docker.com364* download.docker.com

365* gcr.io

329* \*.gcr.io366* \*.gcr.io

330* ghcr.io367* ghcr.io

331* mcr.microsoft.com368* mcr.microsoft.com


402 439 

403* crates.io440* crates.io

404* [www.crates.io](http://www.crates.io)441* [www.crates.io](http://www.crates.io)

442* index.crates.io

405* static.crates.io443* static.crates.io

406* rustup.rs444* rustup.rs

407* static.rust-lang.org445* static.rust-lang.org


427* gradle.org465* gradle.org

428* [www.gradle.org](http://www.gradle.org)466* [www.gradle.org](http://www.gradle.org)

429* services.gradle.org467* services.gradle.org

468* plugins.gradle.org

469* kotlin.org

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

430* spring.io471* spring.io

431* repo.spring.io472* repo.spring.io

432 473 


500* statsig.com541* statsig.com

501* [www.statsig.com](http://www.statsig.com)542* [www.statsig.com](http://www.statsig.com)

502* api.statsig.com543* api.statsig.com

544* sentry.io

503* \*.sentry.io545* \*.sentry.io

546* http-intake.logs.datadoghq.com

547* \*.datadoghq.com

548* \*.datadoghq.eu

504 549 

505#### Content Delivery & Mirrors550#### Content Delivery & Mirrors

506 551 

552* sourceforge.net

507* \*.sourceforge.net553* \*.sourceforge.net

508* packagecloud.io554* packagecloud.io

509* \*.packagecloud.io555* \*.packagecloud.io


515* json.schemastore.org561* json.schemastore.org

516* [www.schemastore.org](http://www.schemastore.org)562* [www.schemastore.org](http://www.schemastore.org)

517 563 

564#### Model Context Protocol

565 

566* \*.modelcontextprotocol.io

567 

518<Note>568<Note>

519 Domains marked with `*` indicate wildcard subdomain matching. For example, `*.gcr.io` allows access to any subdomain of `gcr.io`.569 Domains marked with `*` indicate wildcard subdomain matching. For example, `*.gcr.io` allows access to any subdomain of `gcr.io`.

520</Note>570</Note>


559* [Settings reference](/en/settings)609* [Settings reference](/en/settings)

560* [Security](/en/security)610* [Security](/en/security)

561* [Data usage](/en/data-usage)611* [Data usage](/en/data-usage)

562 

563 

564 

565> 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 +24 −17

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.


26| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |30| `--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"}}'` |31| `--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"}}'` |

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` |32| `--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"` |33| `--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"` |34| `--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"` |

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"` |35| `--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"` |

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


35| `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` |39| `--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"` |40| `--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` |41| `--disable-slash-commands` | Disable all skills and slash 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"` |42| `--disallowedTools` | Tools that are removed from the model's context and cannot be used | `"Bash(git log *)" "Bash(git diff *)" "Edit"` |

39| `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` |43| `--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` |44| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |

45| `--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` |46| `--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` |47| `--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` |48| `--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"` |49| `--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` |50| `--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"` |51| `--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` |52| `--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"` |53| `--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"` |54| `--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` |55| `--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` |56| `--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` |

52| `--no-chrome` | Disable [Chrome browser integration](/en/chrome) for this session | `claude --no-chrome` |57| `--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"` |58| `--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` |59| `--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` |60| `--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"` |61| `--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` |62| `--plugin-dir` | Load plugins from directories for this session only (repeatable) | `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"` |63| `--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"` |64| `--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"` |

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

66| `--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` |

61| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |67| `--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` |68| `--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` |69| `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.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"` |71| `--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"` |

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"` |72| `--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"` |

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

74| `--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` |

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"` |75| `--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"` |

69| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |76| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |

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


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:86The `--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 87 

81| Field | Required | Description |88| Field | Required | Description |

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

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

84| `prompt` | Yes | The system prompt that guides the subagent's behavior |91| `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 |92| `tools` | No | Array of specific tools the subagent can use, for example `["Read", "Edit", "Bash"]`. If omitted, inherits all tools. Supports [`Task(agent_type)`](/en/sub-agents#restrict-which-subagents-can-be-spawned) syntax |

86| `model` | No | Model alias to use: `sonnet`, `opus`, or `haiku`. If omitted, uses the default subagent model |93| `disallowedTools` | No | Array of tool names to explicitly deny for this subagent |

94| `model` | No | Model alias to use: `sonnet`, `opus`, `haiku`, or `inherit`. If omitted, defaults to `inherit` |

95| `skills` | No | Array of [skill](/en/skills) names to preload into the subagent's context |

96| `mcpServers` | No | Array of [MCP servers](/en/mcp) for this subagent. Each entry is a server name string or a `{name: config}` object |

97| `maxTurns` | No | Maximum number of agentic turns before the subagent stops |

87 98 

88Example:99Example:

89 100 


148* [Quickstart guide](/en/quickstart) - Getting started with Claude Code159* [Quickstart guide](/en/quickstart) - Getting started with Claude Code

149* [Common workflows](/en/common-workflows) - Advanced workflows and patterns160* [Common workflows](/en/common-workflows) - Advanced workflows and patterns

150* [Settings](/en/settings) - Configuration options161* [Settings](/en/settings) - Configuration options

151* [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) - Programmatic usage and integrations162* [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

common-workflows.md +140 −86

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.


81 85 

82 * Be specific about what you're looking for86 * Be specific about what you're looking for

83 * Use domain language from the project87 * Use domain language from the project

88 * Install a [code intelligence plugin](/en/discover-plugins#code-intelligence) for your language to give Claude precise "go to definition" and "find references" navigation

84</Tip>89</Tip>

85 90 

86***91***


270> How should we handle database migration?275> How should we handle database migration?

271```276```

272 277 

278<Tip>Press `Ctrl+G` to open the plan in your default text editor, where you can edit it directly before Claude proceeds.</Tip>

279 

273### Configure Plan Mode as default280### Configure Plan Mode as default

274 281 

275```json theme={null}282```json theme={null}


323 330 

324## Create pull requests331## Create pull requests

325 332 

326Suppose you need to create a well-documented pull request for your changes.333You can create pull requests by asking Claude directly ("create a pr for my changes") or by using the `/commit-push-pr` skill, which commits, pushes, and opens a PR in one step.

334 

335```

336> /commit-push-pr

337```

338 

339If you have a Slack MCP server configured and specify channels in your CLAUDE.md (for example, "post PR URLs to #team-prs"), the skill automatically posts the PR URL to those channels.

340 

341For more control over the process, guide Claude through it step-by-step or [create your own skill](/en/skills):

327 342 

328<Steps>343<Steps>

329 <Step title="Summarize your changes">344 <Step title="Summarize your changes">


332 ```347 ```

333 </Step>348 </Step>

334 349 

335 <Step title="Generate a pull request with Claude">350 <Step title="Generate a pull request">

336 ```351 ```

337 > create a pr352 > create a pr

338 ```353 ```


343 > enhance the PR description with more context about the security improvements358 > enhance the PR description with more context about the security improvements

344 ```359 ```

345 </Step>360 </Step>

346 

347 <Step title="Add testing details">

348 ```

349 > add information about how these changes were tested

350 ```

351 </Step>

352</Steps>361</Steps>

353 362 

354<Tip>363When 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>`.

355 Tips:

356 364 

357 * Ask Claude directly to make a PR for you365<Tip>

358 * Review Claude's generated PR before submitting366 Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations.

359 * Ask Claude to highlight potential risks or considerations

360</Tip>367</Tip>

361 368 

362## Handle documentation369## Handle documentation


502 509 

503## Use extended thinking (thinking mode)510## Use extended thinking (thinking mode)

504 511 

505[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`.512[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`.

513 

514Additionally, Opus 4.6 introduces 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.

506 515 

507Extended 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.516Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches.

508 517 

509<Note>518<Note>

510 Phrases like "think", "think hard", "ultrathink", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.519 Phrases like "think", "think hard", "ultrathink", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.


515Thinking is enabled by default, but you can adjust or disable it.524Thinking is enabled by default, but you can adjust or disable it.

516 525 

517| Scope | How to configure | Details |526| Scope | How to configure | Details |

518| ---------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |527| ---------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |

519| **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 |528| **Effort level** | Adjust in `/model` or set [`CLAUDE_CODE_EFFORT_LEVEL`](/en/settings#environment-variables) | Control thinking depth for Opus 4.6: low, medium, high (default). See [Adjust effort level](/en/model-config#adjust-effort-level) |

520| **Global default** | Use `/config` to toggle thinking mode | Sets your default across all projects.<br />Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` |529| **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 |

521| **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` |530| **Global default** | Use `/config` to toggle thinking mode | Sets your default across all projects (all models).<br />Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` |

531| **Limit token budget** | Set [`MAX_THINKING_TOKENS`](/en/settings#environment-variables) environment variable | Limit the thinking budget to a specific number of tokens (ignored on Opus 4.6 unless set to 0). Example: `export MAX_THINKING_TOKENS=10000` |

522 532 

523To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.533To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.

524 534 

525### How extended thinking token budgets work535### How extended thinking works

526 536 

527Extended thinking uses a **token budget** that controls how much internal reasoning Claude can perform before responding.537Extended 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.

528 538 

529A larger thinking token budget provides:539**With Opus 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 (low, medium, high). This is the recommended way to tune the tradeoff between speed and reasoning depth.

530 540 

531* More space to explore multiple solution approaches step-by-step541**With other 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/settings#environment-variables) environment variable, or disable thinking entirely via `/config` or the `Option+T`/`Alt+T` toggle.

532* Room to analyze edge cases and evaluate tradeoffs thoroughly

533* Ability to revise reasoning and self-correct mistakes

534 542 

535Token budgets for thinking mode:543`MAX_THINKING_TOKENS` is ignored when using Opus 4.6, since adaptive reasoning controls thinking depth instead. The one exception: setting `MAX_THINKING_TOKENS=0` still disables thinking entirely on any model.

536 

537* When thinking is **enabled**, Claude can use up to **31,999 tokens** from your output budget for internal reasoning

538* When thinking is **disabled** (via toggle or `/config`), Claude uses **0 tokens** for thinking

539 

540**Limit the thinking budget:**

541 

542* Use the [`MAX_THINKING_TOKENS` environment variable](/en/settings#environment-variables) to cap the thinking budget

543* When set, this value limits the maximum tokens Claude can use for thinking

544* See the [extended thinking documentation](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for valid token ranges

545 544 

546<Warning>545<Warning>

547 You're charged for all thinking tokens used, even though Claude 4 models show summarized thinking546 You're charged for all thinking tokens used, even though Claude 4 models show summarized thinking


555 554 

556* `claude --continue` continues the most recent conversation in the current directory555* `claude --continue` continues the most recent conversation in the current directory

557* `claude --resume` opens a conversation picker or resumes by name556* `claude --resume` opens a conversation picker or resumes by name

557* `claude --from-pr 123` resumes sessions linked to a specific pull request

558 558 

559From inside an active session, use `/resume` to switch to a different conversation.559From inside an active session, use `/resume` to switch to a different conversation.

560 560 


642 642 

643## Run parallel Claude Code sessions with Git worktrees643## Run parallel Claude Code sessions with Git worktrees

644 644 

645Suppose you need to work on multiple tasks simultaneously with complete code isolation between Claude Code instances.645When 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.

646 

647Use the `--worktree` flag to create an isolated worktree and start Claude in it. The value you pass becomes the worktree directory name and branch name:

648 

649```bash theme={null}

650# Start Claude in a worktree named "feature-auth"

651# Creates .claude/worktrees/feature-auth/ with a new branch

652claude -w feature-auth

653 

654# Start another session in a separate worktree

655claude -w bugfix-123

656```

657 

658If you omit the name, Claude generates a random one automatically:

659 

660```bash theme={null}

661# Auto-generates a name like "bright-running-fox"

662claude -w

663```

664 

665Worktrees are created at `<repo>/.claude/worktrees/<name>` and branch from the default remote branch. The worktree branch is named `worktree-<name>`.

666 

667You can also ask Claude to "work in a worktree" or "start a worktree" during a session, and it will create one automatically.

668 

669### Worktree cleanup

670 

671When you exit a worktree session, Claude handles cleanup based on whether you made changes:

672 

673* **No changes**: the worktree and its branch are removed automatically

674* **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

675 

676To clean up worktrees outside of a Claude session, use [manual worktree management](#manage-worktrees-manually).

677 

678<Tip>

679 Add `.claude/worktrees/` to your `.gitignore` to prevent worktree contents from appearing as untracked files in your main repository.

680</Tip>

681 

682### Manage worktrees manually

683 

684For 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.

685 

686```bash theme={null}

687# Create a worktree with a new branch

688git worktree add ../project-feature-a -b feature-a

689 

690# Create a worktree with an existing branch

691git worktree add ../project-bugfix bugfix-123

692 

693# Start Claude in the worktree

694cd ../project-feature-a && claude

695 

696# Clean up when done

697git worktree list

698git worktree remove ../project-feature-a

699```

700 

701Learn more in the [official Git worktree documentation](https://git-scm.com/docs/git-worktree).

702 

703<Tip>

704 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.

705</Tip>

706 

707For automated coordination of parallel sessions with shared tasks and messaging, see [agent teams](/en/agent-teams).

708 

709***

710 

711## Get notified when Claude needs your attention

712 

713When 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.

646 714 

647<Steps>715<Steps>

648 <Step title="Understand Git worktrees">716 <Step title="Open the hooks menu">

649 Git worktrees allow you to check out multiple branches from the same717 Type `/hooks` and select `Notification` from the list of events.

650 repository into separate directories. Each worktree has its own working

651 directory with isolated files, while sharing the same Git history. Learn

652 more in the [official Git worktree

653 documentation](https://git-scm.com/docs/git-worktree).

654 </Step>718 </Step>

655 719 

656 <Step title="Create a new worktree">720 <Step title="Configure the matcher">

657 ```bash theme={null}721 Select `+ Match all (no filter)` to fire on all notification types. To notify only for specific events, select `+ Add new matcher…` and enter one of these values:

658 # Create a new worktree with a new branch

659 git worktree add ../project-feature-a -b feature-a

660 722 

661 # Or create a worktree with an existing branch723 | Matcher | Fires when |

662 git worktree add ../project-bugfix bugfix-123724 | :------------------- | :---------------------------------------------- |

663 ```725 | `permission_prompt` | Claude needs you to approve a tool use |

664 726 | `idle_prompt` | Claude is done and waiting for your next prompt |

665 This creates a new directory with a separate working copy of your repository.727 | `auth_success` | Authentication completes |

728 | `elicitation_dialog` | Claude is asking you a question |

666 </Step>729 </Step>

667 730 

668 <Step title="Run Claude Code in each worktree">731 <Step title="Add your notification command">

669 ```bash theme={null}732 Select `+ Add new hook…` and enter the command for your OS:

670 # Navigate to your worktree 733 

671 cd ../project-feature-a734 <Tabs>

735 <Tab title="macOS">

736 Uses [`osascript`](https://ss64.com/mac/osascript.html) to trigger a native macOS notification through AppleScript:

672 737 

673 # Run Claude Code in this isolated environment

674 claude

675 ```738 ```

676 </Step>739 osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'

740 ```

741 </Tab>

742 

743 <Tab title="Linux">

744 Uses `notify-send`, which is pre-installed on most Linux desktops with a notification daemon:

677 745 

678 <Step title="Run Claude in another worktree">

679 ```bash theme={null}

680 cd ../project-bugfix

681 claude

682 ```746 ```

683 </Step>747 notify-send 'Claude Code' 'Claude Code needs your attention'

748 ```

749 </Tab>

684 750 

685 <Step title="Manage your worktrees">751 <Tab title="Windows (PowerShell)">

686 ```bash theme={null}752 Uses PowerShell to show a native message box through .NET's Windows Forms:

687 # List all worktrees

688 git worktree list

689 753 

690 # Remove a worktree when done

691 git worktree remove ../project-feature-a

692 ```754 ```

755 powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')"

756 ```

757 </Tab>

758 </Tabs>

759 </Step>

760 

761 <Step title="Save to user settings">

762 Select `User settings` to apply the notification across all your projects.

693 </Step>763 </Step>

694</Steps>764</Steps>

695 765 

696<Tip>766For the full walkthrough with JSON configuration examples, see [Automate workflows with hooks](/en/hooks-guide#get-notified-when-claude-needs-input). For the complete event schema and notification types, see the [Notification reference](/en/hooks#notification).

697 Tips:

698 

699 * Each worktree has its own independent file state, making it perfect for parallel Claude Code sessions

700 * Changes made in one worktree won't affect others, preventing Claude instances from interfering with each other

701 * All worktrees share the same Git history and remote connections

702 * For long-running tasks, you can have Claude working in one worktree while you continue development in another

703 * Use descriptive directory names to easily identify which task each worktree is for

704 * Remember to initialize your development environment in each new worktree according to your project's setup. Depending on your stack, this might include:

705 * JavaScript projects: Running dependency installation (`npm install`, `yarn`)

706 * Python projects: Setting up virtual environments or installing with package managers

707 * Other languages: Following your project's standard setup process

708</Tip>

709 767 

710***768***

711 769 


857 Clone our development container reference implementation915 Clone our development container reference implementation

858 </Card>916 </Card>

859</CardGroup>917</CardGroup>

860 

861 

862 

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

costs.md +28 −8

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 


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).


89* **Disable unused servers**: Run `/mcp` to see configured servers and disable any you're not actively using.105* **Disable unused servers**: Run `/mcp` to see configured servers and disable any you're not actively using.

90* **Tool search is automatic**: When MCP tool descriptions exceed 10% of your context window, Claude Code automatically defers them and loads tools on-demand via [tool search](/en/mcp#scale-with-mcp-tool-search). Since deferred tools only enter context when actually used, a lower threshold means fewer idle tool definitions consuming space. Set a lower threshold with `ENABLE_TOOL_SEARCH=auto:<N>` (for example, `auto:5` triggers when tools exceed 5% of your context window).106* **Tool search is automatic**: When MCP tool descriptions exceed 10% of your context window, Claude Code automatically defers them and loads tools on-demand via [tool search](/en/mcp#scale-with-mcp-tool-search). Since deferred tools only enter context when actually used, a lower threshold means fewer idle tool definitions consuming space. Set a lower threshold with `ENABLE_TOOL_SEARCH=auto:<N>` (for example, `auto:5` triggers when tools exceed 5% of your context window).

91 107 

108### Install code intelligence plugins for typed languages

109 

110[Code intelligence plugins](/en/discover-plugins#code-intelligence) give Claude precise symbol navigation instead of text-based search, reducing unnecessary file reads when exploring unfamiliar code. A single "go to definition" call replaces what might otherwise be a grep followed by reading multiple candidate files. Installed language servers also report type errors automatically after edits, so Claude catches mistakes without running a compiler.

111 

92### Offload processing to hooks and skills112### Offload processing to hooks and skills

93 113 

94Custom [hooks](/en/hooks) can preprocess data before Claude sees it. Instead of Claude reading a 10,000-line log file to find errors, a hook can grep for `ERROR` and return only matching lines, reducing context from tens of thousands of tokens to hundreds.114Custom [hooks](/en/hooks) can preprocess data before Claude sees it. Instead of Claude reading a 10,000-line log file to find errors, a hook can grep for `ERROR` and return only matching lines, reducing context from tens of thousands of tokens to hundreds.


145 165 

146### Adjust extended thinking166### Adjust extended thinking

147 167 

148Extended 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) in `/model` for Opus 4.6, disabling thinking in `/config`, or lowering the budget (for example, `MAX_THINKING_TOKENS=8000`).

149 169 

150### Delegate verbose operations to subagents170### Delegate verbose operations to subagents

151 171 

152Running 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.

153 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 

154### Write specific prompts178### Write specific prompts

155 179 

156Vague 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.


176## Understanding changes in Claude Code behavior200## Understanding changes in Claude Code behavior

177 201 

178Claude 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.

179 

180 

181 

182> 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 +14 −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# 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 automatically disabled when using third-party providers (Bedrock, Vertex, Foundry) or when telemetry is disabled.

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.


51 57 

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.58The 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 59 

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" />60<img src="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=e0239c69a0bbae485b726338e50f1082" 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/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?w=280&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=06435e080df22e66a454e99af1b6040b 280w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?w=560&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=8261c15b4ffc12504e0a6e3f0ccd8c7d 560w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?w=840&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=163bfaa8d4727a1bbb492cb086e5f083 840w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?w=1100&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=ea3c2f801dfa5ad956b18b5f72df5c50 1100w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?w=1650&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=91d743def7a8d074c93001b351f23037 1650w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/claude-code-data-flow.svg?w=2500&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=df68b2dd6de83316f70fd7f61c3a3bbd 2500w" />

55 61 

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.62Claude 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 63 


78 84 

79## Default behaviors by API provider85## Default behaviors by API provider

80 86 

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:87By default, we disable all non-essential traffic (including error reporting, telemetry, bug reporting functionality, and session quality surveys) when using Bedrock, Vertex, or Foundry. 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:

82 88 

83| Service | Claude API | Vertex API | Bedrock API |89| Service | Claude API | Vertex API | Bedrock API | Foundry API |

84| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |90| ------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------ |

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. |91| **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. |92| **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. |93| **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. |

94| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=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. |

88 95 

89All environment variables can be checked into `settings.json` ([read more](/en/settings)).96All 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 +306 −74

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, permission modes, connectors, and enterprise configuration.

6 8 

7## Claude Code on desktop (Preview)9The Code tab in the Desktop app lets you use Claude Code through a graphical interface instead of the terminal. You get visual diff review with inline comments, permission modes that control how much Claude does on its own, parallel sessions with automatic Git isolation, and connectors that integrate tools like GitHub, Slack, and Linear. Sessions can run locally, on a remote machine over [SSH](#ssh-sessions), or in [the cloud](#run-long-running-tasks-remotely).

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.11<Tip>

12 New to Desktop? Start with [Get started](/en/desktop-quickstart) to install the app and make your first edit.

13</Tip>

10 14 

11## Installation15This page covers [working with code](#work-with-code), [managing sessions](#manage-sessions), [extending Claude Code](#extend-claude-code), and [configuration](#environment-configuration). It also includes a [CLI comparison](#coming-from-the-cli) and [troubleshooting](#troubleshooting).

12 16 

13Download the Claude desktop app for your platform:17## Start a session

14 18 

15<CardGroup cols={2}>19Before you send your first message, configure four things in the prompt area:

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 20 

20 <Card title="Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs">21* **Environment**: choose where Claude runs. Select **Local** for your machine, a **cloud environment** for Anthropic-hosted sessions, or an [**SSH connection**](#ssh-sessions) for a remote machine you manage. See [environment configuration](#environment-configuration).

21 For x64 processors22* **Project folder**: select the folder or repository Claude works in. For remote sessions, you can add [multiple repositories](#run-long-running-tasks-remotely).

22 </Card>23* **Model**: pick a [model](/en/overview#models) from the dropdown next to the send button. The model is locked once the session starts.

23</CardGroup>24* **Permission mode**: choose how much autonomy Claude has from the [mode selector](#choose-a-permission-mode). You can change this during the session.

24 25 

25For Windows ARM64, [download here](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs).26Type your task and press **Enter** to start. Each session tracks its own context and changes independently.

26 27 

27<Note>28## Work with code

28 Local sessions are not available on Windows ARM64.29 

29</Note>30Give Claude the right context, control how much it does on its own, and review what it changed.

31 

32### Use the prompt box

33 

34Type 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.

30 35 

31## Features36The **+** button next to the prompt box gives you access to file attachments, [skills](#use-skills), [connectors](#connect-external-tools), and [plugins](#install-plugins).

32 37 

33Claude Code on desktop provides:38### Add files and context to prompts

34 39 

35* **Diff view**: Review Claude's changes file by file before creating a pull request, and comment on specific lines to iterate further40The prompt box supports two ways to bring in external context:

36* **Parallel local sessions with `git` worktrees**: Run multiple Claude Code sessions simultaneously in the same repository, each with its own isolated `git` worktree41 

37* **Include files listed in your `.gitignore` in your worktrees**: Automatically copy files in your `.gitignore`, like `.env`, to new worktrees using `.worktreeinclude`42* **@mention files**: type `@` followed by a filename to add a file to the conversation context. Claude can then read and reference that file.

38* **Launch Claude Code on the web**: Kick off secure cloud sessions directly from the desktop app43* **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.

44 

45### Choose a permission mode

46 

47Permission 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 mode to see exactly what Claude does, then move to Code or Plan as you get comfortable.

48 

49| Mode | Settings key | Behavior |

50| -------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

51| **Ask** | `default` | Claude asks for your approval before each file edit or command. You see a diff view and can accept or reject each change. Recommended for new users. |

52| **Code** | `acceptEdits` | Claude auto-accepts file edits but still asks before running terminal commands. Use this when you trust file changes and want faster iteration. |

53| **Plan** | `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. |

54| **Act** | `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. |

55 

56The `dontAsk` permission mode is available only in the [CLI](/en/permissions#permission-modes).

57 

58<Tip title="Best practice">

59 Start complex tasks in Plan mode so Claude maps out an approach before making changes. Once you approve the plan, switch to Code or Ask mode to execute it. See [explore first, then plan, then code](/en/best-practices#explore-first-then-plan-then-code) for more on this workflow.

60</Tip>

39 61 

40## Review changes with diff view62Remote sessions support Code mode and Plan mode. Ask mode is not available because remote sessions auto-accept file edits by default, and Act mode is not available because the remote environment is already sandboxed.

63 

64Enterprise admins can restrict which permission modes are available. See [enterprise configuration](#enterprise-configuration) for details.

65 

66### Review changes with diff view

41 67 

42After Claude makes changes to your code, the diff view lets you review modifications file by file before creating a pull request.68After Claude makes changes to your code, the diff view lets you review modifications file by file before creating a pull request.

43 69 

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.70When 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.

71 

72To 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:

73 

74* **macOS**: press **Cmd+Enter**

75* **Windows**: press **Ctrl+Enter**

45 76 

46### Comment on specific lines77Claude reads your comments and makes the requested changes, which appear as a new diff you can review.

47 78 

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.79## Manage sessions

49 80 

50## Using Git worktrees81Each session is an independent conversation with its own context and changes. You can run multiple sessions in parallel or send work to the cloud.

51 82 

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.83### Work in parallel with sessions

84 

85Click **+ 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.

86 

87Worktrees 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.

53 88 

54<Note>89<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.90 Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check. On Windows, [download Git](https://git-scm.com/downloads) if you don't have it.

91 

92 Without Git, sessions share the same files and changes in one session are immediately visible in others.

56</Note>93</Note>

57 94 

58### Copying files ignored with `.gitignore`95Use 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 this conversation" 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.

59 96 

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.97### Run long-running tasks remotely

61 98 

62Create a `.worktreeinclude` file in your repository root:99For 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.

63 100 

64```101Remote 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.

65.env102 

66.env.local103See [Claude Code on the web](/en/claude-code-on-the-web) for more on how remote sessions work.

67.env.*104 

68**/.claude/settings.local.json105### Continue in another surface

69```106 

107The **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:

108 

109* **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.

110* **Your IDE**: opens your project in a supported IDE at the current working directory.

111 

112## Extend Claude Code

113 

114Connect external services, add reusable workflows, and customize Claude's behavior for your project.

115 

116### Connect external tools

117 

118For 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.

119 

120To manage or disconnect connectors, go to Settings → Connectors in the desktop app, or select **Manage connectors** from the Connectors menu in the prompt box.

121 

122Once 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.

123 

124Connectors 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).

125 

126### Use skills

127 

128[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/interactive-mode#built-in-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.

129 

130### Install plugins

131 

132[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.

133 

134For 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.

135 

136Plugins 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).

137 

138## Environment configuration

139 

140When starting a session, you choose between three environments:

141 

142* **Local**: runs on your machine with direct access to your files

143* **Remote**: runs on Anthropic's cloud infrastructure. Sessions continue even if you close the app.

144* **SSH**: runs on a remote machine you connect to over SSH, such as your own servers, cloud VMs, or dev containers

145 

146### Local sessions

147 

148Local 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/settings#environment-variables) for the full list of supported variables.

149 

150[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 it or adjust the budget, set `MAX_THINKING_TOKENS` in your shell profile. Use `0` to disable.

151 

152### Remote sessions

153 

154Remote 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.

155 

156You 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-environments) for details on configuring network access and environment variables.

157 

158### SSH sessions

159 

160SSH 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.

161 

162To add an SSH connection, click the environment dropdown before starting a session and select **+ Add SSH connection**. The dialog asks for:

163 

164* **Name**: a friendly label for this connection

165* **SSH Host**: `user@hostname` or a host defined in `~/.ssh/config`

166* **SSH Port**: defaults to 22 if left empty, or uses the port from your SSH config

167* **Identity File**: path to your private key, such as `~/.ssh/id_rsa`. Leave empty to use the default key or your SSH config.

70 168 

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.169Once 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.

170 

171SSH sessions support permission modes, connectors, plugins, and MCP servers. Claude Code must be installed on the remote machine.

172 

173## Enterprise configuration

174 

175Organizations on Teams or Enterprise plans can manage desktop app behavior through admin console controls, managed settings files, and device management policies.

176 

177### Admin console controls

178 

179These settings are configured through the [admin settings console](https://claude.ai/admin-settings/claude-code):

180 

181* **Enable or disable the Code tab**: control whether users in your organization can access Claude Code in the desktop app

182* **Disable Act mode**: prevent users in your organization from enabling bypass permissions mode

183* **Disable Claude Code on the web**: enable or disable remote sessions for your organization

184 

185### Managed settings

186 

187Managed 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.

188 

189| Key | Description |

190| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |

191| `permissions.disableBypassPermissionsMode` | set to `"disable"` to prevent users from enabling Act mode. See [permissions](/en/permissions#managed-settings). |

192 

193Remote 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.

194 

195### Device management policies

196 

197IT 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.

198 

199* **macOS**: configure via `com.anthropic.Claude` preference domain using tools like Jamf or Kandji

200* **Windows**: configure via registry at `SOFTWARE\Policies\Claude`

201 

202### Authentication and SSO

203 

204Enterprise 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.

205 

206### Data handling

207 

208Claude 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.

209 

210### Deployment

211 

212Desktop can be distributed through enterprise deployment tools:

213 

214* **macOS**: distribute via MDM such as Jamf or Kandji using the `.dmg` installer

215* **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

216 

217For network configuration such as proxy settings, firewall allowlisting, and LLM gateways, see [network configuration](/en/network-config).

218 

219For the full enterprise configuration reference, see the [enterprise configuration guide](https://support.claude.com/en/articles/12622667-enterprise-configuration).

220 

221## Coming from the CLI?

222 

223If 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.

224 

225To 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.

72 226 

73<Tip>227<Tip>

74 Only files that are both matched by `.worktreeinclude` AND listed in `.gitignore` are copied. This prevents accidentally duplicating tracked files.228 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.

75</Tip>229</Tip>

76 230 

77### Launch Claude Code on the web231### CLI flag equivalents

78 232 

79From the desktop app, you can kick off Claude Code sessions that run on Anthropic's secure cloud infrastructure.233This 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.

80 234 

81To start a web session from desktop, select a remote environment when creating a new session.235| CLI | Desktop equivalent |

236| ------------------------------------- | ------------------------------------------------------------------------------------------------------------- |

237| `--model sonnet` | model dropdown next to the send button, before starting a session |

238| `--resume`, `--continue` | click a session in the sidebar |

239| `--permission-mode` | mode selector next to the send button |

240| `--dangerously-skip-permissions` | Settings → Claude Code → "Allow bypass permissions mode". Enterprise admins can disable this setting. |

241| `--add-dir` | add multiple repos with the **+** button in remote sessions |

242| `--allowedTools`, `--disallowedTools` | not available in Desktop |

243| `--verbose` | not available. Check system logs: Console.app on macOS, Event Viewer → Application on Windows |

244| `--print`, `--output-format` | not available. Desktop is interactive only. |

245| `ANTHROPIC_MODEL` env var | model dropdown next to the send button |

246| `MAX_THINKING_TOKENS` env var | set in shell profile; applies to local sessions. See [environment configuration](#environment-configuration). |

82 247 

83For more details, see [Claude Code on the web](/en/claude-code-on-the-web).248### Shared configuration

84 249 

85## Bundled Claude Code version250Desktop and CLI read the same configuration files, so your setup carries over:

86 251 

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.252* **[CLAUDE.md](/en/memory)** and **CLAUDE.local.md** files in your project are used by both

253* **[MCP servers](/en/mcp)** configured in `~/.claude.json` or `.mcp.json` work in both

254* **[Hooks](/en/hooks)** and **[skills](/en/skills)** defined in settings apply to both

255* **[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.

256* **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.

88 257 

89<Note>258<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.259 **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.

91</Note>260</Note>

92 261 

93## Environment configuration262### Feature comparison

94 263 

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.264This table compares core capabilities between the CLI and Desktop. For a full list of CLI flags, see the [CLI reference](/en/cli-reference).

96 265 

97### Custom environment variables266| Feature | CLI | Desktop |

267| ----------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------ |

268| Permission modes | all modes including `dontAsk` | Ask, Code, Plan, and Act via Settings |

269| `--dangerously-skip-permissions` | CLI flag | Settings → Claude Code → "Allow bypass permissions mode" |

270| [Third-party providers](/en/third-party-integrations) | Bedrock, Vertex, Foundry | not available. Desktop connects to Anthropic's API directly. |

271| [MCP servers](/en/mcp) | configure in settings files | Connectors UI for local and SSH sessions, or settings files |

272| [Plugins](/en/plugins) | `/plugin` command | plugin manager UI |

273| @mention files | text-based | with autocomplete |

274| File attachments | not available | images, PDFs |

275| Session isolation | [`--worktree`](/en/cli-reference) flag | automatic worktrees |

276| Multiple sessions | separate terminals | sidebar tabs |

277| Scripting and automation | [`--print`](/en/cli-reference), [Agent SDK](/en/headless) | not available |

98 278 

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.279### What's not available in Desktop

100 280 

101<Note>281* **Third-party providers**: Desktop connects to Anthropic's API directly. Use the [CLI](/en/quickstart) with Bedrock, Vertex, or Foundry instead.

102 Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:282* **Linux**: the desktop app is available on macOS and Windows only.

283* **Inline code suggestions**: Desktop does not provide autocomplete-style suggestions. It works through conversational prompts and explicit code changes.

284* **Agent teams**: multi-agent orchestration is available via the [CLI](/en/agent-teams) and [Agent SDK](/en/headless), not in Desktop.

103 285 

104 ```286## Troubleshooting

105 API_KEY=your_api_key

106 DEBUG=true

107 287 

108 # Multiline values - wrap in quotes288### Check your version

109 CERT="-----BEGIN CERT-----

110 MIIE...

111 -----END CERT-----"

112 ```

113</Note>

114 289 

115## Enterprise configuration290To see which version of the desktop app you're running:

291 

292* **macOS**: click **Claude** in the menu bar, then **About Claude**

293* **Windows**: click **Help**, then **About**

294 

295Click the version number to copy it to your clipboard.

296 

297### 403 or authentication errors in the Code tab

298 

299If you see `Error 403: Forbidden` or other authentication failures when using the Code tab:

300 

3011. Sign out and back in from the app menu. This is the most common fix.

3022. Verify you have an active paid subscription: Pro, Max, Teams, or Enterprise.

3033. If the CLI works but Desktop does not, quit the desktop app completely, not just close the window, then reopen and sign in again.

3044. Check your internet connection and proxy settings.

305 

306### Blank or stuck screen on launch

307 

308If the app opens but shows a blank or unresponsive screen:

309 

3101. Restart the app.

3112. Check for pending updates. The app auto-updates on launch.

3123. On Windows, check Event Viewer for crash logs under **Windows Logs → Application**.

313 

314### "Failed to load session"

315 

316If 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.

317 

318### Session not finding installed tools

116 319 

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).320If 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.

118 321 

119## Related resources322### Git and Git LFS errors

120 323 

121* [Claude Code on the web](/en/claude-code-on-the-web)324Git is required for session isolation and worktrees. If you see "Git is required," install Git from [git-scm.com](https://git-scm.com/downloads) and restart the app.

122* [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop)325 

123* [Enterprise Configuration](https://support.claude.com/en/articles/12622667-enterprise-configuration)326If 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.

124* [Common workflows](/en/common-workflows)327 

125* [Settings reference](/en/settings)328### MCP servers not working on Windows

329 

330If 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.

331 

332### App won't quit

333 

334* **macOS**: press Cmd+Q. If the app doesn't respond, use Force Quit with Cmd+Option+Esc, select Claude, and click Force Quit.

335* **Windows**: use Task Manager with Ctrl+Shift+Esc to end the Claude process.

336 

337### Windows-specific issues

338 

339* **PATH not updated after install**: open a new terminal window. PATH updates only apply to new terminal sessions.

340* **Concurrent installation error**: if you see an error about another installation in progress but there isn't one, try running the installer as Administrator.

341* **ARM64 limitations**: Windows ARM64 devices can run the desktop app but do not support local sessions. Use **Remote** sessions instead.

342 

343### Cowork tab unavailable on Intel Macs

344 

345The Cowork tab requires Apple Silicon, M1 or later. The Chat and Code tabs work normally on Intel Macs.

346 

347### "Branch doesn't exist yet" when opening in CLI

348 

349Remote 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:

350 

351```bash theme={null}

352git fetch origin <branch-name>

353git checkout <branch-name>

354```

126 355 

356### Still stuck?

127 357 

358* Search or file a bug on [GitHub Issues](https://github.com/anthropics/claude-code/issues)

359* Visit the [Claude support center](https://support.claude.com/)

128 360 

129> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt361When 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 → Application.

desktop-quickstart.md +131 −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, parallel sessions with Git worktree isolation, file attachments, and the ability to run long-running tasks remotely. Work with local files, connect to remote machines over SSH, or run sessions in the cloud. No terminal required.

10 

11If 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, model picker, folder selector, and Local environment option" data-og-width="2500" width="2500" data-og-height="1376" height="1376" data-path="images/desktop-code-tab-light.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?w=280&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=b4d1408a312d3ff3ac96dd133e4ef32b 280w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?w=560&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=c2d9f668767d4de33696b3de190c0024 560w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?w=840&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=89a78335d513c0ec2131feb11eeef6dc 840w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?w=1100&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=0ef93540eafcedd2fb0ad718553325f4 1100w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?w=1650&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=e7923c583f632de9f8a7e0e0da4f8c84 1650w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-light.png?w=2500&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=38d64bdceaba941a73446f258be336ea 2500w" />

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, model picker, folder selector, and Local environment option" data-og-width="2504" width="2504" data-og-height="1374" height="1374" data-path="images/desktop-code-tab-dark.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?w=280&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=f2a6322688262feb9d680b99c24817ab 280w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?w=560&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=ffe9a3d1c4260fb12c66f533fdedc02e 560w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?w=840&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=867b7997a910af3ffac1101559564dd7 840w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?w=1100&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=976c9049c9e4cea2b02d4b6a1ef55142 1100w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?w=1650&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=d8f3792ddadf66f61306dc41680aaa34 1650w, https://mintcdn.com/claude-code/CNLUpFGiXoc9mhvD/images/desktop-code-tab-dark.png?w=2500&fit=max&auto=format&n=CNLUpFGiXoc9mhvD&q=85&s=88d049488f547e483e8c4f59ea8b2fd8 2500w" />

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).

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). Local sessions are not available on ARM64 devices, so use remote sessions instead. See [ARM64 limitations](/en/desktop#windows-specific-issues) for details.

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) 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 

61## Start your first session

62 

63With the Code tab open, choose a project and give Claude something to do.

64 

65<Steps>

66 <Step title="Choose an environment and folder">

67 Select **Local** to run Claude on your machine using your files directly. Click **Select folder** and choose your project directory.

68 

69 <Tip>

70 Start with a small project you know well. It's the fastest way to see what Claude Code can do. Session isolation requires [Git](https://git-scm.com/downloads); without Git, all sessions in the same folder edit the same files.

71 </Tip>

72 

73 You can also select:

74 

75 * **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).

76 * **SSH**: Connect to a remote machine over SSH (your own servers, cloud VMs, or dev containers). Claude runs on the remote machine with access to its files and tools.

77 </Step>

78 

79 <Step title="Choose a model">

80 Select a model from the dropdown next to the send button. See [models](/en/overview#models) for a comparison of Opus, Sonnet, and Haiku. You cannot change the model after the session starts.

81 </Step>

82 

83 <Step title="Tell Claude what to do">

84 Type what you want Claude to do:

85 

86 * `Find a TODO comment and fix it`

87 * `Add tests for the main function`

88 * `Create a CLAUDE.md with instructions for this codebase`

89 

90 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.

91 </Step>

92 

93 <Step title="Review and accept changes">

94 By default, the Code tab starts in [Ask mode](/en/desktop#choose-a-permission-mode), where Claude proposes changes and waits for your approval before applying them. You'll see:

95 

96 1. A [diff view](/en/desktop#review-changes-with-diff-view) showing exactly what will change in each file

97 2. Accept/Reject buttons to approve or decline each change

98 3. Real-time updates as Claude works through your request

99 

100 If you reject a change, Claude will ask how you'd like to proceed differently. Your files aren't modified until you accept.

101 </Step>

102</Steps>

103 

104## Now what?

105 

106You'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.

107 

108**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.

109 

110**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).

111 

112**Use skills for repeatable tasks.** Type `/` or click **+** → **Slash commands** to browse [built-in commands](/en/interactive-mode#built-in-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.

113 

114**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.

115 

116**Adjust how much control you have.** Your [permission mode](/en/desktop#choose-a-permission-mode) controls the balance. Ask mode (default) requires approval before every edit. Code mode 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.

117 

118**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.

119 

120**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 VS Code](/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.

121 

122## Coming from the CLI?

123 

124Desktop 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).

125 

126## What's next

127 

128* [Use Claude Code Desktop](/en/desktop): permission modes, parallel sessions, diff view, connectors, and enterprise configuration

129* [Troubleshooting](/en/desktop#troubleshooting): solutions to common errors and setup issues

130* [Best practices](/en/best-practices): tips for writing effective prompts and getting the most out of Claude Code

131* [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.


40 44 

41### Code intelligence45### Code intelligence

42 46 

43Code intelligence plugins help Claude understand your codebase more deeply. With these plugins installed, Claude can jump to definitions, find references, and see type errors immediately after edits. These plugins use the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP), the same technology that powers VS Code's code intelligence.47Code intelligence plugins enable Claude Code's built-in LSP tool, giving Claude the ability to jump to definitions, find references, and see type errors immediately after edits. These plugins configure [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) connections, the same technology that powers VS Code's code intelligence.

44 48 

45These plugins require the language server binary to be installed on your system. If you already have a language server installed, Claude may prompt you to install the corresponding plugin when you open a project.49These plugins require the language server binary to be installed on your system. If you already have a language server installed, Claude may prompt you to install the corresponding plugin when you open a project.

46 50 


50| C# | `csharp-lsp` | `csharp-ls` |54| C# | `csharp-lsp` | `csharp-ls` |

51| Go | `gopls-lsp` | `gopls` |55| Go | `gopls-lsp` | `gopls` |

52| Java | `jdtls-lsp` | `jdtls` |56| Java | `jdtls-lsp` | `jdtls` |

57| Kotlin | `kotlin-lsp` | `kotlin-language-server` |

53| Lua | `lua-lsp` | `lua-language-server` |58| Lua | `lua-lsp` | `lua-language-server` |

54| PHP | `php-lsp` | `intelephense` |59| PHP | `php-lsp` | `intelephense` |

55| Python | `pyright-lsp` | `pyright-langserver` |60| Python | `pyright-lsp` | `pyright-langserver` |


63 If you see `Executable not found in $PATH` in the `/plugin` Errors tab after installing a plugin, install the required binary from the table above.68 If you see `Executable not found in $PATH` in the `/plugin` Errors tab after installing a plugin, install the required binary from the table above.

64</Note>69</Note>

65 70 

71#### What Claude gains from code intelligence plugins

72 

73Once a code intelligence plugin is installed and its language server binary is available, Claude gains two capabilities:

74 

75* **Automatic diagnostics**: after every file edit Claude makes, the language server analyzes the changes and reports errors and warnings back automatically. Claude sees type errors, missing imports, and syntax issues without needing to run a compiler or linter. If Claude introduces an error, it notices and fixes the issue in the same turn. This requires no configuration beyond installing the plugin. You can see diagnostics inline by pressing **Ctrl+O** when the "diagnostics found" indicator appears.

76* **Code navigation**: Claude can use the language server to jump to definitions, find references, get type info on hover, list symbols, find implementations, and trace call hierarchies. These operations give Claude more precise navigation than grep-based search, though availability may vary by language and environment.

77 

78If you run into issues, see [Code intelligence troubleshooting](#code-intelligence-issues).

79 

66### External integrations80### External integrations

67 81 

68These plugins bundle pre-configured [MCP servers](/en/mcp) so you can connect Claude to external services without manual setup:82These plugins bundle pre-configured [MCP servers](/en/mcp) so you can connect Claude to external services without manual setup:


366 380 

367For detailed troubleshooting with solutions, see [Troubleshooting](/en/plugin-marketplaces#troubleshooting) in the marketplace guide. For debugging tools, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools).381For detailed troubleshooting with solutions, see [Troubleshooting](/en/plugin-marketplaces#troubleshooting) in the marketplace guide. For debugging tools, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools).

368 382 

383### Code intelligence issues

384 

385* **Language server not starting**: verify the binary is installed and available in your `$PATH`. Check the `/plugin` Errors tab for details.

386* **High memory usage**: language servers like `rust-analyzer` and `pyright` can consume significant memory on large projects. If you experience memory issues, disable the plugin with `/plugin disable <plugin-name>` and rely on Claude's built-in search tools instead.

387* **False positive diagnostics in monorepos**: language servers may report unresolved import errors for internal packages if the workspace isn't configured correctly. These don't affect Claude's ability to edit code.

388 

369## Next steps389## Next steps

370 390 

371* **Build your own plugins**: See [Plugins](/en/plugins) to create skills, agents, and hooks391* **Build your own plugins**: See [Plugins](/en/plugins) to create skills, agents, and hooks

372* **Create a marketplace**: See [Create a plugin marketplace](/en/plugin-marketplaces) to distribute plugins to your team or community392* **Create a marketplace**: See [Create a plugin marketplace](/en/plugin-marketplaces) to distribute plugins to your team or community

373* **Technical reference**: See [Plugins reference](/en/plugins-reference) for complete specifications393* **Technical reference**: See [Plugins reference](/en/plugins-reference) for complete specifications

374 

375 

376 

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

fast-mode.md +131 −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 

17What to know:

18 

19* Use `/fast` to toggle on fast mode in Claude Code CLI. Also available via `/fast` in Claude Code VS Code Extension.

20* Fast mode for Opus 4.6 pricing starts at \$30/150 MTok. Fast mode is available at a 50% discount for all plans until 11:59pm PT on February 16.

21* Available to all Claude Code users on subscription plans (Pro/Max/Team/Enterprise) and Claude Console.

22* 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.

23 

24This 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), and [rate limit behavior](#handle-rate-limits).

25 

26## Toggle fast mode

27 

28Toggle fast mode in either of these ways:

29 

30* Type `/fast` and press Tab to toggle on or off

31* Set `"fastMode": true` in your [user settings file](/en/settings)

32 

33Fast mode persists across sessions. For 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.

34 

35When you enable fast mode:

36 

37* If you're on a different model, Claude Code automatically switches to Opus 4.6

38* You'll see a confirmation message: "Fast mode ON"

39* A small `↯` icon appears next to the prompt while fast mode is active

40* Run `/fast` again at any time to check whether fast mode is on or off

41 

42When 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`.

43 

44## Understand the cost tradeoff

45 

46Fast mode has higher per-token pricing than standard Opus 4.6:

47 

48| Mode | Input (MTok) | Output (MTok) |

49| ------------------------------ | ------------ | ------------- |

50| Fast mode on Opus 4.6 (\<200K) | \$30 | \$150 |

51| Fast mode on Opus 4.6 (>200K) | \$60 | \$225 |

52 

53Fast mode is compatible with the 1M token extended context window.

54 

55When 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.

56 

57## Decide when to use fast mode

58 

59Fast mode is best for interactive work where response latency matters more than cost:

60 

61* Rapid iteration on code changes

62* Live debugging sessions

63* Time-sensitive work with tight deadlines

64 

65Standard mode is better for:

66 

67* Long autonomous tasks where speed matters less

68* Batch processing or CI/CD pipelines

69* Cost-sensitive workloads

70 

71### Fast mode vs effort level

72 

73Fast mode and effort level both affect response speed, but differently:

74 

75| Setting | Effect |

76| ---------------------- | -------------------------------------------------------------------------------- |

77| **Fast mode** | Same model quality, lower latency, higher cost |

78| **Lower effort level** | Less thinking time, faster responses, potentially lower quality on complex tasks |

79 

80You can combine both: use fast mode with a lower [effort level](/en/model-config#adjust-effort-level) for maximum speed on straightforward tasks.

81 

82## Requirements

83 

84Fast mode requires all of the following:

85 

86* **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.

87* **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.

88 

89<Note>

90 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.

91</Note>

92 

93* **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.

94 

95<Note>

96 If your admin has not enabled fast mode for your organization, the `/fast` command will show "Fast mode has been disabled by your organization."

97</Note>

98 

99### Enable fast mode for your organization

100 

101Admins can enable fast mode in:

102 

103* **Console** (API customers): [Claude Code preferences](https://platform.claude.com/claude-code/preferences)

104* **Claude AI** (Teams and Enterprise): [Admin Settings > Claude Code](https://claude.ai/admin-settings/claude-code)

105 

106## Handle rate limits

107 

108Fast 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:

109 

1101. Fast mode automatically falls back to standard Opus 4.6

1112. The `↯` icon turns gray to indicate cooldown

1123. You continue working at standard speed and pricing

1134. When the cooldown expires, fast mode automatically re-enables

114 

115To disable fast mode manually instead of waiting for cooldown, run `/fast` again.

116 

117## Research preview

118 

119Fast mode is a research preview feature. This means:

120 

121* The feature may change based on feedback

122* Availability and pricing are subject to change

123* The underlying API configuration may evolve

124 

125Report issues or feedback through your usual Anthropic support channels.

126 

127## See also

128 

129* [Model configuration](/en/model-config): switch models and adjust effort levels

130* [Manage costs effectively](/en/costs): track token usage and reduce costs

131* [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 


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 | `/review` runs your code review 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 


56 62 

57 **Skills can be reference or action.** Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like `/deploy` that runs your deployment workflow).63 **Skills can be reference or action.** Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like `/deploy` that runs your deployment workflow).

58 64 

59 **Use a subagent** when you need context isolation. The subagent might read dozens of files or run extensive searches, but your main conversation only receives a summary. Custom subagents can have their own instructions and can preload skills.65 **Use a subagent** when you need context isolation or when your context window is getting full. The subagent might read dozens of files or run extensive searches, but your main conversation only receives a summary. Since subagent work doesn't consume your main context, this is also useful when you don't need the intermediate work to remain visible. Custom subagents can have their own instructions and can preload skills.

60 66 

61 **They can combine.** A subagent can preload specific skills (`skills:` field). A skill can run in isolated context using `context: fork`. See [Skills](/en/skills) for details.67 **They can combine.** A subagent can preload specific skills (`skills:` field). A skill can run in isolated context using `context: fork`. See [Skills](/en/skills) for details.

62 </Tab>68 </Tab>


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 \~500 lines. If it's growing, move reference content to skills.

79 </Tab>85 </Tab>

80 86 

87 <Tab title="Subagent vs Agent team">

88 Both parallelize work, but they're architecturally different:

89 

90 * **Subagents** run inside your session and report results back to your main context

91 * **Agent teams** are independent Claude Code sessions that communicate with each other

92 

93 | Aspect | Subagent | Agent team |

94 | ----------------- | ------------------------------------------------ | --------------------------------------------------- |

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

96 | **Communication** | Reports results back to the main agent only | Teammates message each other directly |

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

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

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

100 

101 **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.

102 

103 **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.

104 

105 **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.

106 

107 <Note>

108 Agent teams are experimental and disabled by default. See [agent teams](/en/agent-teams) for setup and current limitations.

109 </Note>

110 </Tab>

111 

81 <Tab title="MCP vs Skill">112 <Tab title="MCP vs Skill">

82 MCP connects Claude to external services. Skills extend what Claude knows, including how to use those services effectively.113 MCP connects Claude to external services. Skills extend what Claude knows, including how to use those services effectively.

83 114 


97 </Tab>128 </Tab>

98</Tabs>129</Tabs>

99 130 

131### Understand how features layer

132 

133Features 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:

134 

135* **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).

136* **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).

137* **MCP servers** override by name: local > project > user. See [MCP scope](/en/mcp#scope-hierarchy-and-precedence).

138* **Hooks** merge: all registered hooks fire for their matching events regardless of source. See [hooks](/en/hooks).

139 

100### Combine features140### Combine features

101 141 

102Each extension solves a different problem: CLAUDE.md handles always-on context, skills handle on-demand knowledge and workflows, MCP handles external connections, subagents handle isolation, and hooks handle automation. Real setups combine them based on your workflow.142Each extension solves a different problem: CLAUDE.md handles always-on context, skills handle on-demand knowledge and workflows, MCP handles external connections, subagents handle isolation, and hooks handle automation. Real setups combine them based on your workflow.


132 172 

133Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context.173Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context.

134 174 

135<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" />175<img src="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/context-loading.svg?fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=43114d93ae62bdc1ab6aa64660e2ba3b" 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/TBPmHzr19mDCuhZi/images/context-loading.svg?w=280&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=cc37ac2b6b486c75dea4cf64add648ec 280w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/context-loading.svg?w=560&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=22394bf8452988091802c6bc471a3153 560w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/context-loading.svg?w=840&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=aaf0301abbd63349b3f5ecf27f3bc4c5 840w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/context-loading.svg?w=1100&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=f262d974340400cfd964c555b523808a 1100w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/context-loading.svg?w=1650&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=430b76391f55ba65a0a3da569a52a450 1650w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/context-loading.svg?w=2500&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=46522043165b15cfef464d5f63c70f7c 2500w" />

136 176 

137<Tabs>177<Tabs>

138 <Tab title="CLAUDE.md">178 <Tab title="CLAUDE.md">


189 </Tab>229 </Tab>

190 230 

191 <Tab title="Hooks">231 <Tab title="Hooks">

192 **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.232 **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.

193 233 

194 **What loads:** Nothing by default. Hooks run as external scripts.234 **What loads:** Nothing by default. Hooks run as external scripts.

195 235 


216 Offload work to isolated context256 Offload work to isolated context

217 </Card>257 </Card>

218 258 

259 <Card title="Agent teams" icon="network" href="/en/agent-teams">

260 Coordinate multiple sessions working in parallel

261 </Card>

262 

219 <Card title="MCP" icon="plug" href="/en/mcp">263 <Card title="MCP" icon="plug" href="/en/mcp">

220 Connect Claude to external services264 Connect Claude to external services

221 </Card>265 </Card>

222 266 

223 <Card title="Hooks" icon="bolt" href="/en/hooks">267 <Card title="Hooks" icon="bolt" href="/en/hooks-guide">

224 Run scripts on Claude Code events268 Automate workflows with hooks

225 </Card>269 </Card>

226 270 

227 <Card title="Plugins" icon="puzzle-piece" href="/en/plugins">271 <Card title="Plugins" icon="puzzle-piece" href="/en/plugins">


232 Host and distribute plugin collections276 Host and distribute plugin collections

233 </Card>277 </Card>

234</CardGroup>278</CardGroup>

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

github-actions.md +17 −17

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


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.

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

9 SDK](https://docs.claude.com/en/docs/agent-sdk), which enables programmatic integration of13 Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), which enables programmatic integration of

10 Claude Code into your applications. You can use the SDK to build custom14 Claude Code into your applications. You can use the SDK to build custom

11 automation workflows beyond GitHub Actions.15 automation workflows beyond GitHub Actions.

12</Note>16</Note>

13 17 

14<Info>18<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`.19 **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>20</Info>

17 21 

18## Why use Claude Code GitHub Actions?22## Why use Claude Code GitHub Actions?


90### Breaking Changes Reference94### Breaking Changes Reference

91 95 

92| Old Beta Input | New v1.0 Input |96| Old Beta Input | New v1.0 Input |

93| --------------------- | -------------------------------- |97| --------------------- | ------------------------------------- |

94| `mode` | *(Removed - auto-detected)* |98| `mode` | *(Removed - auto-detected)* |

95| `direct_prompt` | `prompt` |99| `direct_prompt` | `prompt` |

96| `override_prompt` | `prompt` with GitHub variables |100| `override_prompt` | `prompt` with GitHub variables |

97| `custom_instructions` | `claude_args: --system-prompt` |101| `custom_instructions` | `claude_args: --append-system-prompt` |

98| `max_turns` | `claude_args: --max-turns` |102| `max_turns` | `claude_args: --max-turns` |

99| `model` | `claude_args: --model` |103| `model` | `claude_args: --model` |

100| `allowed_tools` | `claude_args: --allowedTools` |104| `allowed_tools` | `claude_args: --allowedTools` |


113 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}117 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

114 custom_instructions: "Follow our coding standards"118 custom_instructions: "Follow our coding standards"

115 max_turns: "10"119 max_turns: "10"

116 model: "claude-sonnet-4-5-20250929"120 model: "claude-sonnet-4-6"

117```121```

118 122 

119**GA version (v1.0):**123**GA version (v1.0):**


124 prompt: "Review this PR for security issues"128 prompt: "Review this PR for security issues"

125 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}129 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

126 claude_args: |130 claude_args: |

127 --system-prompt "Follow our coding standards"131 --append-system-prompt "Follow our coding standards"

128 --max-turns 10132 --max-turns 10

129 --model claude-sonnet-4-5-20250929133 --model claude-sonnet-4-6

130```134```

131 135 

132<Tip>136<Tip>


189 with:193 with:

190 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}194 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

191 prompt: "Generate a summary of yesterday's commits and open issues"195 prompt: "Generate a summary of yesterday's commits and open issues"

192 claude_args: "--model claude-opus-4-5-20251101"196 claude_args: "--model opus"

193```197```

194 198 

195### Common use cases199### Common use cases


517 with:521 with:

518 github_token: ${{ steps.app-token.outputs.token }}522 github_token: ${{ steps.app-token.outputs.token }}

519 use_bedrock: "true"523 use_bedrock: "true"

520 claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0 --max-turns 10'524 claude_args: '--model us.anthropic.claude-sonnet-4-6 --max-turns 10'

521 ```525 ```

522 526 

523 <Tip>527 <Tip>

524 The model ID format for Bedrock includes the region prefix (e.g., `us.anthropic.claude...`) and version suffix.528 The model ID format for Bedrock includes a region prefix (for example, `us.anthropic.claude-sonnet-4-6`).

525 </Tip>529 </Tip>

526 </Accordion>530 </Accordion>

527 531 


641The `claude_args` parameter accepts any Claude Code CLI arguments:645The `claude_args` parameter accepts any Claude Code CLI arguments:

642 646 

643```yaml theme={null}647```yaml theme={null}

644claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json"648claude_args: "--max-turns 5 --model claude-sonnet-4-6 --mcp-config /path/to/config.json"

645```649```

646 650 

647Common arguments:651Common arguments:

648 652 

649* `--max-turns`: Maximum conversation turns (default: 10)653* `--max-turns`: Maximum conversation turns (default: 10)

650* `--model`: Model to use (for example, `claude-sonnet-4-5-20250929`)654* `--model`: Model to use (for example, `claude-sonnet-4-6`)

651* `--mcp-config`: Path to MCP configuration655* `--mcp-config`: Path to MCP configuration

652* `--allowed-tools`: Comma-separated list of allowed tools656* `--allowed-tools`: Comma-separated list of allowed tools

653* `--debug`: Enable debug output657* `--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.6742. **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 675 

672Claude will follow these guidelines when creating PRs and responding to requests.676Claude 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 +11 −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# 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?


87 claude91 claude

88 -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"92 -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"

89 --permission-mode acceptEdits93 --permission-mode acceptEdits

90 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"94 --allowedTools "Bash Read Edit Write mcp__gitlab"

91 --debug95 --debug

92```96```

93 97 


262 claude266 claude

263 -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"267 -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"

264 --permission-mode acceptEdits268 --permission-mode acceptEdits

265 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"269 --allowedTools "Bash Read Edit Write mcp__gitlab"

266 --debug270 --debug

267 # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables271 # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables

268```272```


308 claude312 claude

309 -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"313 -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"

310 --permission-mode acceptEdits314 --permission-mode acceptEdits

311 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"315 --allowedTools "Bash Read Edit Write mcp__gitlab"

312 --debug316 --debug

313 variables:317 variables:

314 AWS_REGION: "us-west-2"318 AWS_REGION: "us-west-2"

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)


361 claude365 claude

362 -p "${AI_FLOW_INPUT:-'Review and update code as requested'}"366 -p "${AI_FLOW_INPUT:-'Review and update code as requested'}"

363 --permission-mode acceptEdits367 --permission-mode acceptEdits

364 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"368 --allowedTools "Bash Read Edit Write mcp__gitlab"

365 --debug369 --debug

366 variables:370 variables:

367 CLOUD_ML_REGION: "us-east5"371 CLOUD_ML_REGION: "us-east5"


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.

90</Note>

91 91 

92### 5. Model configuration92<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>

93 95 

94Claude Code uses these default models for Vertex AI:96Set these environment variables to specific Vertex AI model IDs:

97 

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 Sonnet 4 and Sonnet 4.6 support the [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) on Vertex AI.

131 139 

132<Note>140<Note>

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.141 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.


157* [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs)165* [Vertex AI documentation](https://cloud.google.com/vertex-ai/docs)

158* [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing)166* [Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing)

159* [Vertex AI quotas and limits](https://cloud.google.com/vertex-ai/docs/quotas)167* [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 +23 −6

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/interactive-mode#built-in-commands) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.


148 Use the Agent SDK in GitLab pipelines169 Use the Agent SDK in GitLab pipelines

149 </Card>170 </Card>

150</CardGroup>171</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 +1118 −825

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, 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 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 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, this arrives on stdin. 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/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=783a0db47dd59602418763e037056d49" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop to SessionEnd" data-og-width="520" width="520" data-og-height="960" height="960" data-path="images/hooks-lifecycle.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?w=280&fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=1fd947ad1c8fc4fcfbe85c8b4b7b528b 280w, https://mintcdn.com/claude-code/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?w=560&fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=794ba776ed6126344835c206f587c9dd 560w, https://mintcdn.com/claude-code/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?w=840&fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=d137272c869dd6f9315ec35f99338289 840w, https://mintcdn.com/claude-code/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?w=1100&fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=531c5f866a6fd56adf94ecfa156ac96a 1100w, https://mintcdn.com/claude-code/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?w=1650&fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=dc81c6d273cd26cd7f9a191ddcb92592 1650w, https://mintcdn.com/claude-code/xcAz1d2i2To-I_QJ/images/hooks-lifecycle.svg?w=2500&fit=max&auto=format&n=xcAz1d2i2To-I_QJ&q=85&s=8f29af9b4145e517655a8bdf7a9987c5 2500w" />

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| `ConfigChange` | When a configuration file changes during a session |

30| `PreCompact` | Before context compaction |42| `PreCompact` | Before context compaction |

31| `SessionEnd` | Session terminates |43| `SessionEnd` | When a session terminates |

32| `Notification` | Claude Code sends notifications |44 

45### How a hook resolves

46 

47To 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:

48 

49```json theme={null}

50{

51 "hooks": {

52 "PreToolUse": [

53 {

54 "matcher": "Bash",

55 "hooks": [

56 {

57 "type": "command",

58 "command": ".claude/hooks/block-rm.sh"

59 }

60 ]

61 }

62 ]

63 }

64}

65```

66 

67The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:

68 

69```bash theme={null}

70#!/bin/bash

71# .claude/hooks/block-rm.sh

72COMMAND=$(jq -r '.tool_input.command')

73 

74if echo "$COMMAND" | grep -q 'rm -rf'; then

75 jq -n '{

76 hookSpecificOutput: {

77 hookEventName: "PreToolUse",

78 permissionDecision: "deny",

79 permissionDecisionReason: "Destructive command blocked by hook"

80 }

81 }'

82else

83 exit 0 # allow the command

84fi

85```

86 

87Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:

88 

89<Frame>

90 <img src="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=5bb890134390ecd0581477cf41ef730b" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" data-og-width="780" width="780" data-og-height="290" height="290" data-path="images/hook-resolution.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=280&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=5dcaecd24c260b8a90365d74e2c1fcda 280w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=560&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=c03d91c279f01d92e58ddd70fdbe66f2 560w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=840&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=1be57a4819cbb949a5ea9d08a05c9ecd 840w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=1100&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=0e9dd1807dc7a5c56011d0889b0d5208 1100w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=1650&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=69496ac02e70fabfece087ba31a1dcfc 1650w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/hook-resolution.svg?w=2500&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=a012346cb46a33b86580348802055267 2500w" />

91</Frame>

92 

93<Steps>

94 <Step title="Event fires">

95 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:

96 

97 ```json theme={null}

98 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }

99 ```

100 </Step>

101 

102 <Step title="Matcher checks">

103 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.

104 </Step>

105 

106 <Step title="Hook handler runs">

107 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:

108 

109 ```json theme={null}

110 {

111 "hookSpecificOutput": {

112 "hookEventName": "PreToolUse",

113 "permissionDecision": "deny",

114 "permissionDecisionReason": "Destructive command blocked by hook"

115 }

116 }

117 ```

118 

119 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.

120 </Step>

121 

122 <Step title="Claude Code acts on the result">

123 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.

124 </Step>

125</Steps>

126 

127The [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.

33 128 

34## Configuration129## Configuration

35 130 

36Claude Code hooks are configured in your [settings files](/en/settings):131Hooks are defined in JSON settings files. The configuration has three levels of nesting:

132 

1331. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`

1342. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"

1353. Define one or more [hook handlers](#hook-handler-fields) to run when matched

37 136 

38* `~/.claude/settings.json` - User settings137See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.

39* `.claude/settings.json` - Project settings

40* `.claude/settings.local.json` - Local project settings (not committed)

41* Managed policy settings

42 138 

43<Note>139<Note>

44 Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration).140 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, prompt, or agent that runs. "Hook" on its own refers to the general feature.

45</Note>141</Note>

46 142 

47### Structure143### Hook locations

48 144 

49Hooks are organized by matchers, where each matcher can have multiple hooks:145Where you define a hook determines its scope:

146 

147| Location | Scope | Shareable |

148| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |

149| `~/.claude/settings.json` | All your projects | No, local to your machine |

150| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

151| `.claude/settings.local.json` | Single project | No, gitignored |

152| Managed policy settings | Organization-wide | Yes, admin-controlled |

153| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

154| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |

155 

156For 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).

157 

158### Matcher patterns

159 

160The `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:

161 

162| Event | What the matcher filters | Example matcher values |

163| :--------------------------------------------------------------------- | :------------------------ | :--------------------------------------------------------------------------------- |

164| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

165| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

166| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

167| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

168| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

169| `PreCompact` | what triggered compaction | `manual`, `auto` |

170| `SubagentStop` | agent type | same values as `SubagentStart` |

171| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

172| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted` | no matcher support | always fires on every occurrence |

173 

174The 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.

175 

176This example runs a linting script only when Claude writes or edits a file:

50 177 

51```json theme={null}178```json theme={null}

52{179{

53 "hooks": {180 "hooks": {

54 "EventName": [181 "PostToolUse": [

55 {182 {

56 "matcher": "ToolPattern",183 "matcher": "Edit|Write",

57 "hooks": [184 "hooks": [

58 {185 {

59 "type": "command",186 "type": "command",

60 "command": "your-command-here"187 "command": "/path/to/lint-check.sh"

61 }188 }

62 ]189 ]

63 }190 }


66}193}

67```194```

68 195 

69* **matcher**: Pattern to match tool names, case-sensitive (only applicable for196`UserPromptSubmit` and `Stop` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.

70 `PreToolUse`, `PermissionRequest`, and `PostToolUse`)197 

71 * Simple strings match exactly: `Write` matches only the Write tool198#### Match MCP tools

72 * Supports regex: `Edit|Write` or `Notebook.*`199 

73 * Use `*` to match all tools. You can also use empty string (`""`) or leave200[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.

74 `matcher` blank.201 

75* **hooks**: Array of hooks to execute when the pattern matches202MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:

76 * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation203 

77 * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable)204* `mcp__memory__create_entities`: Memory server's create entities tool

78 * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation205* `mcp__filesystem__read_file`: Filesystem server's read file tool

79 * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook206* `mcp__github__search_repositories`: GitHub server's search tool

80 207 

81For events like `UserPromptSubmit`, `Stop`, `SubagentStop`, and `Setup`208Use regex patterns to target specific MCP tools or groups of tools:

82that don't use matchers, you can omit the matcher field:209 

210* `mcp__memory__.*` matches all tools from the `memory` server

211* `mcp__.*__write.*` matches any tool containing "write" from any server

212 

213This example logs all memory server operations and validates write operations from any MCP server:

83 214 

84```json theme={null}215```json theme={null}

85{216{

86 "hooks": {217 "hooks": {

87 "UserPromptSubmit": [218 "PreToolUse": [

88 {219 {

220 "matcher": "mcp__memory__.*",

89 "hooks": [221 "hooks": [

90 {222 {

91 "type": "command",223 "type": "command",

92 "command": "/path/to/prompt-validator.py"224 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

225 }

226 ]

227 },

228 {

229 "matcher": "mcp__.*__write.*",

230 "hooks": [

231 {

232 "type": "command",

233 "command": "/home/user/scripts/validate-mcp-write.py"

93 }234 }

94 ]235 ]

95 }236 }


98}239}

99```240```

100 241 

101### Project-Specific Hook Scripts242### Hook handler fields

102 243 

103You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when244Each object in the inner `hooks` array is a hook handler: the shell command, LLM prompt, or agent that runs when the matcher matches. There are three types:

104Claude Code spawns the hook command) to reference scripts stored in your project,

105ensuring they work regardless of Claude's current directory:

106 245 

107```json theme={null}246* **[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.

108{247* **[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).

248* **[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).

249 

250#### Common fields

251 

252These fields apply to all hook types:

253 

254| Field | Required | Description |

255| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |

256| `type` | yes | `"command"`, `"prompt"`, or `"agent"` |

257| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |

258| `statusMessage` | no | Custom spinner message displayed while the hook runs |

259| `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) |

260 

261#### Command hook fields

262 

263In addition to the [common fields](#common-fields), command hooks accept these fields:

264 

265| Field | Required | Description |

266| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ |

267| `command` | yes | Shell command to execute |

268| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |

269 

270#### Prompt and agent hook fields

271 

272In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:

273 

274| Field | Required | Description |

275| :------- | :------- | :------------------------------------------------------------------------------------------ |

276| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

277| `model` | no | Model to use for evaluation. Defaults to a fast model |

278 

279All matching hooks run in parallel, and identical handlers are deduplicated automatically. 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.

280 

281### Reference scripts by path

282 

283Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:

284 

285* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.

286* `${CLAUDE_PLUGIN_ROOT}`: the plugin's root directory, for scripts bundled with a [plugin](/en/plugins).

287 

288<Tabs>

289 <Tab title="Project scripts">

290 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:

291 

292 ```json theme={null}

293 {

109 "hooks": {294 "hooks": {

110 "PostToolUse": [295 "PostToolUse": [

111 {296 {


119 }304 }

120 ]305 ]

121 }306 }

122}307 }

123```308 ```

124 309 </Tab>

125### Plugin hooks

126 

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.

128 

129**How plugin hooks work**:

130 310 

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.311 <Tab title="Plugin scripts">

132* When a plugin is enabled, its hooks are merged with user and project hooks312 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.

133* Multiple hooks from different sources can respond to the same event

134* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files

135 313 

136**Example plugin hook configuration**:314 This example runs a formatting script bundled with the plugin:

137 315 

138```json theme={null}316 ```json theme={null}

139{317 {

140 "description": "Automatic code formatting",318 "description": "Automatic code formatting",

141 "hooks": {319 "hooks": {

142 "PostToolUse": [320 "PostToolUse": [


152 }330 }

153 ]331 ]

154 }332 }

155}333 }

156```334 ```

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 

166**Environment variables for plugins**:

167 

168* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory

169* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)

170* All standard environment variables are available

171 335 

172See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.336 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.

337 </Tab>

338</Tabs>

173 339 

174### Hooks in skills and agents340### Hooks in skills and agents

175 341 

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.342In 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 343 

178**Supported events**: `PreToolUse`, `PostToolUse`, and `Stop`344All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.

345 

346Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.

179 347 

180**Example in a Skill**:348This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:

181 349 

182```yaml theme={null}350```yaml theme={null}

183---351---


192---360---

193```361```

194 362 

195**Example in an agent**:363Agents use the same format in their YAML frontmatter.

196 364 

197```yaml theme={null}365### The `/hooks` menu

198name: code-reviewer

199description: Review code changes

200hooks:

201 PostToolUse:

202 - matcher: "Edit|Write"

203 hooks:

204 - type: command

205 command: "./scripts/run-linter.sh"

206```

207 366 

208Component-scoped hooks follow the same configuration format as settings-based hooks but are automatically cleaned up when the component finishes executing.367Type `/hooks` in Claude Code to open the interactive hooks manager, where you can view, add, and delete hooks without editing settings files directly. For a step-by-step walkthrough, see [Set up your first hook](/en/hooks-guide#set-up-your-first-hook) in the guide.

209 368 

210**Additional option for skills:**369Each hook in the menu is labeled with a bracket prefix indicating its source:

211 370 

212* `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.371* `[User]`: from `~/.claude/settings.json`

372* `[Project]`: from `.claude/settings.json`

373* `[Local]`: from `.claude/settings.local.json`

374* `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only

213 375 

214## Prompt-Based Hooks376### Disable or remove hooks

215 377 

216In 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.378To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.

217 379 

218### How prompt-based hooks work380To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file or use the toggle in the `/hooks` menu. There is no way to disable an individual hook while keeping it in the configuration.

219 381 

220Instead of executing a bash command, prompt-based hooks:382The `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.

221 383 

2221. Send the hook input and your prompt to a fast LLM (Haiku)384Direct edits to hooks in settings files don't take effect immediately. Claude Code captures a snapshot of hooks at startup and uses it throughout the session. This prevents malicious or accidental hook modifications from taking effect mid-session without your review. If hooks are modified externally, Claude Code warns you and requires review in the `/hooks` menu before changes apply.

2232. The LLM responds with structured JSON containing a decision

2243. Claude Code processes the decision automatically

225 385 

226### Configuration386## Hook input and output

227 387 

228```json theme={null}388Hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. 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.

229{

230 "hooks": {

231 "Stop": [

232 {

233 "hooks": [

234 {

235 "type": "prompt",

236 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."

237 }

238 ]

239 }

240 ]

241 }

242}

243```

244 389 

245**Fields:**390### Common input fields

246 391 

247* `type`: Must be `"prompt"`392All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:

248* `prompt`: The prompt text to send to the LLM

249 * Use `$ARGUMENTS` as a placeholder for the hook input JSON

250 * If `$ARGUMENTS` is not present, input JSON is appended to the prompt

251* `timeout`: (Optional) Timeout in seconds (default: 30 seconds)

252 393 

253### Response schema394| Field | Description |

395| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |

396| `session_id` | Current session identifier |

397| `transcript_path` | Path to conversation JSON |

398| `cwd` | Current working directory when the hook is invoked |

399| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |

400| `hook_event_name` | Name of the event that fired |

254 401 

255The LLM must respond with JSON containing:402For example, a `PreToolUse` hook for a Bash command receives this on stdin:

256 403 

257```json theme={null}404```json theme={null}

258{405{

259 "ok": true | false,406 "session_id": "abc123",

260 "reason": "Explanation for the decision"407 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",

408 "cwd": "/home/user/my-project",

409 "permission_mode": "default",

410 "hook_event_name": "PreToolUse",

411 "tool_name": "Bash",

412 "tool_input": {

413 "command": "npm test"

414 }

261}415}

262```416```

263 417 

264**Response fields:**418The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.

265 419 

266* `ok`: `true` allows the action, `false` prevents it420### Exit code output

267* `reason`: Required when `ok` is `false`. Explanation shown to Claude

268 421 

269### Supported hook events422The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.

270 423 

271Prompt-based hooks work with any hook event, but are most useful for:424**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.

272 425 

273* **Stop**: Intelligently decide if Claude should continue working426**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.

274* **SubagentStop**: Evaluate if a subagent has completed its task

275* **UserPromptSubmit**: Validate user prompts with LLM assistance

276* **PreToolUse**: Make context-aware permission decisions

277* **PermissionRequest**: Intelligently allow or deny permission dialogs

278 427 

279### Example: Intelligent Stop hook428**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.

280 

281```json theme={null}

282{

283 "hooks": {

284 "Stop": [

285 {

286 "hooks": [

287 {

288 "type": "prompt",

289 "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.",

290 "timeout": 30

291 }

292 ]

293 }

294 ]

295 }

296}

297```

298 429 

299### Example: SubagentStop with custom logic430For example, a hook command script that blocks dangerous Bash commands:

300 431 

301```json theme={null}432```bash theme={null}

302{433#!/bin/bash

303 "hooks": {434# Reads JSON input from stdin, checks the command

304 "SubagentStop": [435command=$(jq -r '.tool_input.command' < /dev/stdin)

305 {

306 "hooks": [

307 {

308 "type": "prompt",

309 "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."

310 }

311 ]

312 }

313 ]

314 }

315}

316```

317 436 

318### Comparison with bash command hooks437if [[ "$command" == rm* ]]; then

438 echo "Blocked: rm commands are not allowed" >&2

439 exit 2 # Blocking error: tool call is prevented

440fi

319 441 

320| Feature | Bash Command Hooks | Prompt-Based Hooks |442exit 0 # Success: tool call proceeds

321| --------------------- | ----------------------- | ------------------------------ |443```

322| **Execution** | Runs bash script | Queries LLM |

323| **Decision logic** | You implement in code | LLM evaluates context |

324| **Setup complexity** | Requires script file | Configure prompt |

325| **Context awareness** | Limited to script logic | Natural language understanding |

326| **Performance** | Fast (local execution) | Slower (API call) |

327| **Use case** | Deterministic rules | Context-aware decisions |

328 444 

329### Best practices445#### Exit code 2 behavior per event

330 446 

331* **Be specific in prompts**: Clearly state what you want the LLM to evaluate447Exit 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.

332* **Include decision criteria**: List the factors the LLM should consider

333* **Test your prompts**: Verify the LLM makes correct decisions for your use cases

334* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed

335* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules

336 448 

337See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.449| Hook event | Can block? | What happens on exit 2 |

450| :------------------- | :--------- | :---------------------------------------------------------------------------- |

451| `PreToolUse` | Yes | Blocks the tool call |

452| `PermissionRequest` | Yes | Denies the permission |

453| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |

454| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |

455| `SubagentStop` | Yes | Prevents the subagent from stopping |

456| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |

457| `TaskCompleted` | Yes | Prevents the task from being marked as completed |

458| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |

459| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |

460| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |

461| `Notification` | No | Shows stderr to user only |

462| `SubagentStart` | No | Shows stderr to user only |

463| `SessionStart` | No | Shows stderr to user only |

464| `SessionEnd` | No | Shows stderr to user only |

465| `PreCompact` | No | Shows stderr to user only |

338 466 

339## Hook Events467### JSON output

340 468 

341### PreToolUse469Exit 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.

342 470 

343Runs after Claude creates tool parameters and before processing the tool call.471<Note>

472 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.

473</Note>

344 474 

345**Common matchers:**475Your 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.

346 476 

347* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents))477The JSON object supports three kinds of fields:

348* `Bash` - Shell commands

349* `Glob` - File pattern matching

350* `Grep` - Content search

351* `Read` - File reading

352* `Edit` - File editing

353* `Write` - File writing

354* `WebFetch`, `WebSearch` - Web operations

355 478 

356Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.479* **Universal fields** like `continue` work across all events. These are listed in the table below.

480* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.

481* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.

357 482 

358### PermissionRequest483| Field | Default | Description |

484| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |

485| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |

486| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |

487| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |

488| `systemMessage` | none | Warning message shown to the user |

359 489 

360Runs when the user is shown a permission dialog.490To stop Claude entirely regardless of event type:

361Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

362 491 

363Recognizes the same matcher values as PreToolUse.492```json theme={null}

493{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }

494```

364 495 

365### PostToolUse496#### Decision control

366 497 

367Runs immediately after a tool completes successfully.498Not 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:

368 499 

369Recognizes the same matcher values as PreToolUse.500| Events | Decision pattern | Key fields |

501| :---------------------------------------------------------------------------------- | :------------------- | :---------------------------------------------------------------- |

502| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |

503| TeammateIdle, TaskCompleted | Exit code only | Exit code 2 blocks the action, stderr is fed back as feedback |

504| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |

505| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |

370 506 

371### Notification507Here are examples of each pattern in action:

372 508 

373Runs when Claude Code sends notifications. Supports matchers to filter by notification type.509<Tabs>

510 <Tab title="Top-level decision">

511 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SubagentStop`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:

374 512 

375**Common matchers:**513 ```json theme={null}

514 {

515 "decision": "block",

516 "reason": "Test suite must pass before proceeding"

517 }

518 ```

519 </Tab>

376 520 

377* `permission_prompt` - Permission requests from Claude Code521 <Tab title="PreToolUse">

378* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time)522 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.

379* `auth_success` - Authentication success notifications

380* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation

381 523 

382You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications.524 ```json theme={null}

525 {

526 "hookSpecificOutput": {

527 "hookEventName": "PreToolUse",

528 "permissionDecision": "deny",

529 "permissionDecisionReason": "Database writes are not allowed"

530 }

531 }

532 ```

533 </Tab>

383 534 

384**Example: Different notifications for different types**535 <Tab title="PermissionRequest">

536 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.

385 537 

386```json theme={null}538 ```json theme={null}

387{

388 "hooks": {

389 "Notification": [

390 {

391 "matcher": "permission_prompt",

392 "hooks": [

393 {539 {

394 "type": "command",540 "hookSpecificOutput": {

395 "command": "/path/to/permission-alert.sh"541 "hookEventName": "PermissionRequest",

542 "decision": {

543 "behavior": "allow",

544 "updatedInput": {

545 "command": "npm run lint"

396 }546 }

397 ]

398 },

399 {

400 "matcher": "idle_prompt",

401 "hooks": [

402 {

403 "type": "command",

404 "command": "/path/to/idle-notification.sh"

405 }547 }

406 ]

407 }548 }

408 ]

409 }549 }

410}550 ```

411```551 </Tab>

552</Tabs>

412 553 

413### UserPromptSubmit554For 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).

414 

415Runs when the user submits a prompt, before Claude processes it. This allows you

416to add additional context based on the prompt/conversation, validate prompts, or

417block certain types of prompts.

418 555 

419### Stop556## Hook events

420 557 

421Runs when the main Claude Code agent has finished responding. Does not run if558Each 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.

422the stoppage occurred due to a user interrupt.

423 559 

424### SubagentStop560### SessionStart

425 561 

426Runs when a Claude Code subagent (Task tool call) has finished responding.562Runs 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.

427 563 

428### PreCompact564SessionStart runs on every session, so keep these hooks fast.

429 565 

430Runs before Claude Code is about to run a compact operation.566The matcher value corresponds to how the session was initiated:

431 567 

432**Matchers:**568| Matcher | When it fires |

569| :-------- | :------------------------------------- |

570| `startup` | New session |

571| `resume` | `--resume`, `--continue`, or `/resume` |

572| `clear` | `/clear` |

573| `compact` | Auto or manual compaction |

433 574 

434* `manual` - Invoked from `/compact`575#### SessionStart input

435* `auto` - Invoked from auto-compact (due to full context window)

436 576 

437### Setup577In 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.

438 578 

439Runs 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.579```json theme={null}

440 580{

441<Note>581 "session_id": "abc123",

442 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.582 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

443</Note>583 "cwd": "/Users/...",

444 584 "permission_mode": "default",

445**Matchers:**585 "hook_event_name": "SessionStart",

446 586 "source": "startup",

447* `init` - Invoked from `--init` or `--init-only` flags587 "model": "claude-sonnet-4-6"

448* `maintenance` - Invoked from `--maintenance` flag588}

589```

449 590 

450Setup hooks have access to the `CLAUDE_ENV_FILE` environment variable for persisting environment variables, similar to SessionStart hooks.591#### SessionStart decision control

451 592 

452### SessionStart593Any 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:

453 594 

454Runs when Claude Code starts a new session or resumes an existing session (which595| Field | Description |

455currently 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.596| :------------------ | :------------------------------------------------------------------------ |

597| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |

456 598 

457<Note>599```json theme={null}

458 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.600{

459</Note>601 "hookSpecificOutput": {

460 602 "hookEventName": "SessionStart",

461**Matchers:**603 "additionalContext": "My additional context here"

462 604 }

463* `startup` - Invoked from startup605}

464* `resume` - Invoked from `--resume`, `--continue`, or `/resume`606```

465* `clear` - Invoked from `/clear`

466* `compact` - Invoked from auto or manual compact.

467 607 

468#### Persisting environment variables608#### Persist environment variables

469 609 

470SessionStart 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.610SessionStart 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.

471 611 

472**Example: Setting individual environment variables**612To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:

473 613 

474```bash theme={null}614```bash theme={null}

475#!/bin/bash615#!/bin/bash

476 616 

477if [ -n "$CLAUDE_ENV_FILE" ]; then617if [ -n "$CLAUDE_ENV_FILE" ]; then

478 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"618 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"

479 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"619 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"

480 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"620 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"

481fi621fi

482 622 

483exit 0623exit 0

484```624```

485 625 

486**Example: Persisting all environment changes from the hook**626To capture all environment changes from setup commands, compare the exported variables before and after:

487 

488When your setup modifies the environment (for example, `nvm use`), capture and persist all changes by diffing the environment:

489 627 

490```bash theme={null}628```bash theme={null}

491#!/bin/bash629#!/bin/bash


506exit 0642exit 0

507```643```

508 644 

509Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.645Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.

510 646 

511<Note>647<Note>

512 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.648 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.

513</Note>649</Note>

514 650 

515### SessionEnd651### UserPromptSubmit

516 652 

517Runs when a Claude Code session ends. Useful for cleanup tasks, logging session653Runs when the user submits a prompt, before Claude processes it. This allows you

518statistics, or saving session state.654to add additional context based on the prompt/conversation, validate prompts, or

655block certain types of prompts.

656 

657#### UserPromptSubmit input

658 

659In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.

660 

661```json theme={null}

662{

663 "session_id": "abc123",

664 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

665 "cwd": "/Users/...",

666 "permission_mode": "default",

667 "hook_event_name": "UserPromptSubmit",

668 "prompt": "Write a function to calculate the factorial of a number"

669}

670```

671 

672#### UserPromptSubmit decision control

673 

674`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.

519 675 

520The `reason` field in the hook input will be one of:676There are two ways to add context to the conversation on exit code 0:

521 677 

522* `clear` - Session cleared with /clear command678* **Plain text stdout**: any non-JSON text written to stdout is added as context

523* `logout` - User logged out679* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context

524* `prompt_input_exit` - User exited while prompt input was visible

525* `other` - Other exit reasons

526 680 

527## Hook Input681Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.

528 682 

529Hooks receive JSON data via stdin containing session information and683To block a prompt, return a JSON object with `decision` set to `"block"`:

530event-specific data:

531 684 

532```typescript theme={null}685| Field | Description |

686| :------------------ | :----------------------------------------------------------------------------------------------------------------- |

687| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |

688| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |

689| `additionalContext` | String added to Claude's context |

690 

691```json theme={null}

533{692{

534 // Common fields693 "decision": "block",

535 session_id: string694 "reason": "Explanation for decision",

536 transcript_path: string // Path to conversation JSON695 "hookSpecificOutput": {

537 cwd: string // The current working directory when the hook is invoked696 "hookEventName": "UserPromptSubmit",

538 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", "dontAsk", or "bypassPermissions"697 "additionalContext": "My additional context here"

539 698 }

540 // Event-specific fields

541 hook_event_name: string

542 ...

543}699}

544```700```

545 701 

546### PreToolUse Input702<Note>

703 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

704 block prompts or want more structured control.

705</Note>

706 

707### PreToolUse

708 

709Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).

710 

711Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.

712 

713#### PreToolUse input

714 

715In 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:

716 

717##### Bash

718 

719Executes shell commands.

720 

721| Field | Type | Example | Description |

722| :------------------ | :------ | :----------------- | :-------------------------------------------- |

723| `command` | string | `"npm test"` | The shell command to execute |

724| `description` | string | `"Run test suite"` | Optional description of what the command does |

725| `timeout` | number | `120000` | Optional timeout in milliseconds |

726| `run_in_background` | boolean | `false` | Whether to run the command in background |

727 

728##### Write

729 

730Creates or overwrites a file.

731 

732| Field | Type | Example | Description |

733| :---------- | :----- | :-------------------- | :--------------------------------- |

734| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |

735| `content` | string | `"file content"` | Content to write to the file |

547 736 

548The exact schema for `tool_input` depends on the tool. Here are examples for commonly hooked tools.737##### Edit

549 738 

550#### Bash tool739Replaces a string in an existing file.

551 740 

552The Bash tool is the most commonly hooked tool for command validation:741| Field | Type | Example | Description |

742| :------------ | :------ | :-------------------- | :--------------------------------- |

743| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |

744| `old_string` | string | `"original text"` | Text to find and replace |

745| `new_string` | string | `"replacement text"` | Replacement text |

746| `replace_all` | boolean | `false` | Whether to replace all occurrences |

747 

748##### Read

749 

750Reads file contents.

751 

752| Field | Type | Example | Description |

753| :---------- | :----- | :-------------------- | :----------------------------------------- |

754| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |

755| `offset` | number | `10` | Optional line number to start reading from |

756| `limit` | number | `50` | Optional number of lines to read |

757 

758##### Glob

759 

760Finds files matching a glob pattern.

761 

762| Field | Type | Example | Description |

763| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |

764| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |

765| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |

766 

767##### Grep

768 

769Searches file contents with regular expressions.

770 

771| Field | Type | Example | Description |

772| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |

773| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |

774| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |

775| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |

776| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |

777| `-i` | boolean | `true` | Case insensitive search |

778| `multiline` | boolean | `false` | Enable multiline matching |

779 

780##### WebFetch

781 

782Fetches and processes web content.

783 

784| Field | Type | Example | Description |

785| :------- | :----- | :---------------------------- | :----------------------------------- |

786| `url` | string | `"https://example.com/api"` | URL to fetch content from |

787| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |

788 

789##### WebSearch

790 

791Searches the web.

792 

793| Field | Type | Example | Description |

794| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |

795| `query` | string | `"react hooks best practices"` | Search query |

796| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |

797| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |

798 

799##### Task

800 

801Spawns a [subagent](/en/sub-agents).

802 

803| Field | Type | Example | Description |

804| :-------------- | :----- | :------------------------- | :------------------------------------------- |

805| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |

806| `description` | string | `"Find API endpoints"` | Short description of the task |

807| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |

808| `model` | string | `"sonnet"` | Optional model alias to override the default |

809 

810#### PreToolUse decision control

811 

812`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.

813 

814| Field | Description |

815| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |

816| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |

817| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |

818| `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 |

819| `additionalContext` | String added to Claude's context before the tool executes |

820 

821```json theme={null}

822{

823 "hookSpecificOutput": {

824 "hookEventName": "PreToolUse",

825 "permissionDecision": "allow",

826 "permissionDecisionReason": "My reason here",

827 "updatedInput": {

828 "field_to_modify": "new value"

829 },

830 "additionalContext": "Current environment: production. Proceed with caution."

831 }

832}

833```

834 

835<Note>

836 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.

837</Note>

838 

839### PermissionRequest

840 

841Runs when the user is shown a permission dialog.

842Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

843 

844Matches on tool name, same values as PreToolUse.

845 

846#### PermissionRequest input

847 

848PermissionRequest 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.

553 849 

554```json theme={null}850```json theme={null}

555{851{


557 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",853 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

558 "cwd": "/Users/...",854 "cwd": "/Users/...",

559 "permission_mode": "default",855 "permission_mode": "default",

560 "hook_event_name": "PreToolUse",856 "hook_event_name": "PermissionRequest",

561 "tool_name": "Bash",857 "tool_name": "Bash",

562 "tool_input": {858 "tool_input": {

563 "command": "psql -c 'SELECT * FROM users'",859 "command": "rm -rf node_modules",

564 "description": "Query the users table",860 "description": "Remove node_modules directory"

565 "timeout": 120000

566 },861 },

567 "tool_use_id": "toolu_01ABC123..."862 "permission_suggestions": [

863 { "type": "toolAlwaysAllow", "tool": "Bash" }

864 ]

568}865}

569```866```

570 867 

571| Field | Type | Description |868#### PermissionRequest decision control

572| :------------------ | :------ | :-------------------------------------------- |869 

573| `command` | string | The shell command to execute |870`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:

574| `description` | string | Optional description of what the command does |

575| `timeout` | number | Optional timeout in milliseconds |

576| `run_in_background` | boolean | Whether to run the command in background |

577 871 

578#### Write tool872| Field | Description |

873| :------------------- | :------------------------------------------------------------------------------------------------------------- |

874| `behavior` | `"allow"` grants the permission, `"deny"` denies it |

875| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |

876| `updatedPermissions` | For `"allow"` only: applies permission rule updates, equivalent to the user selecting an "always allow" option |

877| `message` | For `"deny"` only: tells Claude why the permission was denied |

878| `interrupt` | For `"deny"` only: if `true`, stops Claude |

879 

880```json theme={null}

881{

882 "hookSpecificOutput": {

883 "hookEventName": "PermissionRequest",

884 "decision": {

885 "behavior": "allow",

886 "updatedInput": {

887 "command": "npm run lint"

888 }

889 }

890 }

891}

892```

893 

894### PostToolUse

895 

896Runs immediately after a tool completes successfully.

897 

898Matches on tool name, same values as PreToolUse.

899 

900#### PostToolUse input

901 

902`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.

579 903 

580```json theme={null}904```json theme={null}

581{905{


583 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",907 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

584 "cwd": "/Users/...",908 "cwd": "/Users/...",

585 "permission_mode": "default",909 "permission_mode": "default",

586 "hook_event_name": "PreToolUse",910 "hook_event_name": "PostToolUse",

587 "tool_name": "Write",911 "tool_name": "Write",

588 "tool_input": {912 "tool_input": {

589 "file_path": "/path/to/file.txt",913 "file_path": "/path/to/file.txt",

590 "content": "file content"914 "content": "file content"

591 },915 },

916 "tool_response": {

917 "filePath": "/path/to/file.txt",

918 "success": true

919 },

592 "tool_use_id": "toolu_01ABC123..."920 "tool_use_id": "toolu_01ABC123..."

593}921}

594```922```

595 923 

596| Field | Type | Description |924#### PostToolUse decision control

597| :---------- | :----- | :--------------------------------- |925 

598| `file_path` | string | Absolute path to the file to write |926`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:

599| `content` | string | Content to write to the file |

600 927 

601#### Edit tool928| Field | Description |

929| :--------------------- | :----------------------------------------------------------------------------------------- |

930| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |

931| `reason` | Explanation shown to Claude when `decision` is `"block"` |

932| `additionalContext` | Additional context for Claude to consider |

933| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |

602 934 

603```json theme={null}935```json theme={null}

604{936{

605 "session_id": "abc123",937 "decision": "block",

606 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",938 "reason": "Explanation for decision",

607 "cwd": "/Users/...",939 "hookSpecificOutput": {

608 "permission_mode": "default",940 "hookEventName": "PostToolUse",

609 "hook_event_name": "PreToolUse",941 "additionalContext": "Additional information for Claude"

610 "tool_name": "Edit",942 }

611 "tool_input": {

612 "file_path": "/path/to/file.txt",

613 "old_string": "original text",

614 "new_string": "replacement text"

615 },

616 "tool_use_id": "toolu_01ABC123..."

617}943}

618```944```

619 945 

620| Field | Type | Description |946### PostToolUseFailure

621| :------------ | :------ | :-------------------------------------------------- |947 

622| `file_path` | string | Absolute path to the file to edit |948Runs 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.

623| `old_string` | string | Text to find and replace |949 

624| `new_string` | string | Replacement text |950Matches on tool name, same values as PreToolUse.

625| `replace_all` | boolean | Whether to replace all occurrences (default: false) |951 

952#### PostToolUseFailure input

626 953 

627#### Read tool954PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:

628 955 

629```json theme={null}956```json theme={null}

630{957{


632 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",959 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

633 "cwd": "/Users/...",960 "cwd": "/Users/...",

634 "permission_mode": "default",961 "permission_mode": "default",

635 "hook_event_name": "PreToolUse",962 "hook_event_name": "PostToolUseFailure",

636 "tool_name": "Read",963 "tool_name": "Bash",

637 "tool_input": {964 "tool_input": {

638 "file_path": "/path/to/file.txt"965 "command": "npm test",

966 "description": "Run test suite"

639 },967 },

640 "tool_use_id": "toolu_01ABC123..."968 "tool_use_id": "toolu_01ABC123...",

969 "error": "Command exited with non-zero status code 1",

970 "is_interrupt": false

641}971}

642```972```

643 973 

644| Field | Type | Description |974| Field | Description |

645| :---------- | :----- | :----------------------------------------- |975| :------------- | :------------------------------------------------------------------------------ |

646| `file_path` | string | Absolute path to the file to read |976| `error` | String describing what went wrong |

647| `offset` | number | Optional line number to start reading from |977| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |

648| `limit` | number | Optional number of lines to read |

649 978 

650### PostToolUse Input979#### PostToolUseFailure decision control

651 980 

652The exact schema for `tool_input` and `tool_response` depends on the tool.981`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:

982 

983| Field | Description |

984| :------------------ | :------------------------------------------------------------ |

985| `additionalContext` | Additional context for Claude to consider alongside the error |

653 986 

654```json theme={null}987```json theme={null}

655{988{

656 "session_id": "abc123",989 "hookSpecificOutput": {

657 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",990 "hookEventName": "PostToolUseFailure",

658 "cwd": "/Users/...",991 "additionalContext": "Additional information about the failure for Claude"

659 "permission_mode": "default",992 }

660 "hook_event_name": "PostToolUse",993}

661 "tool_name": "Write",994```

662 "tool_input": {995 

663 "file_path": "/path/to/file.txt",996### Notification

664 "content": "file content"997 

665 },998Runs 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.

666 "tool_response": {999 

667 "filePath": "/path/to/file.txt",1000Use 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:

668 "success": true1001 

1002```json theme={null}

1003{

1004 "hooks": {

1005 "Notification": [

1006 {

1007 "matcher": "permission_prompt",

1008 "hooks": [

1009 {

1010 "type": "command",

1011 "command": "/path/to/permission-alert.sh"

1012 }

1013 ]

669 },1014 },

670 "tool_use_id": "toolu_01ABC123..."1015 {

1016 "matcher": "idle_prompt",

1017 "hooks": [

1018 {

1019 "type": "command",

1020 "command": "/path/to/idle-notification.sh"

1021 }

1022 ]

1023 }

1024 ]

1025 }

671}1026}

672```1027```

673 1028 

674### Notification Input1029#### Notification input

1030 

1031In 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 1032 

676```json theme={null}1033```json theme={null}

677{1034{


681 "permission_mode": "default",1038 "permission_mode": "default",

682 "hook_event_name": "Notification",1039 "hook_event_name": "Notification",

683 "message": "Claude needs your permission to use Bash",1040 "message": "Claude needs your permission to use Bash",

1041 "title": "Permission needed",

684 "notification_type": "permission_prompt"1042 "notification_type": "permission_prompt"

685}1043}

686```1044```

687 1045 

688### UserPromptSubmit Input1046Notification 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:

1047 

1048| Field | Description |

1049| :------------------ | :------------------------------- |

1050| `additionalContext` | String added to Claude's context |

1051 

1052### SubagentStart

1053 

1054Runs when a Claude Code subagent is spawned via the Task tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).

1055 

1056#### SubagentStart input

1057 

1058In 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).

689 1059 

690```json theme={null}1060```json theme={null}

691{1061{


693 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1063 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

694 "cwd": "/Users/...",1064 "cwd": "/Users/...",

695 "permission_mode": "default",1065 "permission_mode": "default",

696 "hook_event_name": "UserPromptSubmit",1066 "hook_event_name": "SubagentStart",

697 "prompt": "Write a function to calculate the factorial of a number"1067 "agent_id": "agent-abc123",

1068 "agent_type": "Explore"

698}1069}

699```1070```

700 1071 

701### Stop and SubagentStop Input1072SubagentStart 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:

702 1073 

703`stop_hook_active` is true when Claude Code is already continuing as a result of1074| Field | Description |

704a stop hook. Check this value or process the transcript to prevent Claude Code1075| :------------------ | :------------------------------------- |

705from running indefinitely.1076| `additionalContext` | String added to the subagent's context |

706 1077 

707```json theme={null}1078```json theme={null}

708{1079{

709 "session_id": "abc123",1080 "hookSpecificOutput": {

710 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1081 "hookEventName": "SubagentStart",

711 "permission_mode": "default",1082 "additionalContext": "Follow security guidelines for this task"

712 "hook_event_name": "Stop",1083 }

713 "stop_hook_active": true

714}1084}

715```1085```

716 1086 

717### PreCompact Input1087### SubagentStop

1088 

1089Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.

1090 

1091#### SubagentStop input

718 1092 

719For `manual`, `custom_instructions` comes from what the user passes into1093In 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.

720`/compact`. For `auto`, `custom_instructions` is empty.

721 1094 

722```json theme={null}1095```json theme={null}

723{1096{

724 "session_id": "abc123",1097 "session_id": "abc123",

725 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1098 "transcript_path": "~/.claude/projects/.../abc123.jsonl",

1099 "cwd": "/Users/...",

726 "permission_mode": "default",1100 "permission_mode": "default",

727 "hook_event_name": "PreCompact",1101 "hook_event_name": "SubagentStop",

728 "trigger": "manual",1102 "stop_hook_active": false,

729 "custom_instructions": ""1103 "agent_id": "def456",

1104 "agent_type": "Explore",

1105 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",

1106 "last_assistant_message": "Analysis complete. Found 3 potential issues..."

730}1107}

731```1108```

732 1109 

733### Setup Input1110SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).

1111 

1112### Stop

1113 

1114Runs when the main Claude Code agent has finished responding. Does not run if

1115the stoppage occurred due to a user interrupt.

1116 

1117#### Stop input

1118 

1119In 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.

734 1120 

735```json theme={null}1121```json theme={null}

736{1122{


738 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1124 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

739 "cwd": "/Users/...",1125 "cwd": "/Users/...",

740 "permission_mode": "default",1126 "permission_mode": "default",

741 "hook_event_name": "Setup",1127 "hook_event_name": "Stop",

742 "trigger": "init"1128 "stop_hook_active": true,

1129 "last_assistant_message": "I've completed the refactoring. Here's a summary..."

743}1130}

744```1131```

745 1132 

746The `trigger` field will be either `"init"` (from `--init` or `--init-only`) or `"maintenance"` (from `--maintenance`).1133#### Stop decision control

1134 

1135`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:

747 1136 

748### SessionStart Input1137| Field | Description |

1138| :--------- | :------------------------------------------------------------------------- |

1139| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |

1140| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |

749 1141 

750```json theme={null}1142```json theme={null}

751{1143{

752 "session_id": "abc123",1144 "decision": "block",

753 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1145 "reason": "Must be provided when Claude is blocked from stopping"

754 "permission_mode": "default",

755 "hook_event_name": "SessionStart",

756 "source": "startup"

757}1146}

758```1147```

759 1148 

760### SessionEnd Input1149### TeammateIdle

1150 

1151Runs 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.

1152 

1153When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. TeammateIdle hooks do not support matchers and fire on every occurrence.

1154 

1155#### TeammateIdle input

1156 

1157In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.

761 1158 

762```json theme={null}1159```json theme={null}

763{1160{

764 "session_id": "abc123",1161 "session_id": "abc123",

765 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1162 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

766 "cwd": "/Users/...",1163 "cwd": "/Users/...",

767 "permission_mode": "default",1164 "permission_mode": "default",

768 "hook_event_name": "SessionEnd",1165 "hook_event_name": "TeammateIdle",

769 "reason": "exit"1166 "teammate_name": "researcher",

1167 "team_name": "my-project"

770}1168}

771```1169```

772 1170 

773## Hook Output1171| Field | Description |

774 1172| :-------------- | :-------------------------------------------- |

775There are two mutually exclusive ways for hooks to return output back to Claude Code. The output1173| `teammate_name` | Name of the teammate that is about to go idle |

776communicates whether to block and any feedback that should be shown to Claude1174| `team_name` | Name of the team |

777and the user.

778 1175 

779### Simple: Exit Code1176#### TeammateIdle decision control

780 1177 

781Hooks communicate status through exit codes, stdout, and stderr:1178TeammateIdle hooks use exit codes only, not JSON decision control. This example checks that a build artifact exists before allowing a teammate to go idle:

782 1179 

783* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode1180```bash theme={null}

784 (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is1181#!/bin/bash

785 added to the context. JSON output in `stdout` is parsed for structured control

786 (see [Advanced: JSON Output](#advanced-json-output)).

787* **Exit code 2**: Blocking error. Only `stderr` is used as the error message

788 and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout`

789 is **not** processed for exit code 2. See per-hook-event behavior below.

790* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with

791 format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty,

792 it shows `No stderr output`. Execution continues.

793 

794<Warning>

795 Reminder: Claude Code does not see stdout if the exit code is 0, except for

796 the `UserPromptSubmit` hook where stdout is injected as context.

797</Warning>

798 1182 

799#### Exit Code 2 Behavior1183if [ ! -f "./dist/output.js" ]; then

1184 echo "Build artifact missing. Run the build before stopping." >&2

1185 exit 2

1186fi

800 1187 

801| Hook Event | Behavior |1188exit 0

802| ------------------- | ------------------------------------------------------------------ |1189```

803| `PreToolUse` | Blocks the tool call, shows stderr to Claude |

804| `PermissionRequest` | Denies the permission, shows stderr to Claude |

805| `PostToolUse` | Shows stderr to Claude (tool already ran) |

806| `Notification` | N/A, shows stderr to user only |

807| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |

808| `Stop` | Blocks stoppage, shows stderr to Claude |

809| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |

810| `PreCompact` | N/A, shows stderr to user only |

811| `Setup` | N/A, shows stderr to user only |

812| `SessionStart` | N/A, shows stderr to user only |

813| `SessionEnd` | N/A, shows stderr to user only |

814 1190 

815### Advanced: JSON Output1191### TaskCompleted

816 1192 

817Hooks can return structured JSON in `stdout` for more sophisticated control.1193Runs 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.

818 1194 

819<Warning>1195When 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. TaskCompleted hooks do not support matchers and fire on every occurrence.

820 JSON output is only processed when the hook exits with code 0. If your hook

821 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`

822 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).

823</Warning>

824 1196 

825#### Common JSON Fields1197#### TaskCompleted input

826 1198 

827All hook types can include these optional fields:1199In 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`.

828 1200 

829```json theme={null}1201```json theme={null}

830{1202{

831 "continue": true, // Whether Claude should continue after hook execution (default: true)1203 "session_id": "abc123",

832 "stopReason": "string", // Message shown when continue is false1204 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

833 1205 "cwd": "/Users/...",

834 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1206 "permission_mode": "default",

835 "systemMessage": "string" // Optional warning message shown to the user1207 "hook_event_name": "TaskCompleted",

1208 "task_id": "task-001",

1209 "task_subject": "Implement user authentication",

1210 "task_description": "Add login and signup endpoints",

1211 "teammate_name": "implementer",

1212 "team_name": "my-project"

836}1213}

837```1214```

838 1215 

839If `continue` is false, Claude stops processing after the hooks run.1216| Field | Description |

1217| :----------------- | :------------------------------------------------------ |

1218| `task_id` | Identifier of the task being completed |

1219| `task_subject` | Title of the task |

1220| `task_description` | Detailed description of the task. May be absent |

1221| `teammate_name` | Name of the teammate completing the task. May be absent |

1222| `team_name` | Name of the team. May be absent |

1223 

1224#### TaskCompleted decision control

840 1225 

841* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which1226TaskCompleted hooks use exit codes only, not JSON decision control. This example runs tests and blocks task completion if they fail:

842 only blocks a specific tool call and provides automatic feedback to Claude.1227 

843* For `PostToolUse`, this is different from `"decision": "block"`, which1228```bash theme={null}

844 provides automated feedback to Claude.1229#!/bin/bash

845* For `UserPromptSubmit`, this prevents the prompt from being processed.1230INPUT=$(cat)

846* For `Stop` and `SubagentStop`, this takes precedence over any1231TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

847 `"decision": "block"` output.

848* In all cases, `"continue" = false` takes precedence over any

849 `"decision": "block"` output.

850 1232 

851`stopReason` accompanies `continue` with a reason shown to the user, not shown1233# Run the test suite

852to Claude.1234if ! npm test 2>&1; then

1235 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2

1236 exit 2

1237fi

853 1238 

854#### `PreToolUse` Decision Control1239exit 0

1240```

855 1241 

856`PreToolUse` hooks can control whether a tool call proceeds.1242### ConfigChange

857 1243 

858* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown1244Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.

859 to the user but not to Claude.

860* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is

861 shown to Claude.

862* `"ask"` asks the user to confirm the tool call in the UI.

863 `permissionDecisionReason` is shown to the user but not to Claude.

864 1245 

865Additionally, hooks can modify tool inputs before execution using `updatedInput`:1246ConfigChange 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.

866 1247 

867* `updatedInput` modifies the tool's input parameters before the tool executes1248The matcher filters on the configuration source:

868* Combine with `"permissionDecision": "allow"` to modify the input and auto-approve the tool call

869* Combine with `"permissionDecision": "ask"` to modify the input and show it to the user for confirmation

870 1249 

871Hooks can also provide context to Claude using `additionalContext`:1250| Matcher | When it fires |

1251| :----------------- | :---------------------------------------- |

1252| `user_settings` | `~/.claude/settings.json` changes |

1253| `project_settings` | `.claude/settings.json` changes |

1254| `local_settings` | `.claude/settings.local.json` changes |

1255| `policy_settings` | Managed policy settings change |

1256| `skills` | A skill file in `.claude/skills/` changes |

872 1257 

873* `"hookSpecificOutput.additionalContext"` adds a string to Claude's context before the tool executes.1258This example logs all configuration changes for security auditing:

874 1259 

875```json theme={null}1260```json theme={null}

876{1261{

877 "hookSpecificOutput": {1262 "hooks": {

878 "hookEventName": "PreToolUse",1263 "ConfigChange": [

879 "permissionDecision": "allow",1264 {

880 "permissionDecisionReason": "My reason here",1265 "hooks": [

881 "updatedInput": {1266 {

882 "field_to_modify": "new value"1267 "type": "command",

883 },1268 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"

884 "additionalContext": "Current environment: production. Proceed with caution."1269 }

1270 ]

1271 }

1272 ]

885 }1273 }

886}1274}

887```1275```

888 1276 

889<Note>1277#### ConfigChange input

890 The `decision` and `reason` fields are deprecated for PreToolUse hooks.

891 Use `hookSpecificOutput.permissionDecision` and

892 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields

893 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.

894</Note>

895 

896#### `PermissionRequest` Decision Control

897 1278 

898`PermissionRequest` hooks can allow or deny permission requests shown to the user.1279In 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.

899 

900* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes.

901* 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.

902 1280 

903```json theme={null}1281```json theme={null}

904{1282{

905 "hookSpecificOutput": {1283 "session_id": "abc123",

906 "hookEventName": "PermissionRequest",1284 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

907 "decision": {1285 "cwd": "/Users/...",

908 "behavior": "allow",1286 "permission_mode": "default",

909 "updatedInput": {1287 "hook_event_name": "ConfigChange",

910 "command": "npm run lint"1288 "source": "project_settings",

911 }1289 "file_path": "/Users/.../my-project/.claude/settings.json"

912 }

913 }

914}1290}

915```1291```

916 1292 

917#### `PostToolUse` Decision Control1293#### ConfigChange decision control

918 1294 

919`PostToolUse` hooks can provide feedback to Claude after tool execution.1295ConfigChange 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.

920 1296 

921* `"block"` automatically prompts Claude with `reason`.1297| Field | Description |

922* `undefined` does nothing. `reason` is ignored.1298| :--------- | :--------------------------------------------------------------------------------------- |

923* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.1299| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |

1300| `reason` | Explanation shown to the user when `decision` is `"block"` |

924 1301 

925```json theme={null}1302```json theme={null}

926{1303{

927 "decision": "block" | undefined,1304 "decision": "block",

928 "reason": "Explanation for decision",1305 "reason": "Configuration changes to project settings require admin approval"

929 "hookSpecificOutput": {

930 "hookEventName": "PostToolUse",

931 "additionalContext": "Additional information for Claude"

932 }

933}1306}

934```1307```

935 1308 

936#### `UserPromptSubmit` Decision Control1309`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.

937 1310 

938`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1311### PreCompact

939 

940**Adding context (exit code 0):**

941There are two ways to add context to the conversation:

942 1312 

9431. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1313Runs before Claude Code is about to run a compact operation.

944 as context. This is the easiest way to inject information.

945 1314 

9462. **JSON with `additionalContext`** (structured): Use the JSON format below for1315The matcher value indicates whether compaction was triggered manually or automatically:

947 more control. The `additionalContext` field is added as context.

948 1316 

949Both methods work with exit code 0. Plain stdout is shown as hook output in1317| Matcher | When it fires |

950the transcript; `additionalContext` is added more discretely.1318| :------- | :------------------------------------------- |

1319| `manual` | `/compact` |

1320| `auto` | Auto-compact when the context window is full |

951 1321 

952**Blocking prompts:**1322#### PreCompact input

953 1323 

954* `"decision": "block"` prevents the prompt from being processed. The submitted1324In 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.

955 prompt is erased from context. `"reason"` is shown to the user but not added

956 to context.

957* `"decision": undefined` (or omitted) allows the prompt to proceed normally.

958 1325 

959```json theme={null}1326```json theme={null}

960{1327{

961 "decision": "block" | undefined,1328 "session_id": "abc123",

962 "reason": "Explanation for decision",1329 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

963 "hookSpecificOutput": {1330 "cwd": "/Users/...",

964 "hookEventName": "UserPromptSubmit",1331 "permission_mode": "default",

965 "additionalContext": "My additional context here"1332 "hook_event_name": "PreCompact",

966 }1333 "trigger": "manual",

1334 "custom_instructions": ""

967}1335}

968```1336```

969 1337 

970<Note>1338### SessionEnd

971 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

972 block prompts or want more structured control.

973</Note>

974 1339 

975#### `Stop`/`SubagentStop` Decision Control1340Runs when a Claude Code session ends. Useful for cleanup tasks, logging session

1341statistics, or saving session state. Supports matchers to filter by exit reason.

1342 

1343The `reason` field in the hook input indicates why the session ended:

976 1344 

977`Stop` and `SubagentStop` hooks can control whether Claude must continue.1345| Reason | Description |

1346| :---------------------------- | :----------------------------------------- |

1347| `clear` | Session cleared with `/clear` command |

1348| `logout` | User logged out |

1349| `prompt_input_exit` | User exited while prompt input was visible |

1350| `bypass_permissions_disabled` | Bypass permissions mode was disabled |

1351| `other` | Other exit reasons |

978 1352 

979* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1353#### SessionEnd input

980 to know how to proceed.1354 

981* `undefined` allows Claude to stop. `reason` is ignored.1355In 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.

982 1356 

983```json theme={null}1357```json theme={null}

984{1358{

985 "decision": "block" | undefined,1359 "session_id": "abc123",

986 "reason": "Must be provided when Claude is blocked from stopping"1360 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1361 "cwd": "/Users/...",

1362 "permission_mode": "default",

1363 "hook_event_name": "SessionEnd",

1364 "reason": "other"

987}1365}

988```1366```

989 1367 

990#### `Setup` Decision Control1368SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.

1369 

1370## Prompt-based hooks

1371 

1372In 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 work with the following events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `UserPromptSubmit`, `Stop`, `SubagentStop`, and `TaskCompleted`. `TeammateIdle` does not support prompt-based or agent-based hooks.

1373 

1374### How prompt-based hooks work

1375 

1376Instead of executing a Bash command, prompt-based hooks:

1377 

13781. Send the hook input and your prompt to a Claude model, Haiku by default

13792. The LLM responds with structured JSON containing a decision

13803. Claude Code processes the decision automatically

1381 

1382### Prompt hook configuration

991 1383 

992`Setup` hooks allow you to load context and configure the environment during repository initialization or maintenance.1384Set `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.

993 1385 

994* `"hookSpecificOutput.additionalContext"` adds the string to the context.1386This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:

995* Multiple hooks' `additionalContext` values are concatenated.

996* Setup hooks have access to `CLAUDE_ENV_FILE` for persisting environment variables.

997 1387 

998```json theme={null}1388```json theme={null}

999{1389{

1000 "hookSpecificOutput": {1390 "hooks": {

1001 "hookEventName": "Setup",1391 "Stop": [

1002 "additionalContext": "Repository initialized with custom configuration"1392 {

1393 "hooks": [

1394 {

1395 "type": "prompt",

1396 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."

1397 }

1398 ]

1399 }

1400 ]

1003 }1401 }

1004}1402}

1005```1403```

1006 1404 

1007#### `SessionStart` Decision Control1405| Field | Required | Description |

1406| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1407| `type` | yes | Must be `"prompt"` |

1408| `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 |

1409| `model` | no | Model to use for evaluation. Defaults to a fast model |

1410| `timeout` | no | Timeout in seconds. Default: 30 |

1008 1411 

1009`SessionStart` hooks allow you to load in context at the start of a session.1412### Response schema

1010 1413 

1011* `"hookSpecificOutput.additionalContext"` adds the string to the context.1414The LLM must respond with JSON containing:

1012* Multiple hooks' `additionalContext` values are concatenated.

1013 1415 

1014```json theme={null}1416```json theme={null}

1015{1417{

1016 "hookSpecificOutput": {1418 "ok": true | false,

1017 "hookEventName": "SessionStart",1419 "reason": "Explanation for the decision"

1018 "additionalContext": "My additional context here"

1019 }

1020}1420}

1021```1421```

1022 1422 

1023#### `SessionEnd` Decision Control1423| Field | Description |

1024 1424| :------- | :--------------------------------------------------------- |

1025`SessionEnd` hooks run when a session ends. They cannot block session termination1425| `ok` | `true` allows the action, `false` prevents it |

1026but can perform cleanup tasks.1426| `reason` | Required when `ok` is `false`. Explanation shown to Claude |

1027 

1028#### Exit Code Example: Bash Command Validation

1029 

1030```python theme={null}

1031#!/usr/bin/env python3

1032import json

1033import re

1034import sys

1035 

1036# Define validation rules as a list of (regex pattern, message) tuples

1037VALIDATION_RULES = [

1038 (

1039 r"\bgrep\b(?!.*\|)",

1040 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",

1041 ),

1042 (

1043 r"\bfind\s+\S+\s+-name\b",

1044 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",

1045 ),

1046]

1047 

1048 

1049def validate_command(command: str) -> list[str]:

1050 issues = []

1051 for pattern, message in VALIDATION_RULES:

1052 if re.search(pattern, command):

1053 issues.append(message)

1054 return issues

1055 

1056 

1057try:

1058 input_data = json.load(sys.stdin)

1059except json.JSONDecodeError as e:

1060 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

1061 sys.exit(1)

1062 

1063tool_name = input_data.get("tool_name", "")

1064tool_input = input_data.get("tool_input", {})

1065command = tool_input.get("command", "")

1066 

1067if tool_name != "Bash" or not command:

1068 sys.exit(1)

1069 

1070# Validate the command

1071issues = validate_command(command)

1072 

1073if issues:

1074 for message in issues:

1075 print(f"• {message}", file=sys.stderr)

1076 # Exit code 2 blocks tool call and shows stderr to Claude

1077 sys.exit(2)

1078```

1079 

1080#### JSON Output Example: UserPromptSubmit to Add Context and Validation

1081 1427 

1082<Note>1428### Example: Multi-criteria Stop hook

1083 For `UserPromptSubmit` hooks, you can inject context using either method:

1084 

1085 * **Plain text stdout** with exit code 0: Simplest approach, prints text

1086 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,

1087 or `additionalContext` for structured context injection

1088 1429 

1089 Remember: Exit code 2 only uses `stderr` for the error message. To block using1430This `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:

1090 JSON (with a custom reason), use `"decision": "block"` with exit code 0.

1091</Note>

1092 1431 

1093```python theme={null}1432```json theme={null}

1094#!/usr/bin/env python31433{

1095import json1434 "hooks": {

1096import sys1435 "Stop": [

1097import re1436 {

1098import datetime1437 "hooks": [

1099 1438 {

1100# Load input from stdin1439 "type": "prompt",

1101try:1440 "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.",

1102 input_data = json.load(sys.stdin)1441 "timeout": 30

1103except json.JSONDecodeError as e:

1104 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

1105 sys.exit(1)

1106 

1107prompt = input_data.get("prompt", "")

1108 

1109# Check for sensitive patterns

1110sensitive_patterns = [

1111 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),

1112]

1113 

1114for pattern, message in sensitive_patterns:

1115 if re.search(pattern, prompt):

1116 # Use JSON output to block with a specific reason

1117 output = {

1118 "decision": "block",

1119 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."

1120 }1442 }

1121 print(json.dumps(output))1443 ]

1122 sys.exit(0)1444 }

1123 1445 ]

1124# Add current time to context1446 }

1125context = f"Current time: {datetime.datetime.now()}"1447}

1126print(context)1448```

1127 1449 

1128"""1450## Agent-based hooks

1129The following is also equivalent:

1130print(json.dumps({

1131 "hookSpecificOutput": {

1132 "hookEventName": "UserPromptSubmit",

1133 "additionalContext": context,

1134 },

1135}))

1136"""

1137 1451 

1138# Allow the prompt to proceed with the additional context1452Agent-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.

1139sys.exit(0)

1140```

1141 1453 

1142#### JSON Output Example: PreToolUse with Approval1454### How agent hooks work

1143 

1144```python theme={null}

1145#!/usr/bin/env python3

1146import json

1147import sys

1148 

1149# Load input from stdin

1150try:

1151 input_data = json.load(sys.stdin)

1152except json.JSONDecodeError as e:

1153 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

1154 sys.exit(1)

1155 

1156tool_name = input_data.get("tool_name", "")

1157tool_input = input_data.get("tool_input", {})

1158 

1159# Example: Auto-approve file reads for documentation files

1160if tool_name == "Read":

1161 file_path = tool_input.get("file_path", "")

1162 if file_path.endswith((".md", ".mdx", ".txt", ".json")):

1163 # Use JSON output to auto-approve the tool call

1164 output = {

1165 "decision": "approve",

1166 "reason": "Documentation file auto-approved",

1167 "suppressOutput": True # Don't show in verbose mode

1168 }

1169 print(json.dumps(output))

1170 sys.exit(0)

1171 1455 

1172# For other cases, let the normal permission flow proceed1456When an agent hook fires:

1173sys.exit(0)

1174```

1175 1457 

1176## Working with MCP Tools14581. Claude Code spawns a subagent with your prompt and the hook's JSON input

14592. The subagent can use tools like Read, Grep, and Glob to investigate

14603. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision

14614. Claude Code processes the decision the same way as a prompt hook

1177 1462 

1178Claude Code hooks work seamlessly with1463Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.

1179[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers

1180provide tools, they appear with a special naming pattern that you can match in

1181your hooks.

1182 1464 

1183### MCP Tool Naming1465### Agent hook configuration

1184 1466 

1185MCP tools follow the pattern `mcp__<server>__<tool>`, for example:1467Set `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:

1186 1468 

1187* `mcp__memory__create_entities` - Memory server's create entities tool1469| Field | Required | Description |

1188* `mcp__filesystem__read_file` - Filesystem server's read file tool1470| :-------- | :------- | :------------------------------------------------------------------------------------------ |

1189* `mcp__github__search_repositories` - GitHub server's search tool1471| `type` | yes | Must be `"agent"` |

1472| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

1473| `model` | no | Model to use. Defaults to a fast model |

1474| `timeout` | no | Timeout in seconds. Default: 60 |

1190 1475 

1191### Configuring Hooks for MCP Tools1476The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.

1192 1477 

1193You can target specific MCP tools or entire MCP servers:1478This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:

1194 1479 

1195```json theme={null}1480```json theme={null}

1196{1481{

1197 "hooks": {1482 "hooks": {

1198 "PreToolUse": [1483 "Stop": [

1199 {1484 {

1200 "matcher": "mcp__memory__.*",

1201 "hooks": [1485 "hooks": [

1202 {1486 {

1203 "type": "command",1487 "type": "agent",

1204 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"1488 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

1489 "timeout": 120

1205 }1490 }

1206 ]1491 ]

1207 },1492 }

1493 ]

1494 }

1495}

1496```

1497 

1498## Run hooks in the background

1499 

1500By 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.

1501 

1502### Configure an async hook

1503 

1504Add `"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.

1505 

1506This 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:

1507 

1508```json theme={null}

1509{

1510 "hooks": {

1511 "PostToolUse": [

1208 {1512 {

1209 "matcher": "mcp__.*__write.*",1513 "matcher": "Write",

1210 "hooks": [1514 "hooks": [

1211 {1515 {

1212 "type": "command",1516 "type": "command",

1213 "command": "/home/user/scripts/validate-mcp-write.py"1517 "command": "/path/to/run-tests.sh",

1518 "async": true,

1519 "timeout": 120

1214 }1520 }

1215 ]1521 ]

1216 }1522 }


1219}1525}

1220```1526```

1221 1527 

1222## Examples1528The `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.

1223 

1224<Tip>

1225 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide.

1226</Tip>

1227 

1228## Security Considerations

1229 1529 

1230### Disclaimer1530### How async hooks execute

1231 1531 

1232**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on1532When 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.

1233your system automatically. By using hooks, you acknowledge that:

1234 1533 

1235* You are solely responsible for the commands you configure1534After 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.

1236* Hooks can modify, delete, or access any files your user account can access

1237* Malicious or poorly written hooks can cause data loss or system damage

1238* Anthropic provides no warranty and assumes no liability for any damages

1239 resulting from hook usage

1240* You should thoroughly test hooks in a safe environment before production use

1241 1535 

1242Always review and understand any hook commands before adding them to your1536### Example: run tests after file changes

1243configuration.

1244 1537 

1245### Security Best Practices1538This 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`:

1246 1539 

1247Here are some key practices for writing more secure hooks:1540```bash theme={null}

1541#!/bin/bash

1542# run-tests-async.sh

1248 1543 

12491. **Validate and sanitize inputs** - Never trust input data blindly1544# Read hook input from stdin

12502. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1545INPUT=$(cat)

12513. **Block path traversal** - Check for `..` in file paths1546FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

12524. **Use absolute paths** - Specify full paths for scripts (use

1253 "\$CLAUDE\_PROJECT\_DIR" for the project path)

12545. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.

1255 1547 

1256### Configuration Safety1548# Only run tests for source files

1549if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then

1550 exit 0

1551fi

1257 1552 

1258Direct edits to hooks in settings files don't take effect immediately. Claude1553# Run tests and report results via systemMessage

1259Code:1554RESULT=$(npm test 2>&1)

1555EXIT_CODE=$?

1260 1556 

12611. Captures a snapshot of hooks at startup1557if [ $EXIT_CODE -eq 0 ]; then

12622. Uses this snapshot throughout the session1558 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"

12633. Warns if hooks are modified externally1559else

12644. Requires review in `/hooks` menu for changes to apply1560 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"

1561fi

1562```

1265 1563 

1266This prevents malicious hook modifications from affecting your current session.1564Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:

1267 1565 

1268## Hook Execution Details1566```json theme={null}

1567{

1568 "hooks": {

1569 "PostToolUse": [

1570 {

1571 "matcher": "Write|Edit",

1572 "hooks": [

1573 {

1574 "type": "command",

1575 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",

1576 "async": true,

1577 "timeout": 300

1578 }

1579 ]

1580 }

1581 ]

1582 }

1583}

1584```

1269 1585 

1270* **Timeout**: 60-second execution limit by default, configurable per command.1586### Limitations

1271 * A timeout for an individual command does not affect the other commands.

1272* **Parallelization**: All matching hooks run in parallel

1273* **Deduplication**: Multiple identical hook commands are deduplicated automatically

1274* **Environment**: Runs in current directory with Claude Code's environment

1275 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the

1276 absolute path to the project root directory (where Claude Code was started)

1277 * 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.

1278* **Input**: JSON via stdin

1279* **Output**:

1280 * PreToolUse/PermissionRequest/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)

1281 * Notification/SessionEnd: Logged to debug only (`--debug`)

1282 * UserPromptSubmit/SessionStart/Setup: stdout added as context for Claude

1283 1587 

1284## Debugging1588Async hooks have several constraints compared to synchronous hooks:

1285 1589 

1286### Basic Troubleshooting1590* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.

1591* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.

1592* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.

1593* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.

1287 1594 

1288If your hooks aren't working:1595## Security considerations

1289 1596 

12901. **Check configuration** - Run `/hooks` to see if your hook is registered1597### Disclaimer

12912. **Verify syntax** - Ensure your JSON settings are valid

12923. **Test commands** - Run hook commands manually first

12934. **Check permissions** - Make sure scripts are executable

12945. **Review logs** - Use `claude --debug` to see hook execution details

1295 1598 

1296Common issues:1599Hooks run with your system user's full permissions.

1297 1600 

1298* **Quotes not escaped** - Use `\"` inside JSON strings1601<Warning>

1299* **Wrong matcher** - Check tool names match exactly (case-sensitive)1602 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.

1300* **Command not found** - Use full paths for scripts1603</Warning>

1301 1604 

1302### Advanced Debugging1605### Security best practices

1303 1606 

1304For complex hook issues:1607Keep these practices in mind when writing hooks:

1305 1608 

13061. **Inspect hook execution** - Use `claude --debug` to see detailed hook1609* **Validate and sanitize inputs**: never trust input data blindly

1307 execution1610* **Always quote shell variables**: use `"$VAR"` not `$VAR`

13082. **Validate JSON schemas** - Test hook input/output with external tools1611* **Block path traversal**: check for `..` in file paths

13093. **Check environment variables** - Verify Claude Code's environment is correct1612* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root

13104. **Test edge cases** - Try hooks with unusual file paths or inputs1613* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.

13115. **Monitor system resources** - Check for resource exhaustion during hook

1312 execution

13136. **Use structured logging** - Implement logging in your hook scripts

1314 1614 

1315### Debug Output Example1615## Debug hooks

1316 1616 

1317Use `claude --debug` to see hook execution details:1617Run `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.

1318 1618 

1319```1619```

1320[DEBUG] Executing hooks for PostToolUse:Write1620[DEBUG] Executing hooks for PostToolUse:Write


1322[DEBUG] Found 1 hook matchers in settings1622[DEBUG] Found 1 hook matchers in settings

1323[DEBUG] Matched 1 hooks for query "Write"1623[DEBUG] Matched 1 hooks for query "Write"

1324[DEBUG] Found 1 hook commands to execute1624[DEBUG] Found 1 hook commands to execute

1325[DEBUG] Executing hook command: <Your command> with timeout 60000ms1625[DEBUG] Executing hook command: <Your command> with timeout 600000ms

1326[DEBUG] Hook command completed with status 0: <Your stdout>1626[DEBUG] Hook command completed with status 0: <Your stdout>

1327```1627```

1328 1628 

1329Progress messages appear in verbose mode (ctrl+o) showing:1629For 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.

1330 

1331* Which hook is running

1332* Command being executed

1333* Success/failure status

1334* Output or error messages

1335 

1336 

1337 

1338> 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 +529 −206

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

20 

21The fastest way to create a hook is through the `/hooks` interactive menu in Claude Code. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.

15 22 

16* **Notifications**: Customize how you get notified when Claude Code is awaiting23<Steps>

17 your input or permission to run something.24 <Step title="Open the hooks menu">

18* **Automatic formatting**: Run `prettier` on .ts files, `gofmt` on .go files,25 Type `/hooks` in the Claude Code CLI. You'll see a list of all available hook events, plus an option to disable all hooks. Each event corresponds to a point in Claude's lifecycle where you can run custom code. Select `Notification` to create a hook that fires when Claude needs your attention.

19 etc. after every file edit.26 </Step>

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 27 

27By encoding these rules as hooks rather than prompting instructions, you turn28 <Step title="Configure the matcher">

28suggestions into app-level code that executes every time it is expected to run.29 The menu shows a list of matchers, which filter when the hook fires. Set the matcher to `*` to fire on all notification types. You can narrow it later by changing the matcher to a specific value like `permission_prompt` or `idle_prompt`.

30 </Step>

29 31 

30<Warning>32 <Step title="Add your command">

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.33 Select `+ Add new hook…`. The menu prompts you for a shell command to run when the event fires. Hooks run any shell command you provide, so you can use your platform's built-in notification tool. Copy the command for your OS:

32 For example, malicious hooks code can exfiltrate your data. Always review your hooks implementation before registering them.

33 34 

34 For full security best practices, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.35 <Tabs>

35</Warning>36 <Tab title="macOS">

37 Uses [`osascript`](https://ss64.com/mac/osascript.html) to trigger a native macOS notification through AppleScript:

36 38 

37## Hook Events Overview39 ```

40 osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'

41 ```

42 </Tab>

38 43 

39Claude Code provides several hook events that run at different points in the44 <Tab title="Linux">

40workflow:45 Uses `notify-send`, which is pre-installed on most Linux desktops with a notification daemon:

41 46 

42* **PreToolUse**: Runs before tool calls (can block them)47 ```

43* **PermissionRequest**: Runs when a permission dialog is shown (can allow or deny)48 notify-send 'Claude Code' 'Claude Code needs your attention'

44* **PostToolUse**: Runs after tool calls complete49 ```

45* **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it50 </Tab>

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 51 

54Each event receives different data and can control Claude's behavior in52 <Tab title="Windows (PowerShell)">

55different ways.53 Uses PowerShell to show a native message box through .NET's Windows Forms:

56 54 

57## Quickstart55 ```

56 powershell.exe -Command "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')"

57 ```

58 </Tab>

59 </Tabs>

60 </Step>

58 61 

59In this quickstart, you'll add a hook that logs the shell commands that Claude62 <Step title="Choose a storage location">

60Code runs.63 The menu asks where to save the hook configuration. Select `User settings` to store it in `~/.claude/settings.json`, which applies the hook to all your projects. You could also choose `Project settings` to scope it to the current project. See [Configure hook location](#configure-hook-location) for all available scopes.

64 </Step>

61 65 

62### Prerequisites66 <Step title="Test the hook">

67 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.

68 </Step>

69</Steps>

63 70 

64Install `jq` for JSON processing in the command line.71## What you can automate

65 72 

66### Step 1: Open hooks configuration73Hooks 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).

67 74 

68Run the `/hooks` command and select75Each example includes a ready-to-use configuration block that you add to a [settings file](#configure-hook-location). The most common patterns:

69the `PreToolUse` hook event.

70 76 

71`PreToolUse` hooks run before tool calls and can block them while providing77* [Get notified when Claude needs input](#get-notified-when-claude-needs-input)

72Claude feedback on what to do differently.78* [Auto-format code after edits](#auto-format-code-after-edits)

79* [Block edits to protected files](#block-edits-to-protected-files)

80* [Re-inject context after compaction](#re-inject-context-after-compaction)

81* [Audit configuration changes](#audit-configuration-changes)

73 82 

74### Step 2: Add a matcher83### Get notified when Claude needs input

84 

85Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal.

86 

87This 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`, or use the [interactive walkthrough](#set-up-your-first-hook) above to configure it with `/hooks`:

88 

89<Tabs>

90 <Tab title="macOS">

91 ```json theme={null}

92 {

93 "hooks": {

94 "Notification": [

95 {

96 "matcher": "",

97 "hooks": [

98 {

99 "type": "command",

100 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

101 }

102 ]

103 }

104 ]

105 }

106 }

107 ```

108 </Tab>

75 109 

76Select `+ Add new matcher…` to run your hook only on Bash tool calls.110 <Tab title="Linux">

111 ```json theme={null}

112 {

113 "hooks": {

114 "Notification": [

115 {

116 "matcher": "",

117 "hooks": [

118 {

119 "type": "command",

120 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

121 }

122 ]

123 }

124 ]

125 }

126 }

127 ```

128 </Tab>

77 129 

78Type `Bash` for the matcher.130 <Tab title="Windows (PowerShell)">

131 ```json theme={null}

132 {

133 "hooks": {

134 "Notification": [

135 {

136 "matcher": "",

137 "hooks": [

138 {

139 "type": "command",

140 "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""

141 }

142 ]

143 }

144 ]

145 }

146 }

147 ```

148 </Tab>

149</Tabs>

79 150 

80<Note>You can use `*` to match all tools.</Note>151### Auto-format code after edits

81 152 

82### Step 3: Add the hook153Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

83 154 

84Select `+ Add new hook…` and enter this command:155This 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:

85 156 

86```bash theme={null}157```json theme={null}

87jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt158{

159 "hooks": {

160 "PostToolUse": [

161 {

162 "matcher": "Edit|Write",

163 "hooks": [

164 {

165 "type": "command",

166 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"

167 }

168 ]

169 }

170 ]

171 }

172}

88```173```

89 174 

90### Step 4: Save your configuration175<Note>

176 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/).

177</Note>

178 

179### Block edits to protected files

180 

181Prevent 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.

182 

183This 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.

184 

185<Steps>

186 <Step title="Create the hook script">

187 Save this to `.claude/hooks/protect-files.sh`:

188 

189 ```bash theme={null}

190 #!/bin/bash

191 # protect-files.sh

192 

193 INPUT=$(cat)

194 FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

195 

196 PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

197 

198 for pattern in "${PROTECTED_PATTERNS[@]}"; do

199 if [[ "$FILE_PATH" == *"$pattern"* ]]; then

200 echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2

201 exit 2

202 fi

203 done

91 204 

92For storage location, select `User settings` since you're logging to your home205 exit 0

93directory. This hook will then apply to all projects, not just your current206 ```

94project.207 </Step>

95 208 

96Then press `Esc` until you return to the REPL. Your hook is now registered.209 <Step title="Make the script executable (macOS/Linux)">

210 Hook scripts must be executable for Claude Code to run them:

97 211 

98### Step 5: Verify your hook212 ```bash theme={null}

213 chmod +x .claude/hooks/protect-files.sh

214 ```

215 </Step>

99 216 

100Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:217 <Step title="Register the hook">

218 Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call:

219 

220 ```json theme={null}

221 {

222 "hooks": {

223 "PreToolUse": [

224 {

225 "matcher": "Edit|Write",

226 "hooks": [

227 {

228 "type": "command",

229 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"

230 }

231 ]

232 }

233 ]

234 }

235 }

236 ```

237 </Step>

238</Steps>

239 

240### Re-inject context after compaction

241 

242When 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.

243 

244Any 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:

101 245 

102```json theme={null}246```json theme={null}

103{247{

104 "hooks": {248 "hooks": {

105 "PreToolUse": [249 "SessionStart": [

106 {250 {

107 "matcher": "Bash",251 "matcher": "compact",

108 "hooks": [252 "hooks": [

109 {253 {

110 "type": "command",254 "type": "command",

111 "command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"255 "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"

112 }256 }

113 ]257 ]

114 }258 }


117}261}

118```262```

119 263 

120### Step 6: Test your hook264You 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.

121 265 

122Ask Claude to run a simple command like `ls` and check your log file:266### Audit configuration changes

123 267 

124```bash theme={null}268Track 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.

125cat ~/.claude/bash-command-log.txt269 

270This example appends each change to an audit log. Add this to `~/.claude/settings.json`:

271 

272```json theme={null}

273{

274 "hooks": {

275 "ConfigChange": [

276 {

277 "matcher": "",

278 "hooks": [

279 {

280 "type": "command",

281 "command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"

282 }

283 ]

284 }

285 ]

286 }

287}

126```288```

127 289 

128You should see entries like:290The 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.

291 

292## How hooks work

293 

294Hook 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:

295 

296| Event | When it fires |

297| :------------------- | :----------------------------------------------------------------- |

298| `SessionStart` | When a session begins or resumes |

299| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

300| `PreToolUse` | Before a tool call executes. Can block it |

301| `PermissionRequest` | When a permission dialog appears |

302| `PostToolUse` | After a tool call succeeds |

303| `PostToolUseFailure` | After a tool call fails |

304| `Notification` | When Claude Code sends a notification |

305| `SubagentStart` | When a subagent is spawned |

306| `SubagentStop` | When a subagent finishes |

307| `Stop` | When Claude finishes responding |

308| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

309| `TaskCompleted` | When a task is being marked as completed |

310| `ConfigChange` | When a configuration file changes during a session |

311| `PreCompact` | Before context compaction |

312| `SessionEnd` | When a session terminates |

313 

314Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Two other options use a Claude model to make decisions: `"type": "prompt"` for single-turn evaluation and `"type": "agent"` for multi-turn verification with tool access. See [Prompt-based hooks](#prompt-based-hooks) and [Agent-based hooks](#agent-based-hooks) for details.

315 

316### Read input and return output

317 

318Hooks 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.

319 

320#### Hook input

129 321 

322Every 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:

323 

324```json theme={null}

325{

326 "session_id": "abc123", // unique ID for this session

327 "cwd": "/Users/sarah/myproject", // working directory when the event fired

328 "hook_event_name": "PreToolUse", // which event triggered this hook

329 "tool_name": "Bash", // the tool Claude is about to use

330 "tool_input": { // the arguments Claude passed to the tool

331 "command": "npm test" // for Bash, this is the shell command

332 }

333}

130```334```

131ls - Lists files and directories335 

336Your 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, 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.

337 

338#### Hook output

339 

340Your 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:

341 

342```bash theme={null}

343#!/bin/bash

344INPUT=$(cat)

345COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')

346 

347if echo "$COMMAND" | grep -q "drop table"; then

348 echo "Blocked: dropping tables is not allowed" >&2 # stderr becomes Claude's feedback

349 exit 2 # exit 2 = block the action

350fi

351 

352exit 0 # exit 0 = let it proceed

132```353```

133 354 

134## More Examples355The exit code determines what happens next:

356 

357* **Exit 0**: the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude's context.

358* **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.

359* **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.

360 

361#### Structured JSON output

362 

363Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead.

135 364 

136<Note>365<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.366 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>367</Note>

139 368 

140### Code Formatting Hook369For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:

141 370 

142Automatically format TypeScript files after editing:371```json theme={null}

372{

373 "hookSpecificOutput": {

374 "hookEventName": "PreToolUse",

375 "permissionDecision": "deny",

376 "permissionDecisionReason": "Use rg instead of grep for better performance"

377 }

378}

379```

380 

381Claude Code reads `permissionDecision` and cancels the tool call, then feeds `permissionDecisionReason` back to Claude as feedback. These three options are specific to `PreToolUse`:

382 

383* `"allow"`: proceed without showing a permission prompt

384* `"deny"`: cancel the tool call and send the reason to Claude

385* `"ask"`: show the permission prompt to the user as normal

386 

387Other 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.

388 

389For `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).

390 

391### Filter hooks with matchers

392 

393Without 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 394 

144```json theme={null}395```json theme={null}

145{396{


148 {399 {

149 "matcher": "Edit|Write",400 "matcher": "Edit|Write",

150 "hooks": [401 "hooks": [

151 {402 { "type": "command", "command": "prettier --write ..." }

152 "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; }"

154 }

155 ]403 ]

156 }404 }

157 ]405 ]


159}407}

160```408```

161 409 

162### Markdown Formatting Hook410The `"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.

163 411 

164Automatically fix missing language tags and formatting issues in markdown files:412Each event type matches on a specific field. Matchers support exact strings and regex patterns:

165 413 

166```json theme={null}414| Event | What the matcher filters | Example matcher values |

167{415| :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- |

416| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

417| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

418| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

419| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

420| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

421| `PreCompact` | what triggered compaction | `manual`, `auto` |

422| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted` | no matcher support | always fires on every occurrence |

423| `SubagentStop` | agent type | same values as `SubagentStart` |

424 

425A few more examples showing matchers on different event types:

426 

427<Tabs>

428 <Tab title="Log every Bash command">

429 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:

430 

431 ```json theme={null}

432 {

168 "hooks": {433 "hooks": {

169 "PostToolUse": [434 "PostToolUse": [

170 {435 {

171 "matcher": "Edit|Write",436 "matcher": "Bash",

172 "hooks": [437 "hooks": [

173 {438 {

174 "type": "command",439 "type": "command",

175 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"440 "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"

176 }441 }

177 ]442 ]

178 }443 }

179 ]444 ]

180 }445 }

181}446 }

182```447 ```

448 </Tab>

183 449 

184Create `.claude/hooks/markdown_formatter.py` with this content:450 <Tab title="Match MCP tools">

185 451 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.

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 452 

274```bash theme={null}453 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`):

275chmod +x .claude/hooks/markdown_formatter.py454 

276```455 ```json theme={null}

456 {

457 "hooks": {

458 "PreToolUse": [

459 {

460 "matcher": "mcp__github__.*",

461 "hooks": [

462 {

463 "type": "command",

464 "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2"

465 }

466 ]

467 }

468 ]

469 }

470 }

471 ```

472 </Tab>

473 

474 <Tab title="Clean up on session end">

475 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:

476 

477 ```json theme={null}

478 {

479 "hooks": {

480 "SessionEnd": [

481 {

482 "matcher": "clear",

483 "hooks": [

484 {

485 "type": "command",

486 "command": "rm -f /tmp/claude-scratch-*.txt"

487 }

488 ]

489 }

490 ]

491 }

492 }

493 ```

494 </Tab>

495</Tabs>

496 

497For full matcher syntax, see the [Hooks reference](/en/hooks#configuration).

498 

499### Configure hook location

500 

501Where you add a hook determines its scope:

502 

503| Location | Scope | Shareable |

504| :--------------------------------------------------------- | :--------------------------------- | :--------------------------------- |

505| `~/.claude/settings.json` | All your projects | No, local to your machine |

506| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

507| `.claude/settings.local.json` | Single project | No, gitignored |

508| Managed policy settings | Organization-wide | Yes, admin-controlled |

509| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

510| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file |

277 511 

278This hook automatically:512You can also use the [`/hooks` menu](/en/hooks#the-hooks-menu) in Claude Code to add, delete, and view hooks interactively. To disable all hooks at once, use the toggle at the bottom of the `/hooks` menu or set `"disableAllHooks": true` in your settings file.

279 513 

280* Detects programming languages in unlabeled code blocks514Hooks added through the `/hooks` menu take effect immediately. If you edit settings files directly while Claude Code is running, the changes won't take effect until you review them in the `/hooks` menu or restart your session.

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 515 

285### Custom Notification Hook516## Prompt-based hooks

286 517 

287Get desktop notifications when Claude needs input:518For 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.

519 

520The model's only job is to return a yes/no decision as JSON:

521 

522* `"ok": true`: the action proceeds

523* `"ok": false`: the action is blocked. The model's `"reason"` is fed back to Claude so it can adjust.

524 

525This 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:

288 526 

289```json theme={null}527```json theme={null}

290{528{

291 "hooks": {529 "hooks": {

292 "Notification": [530 "Stop": [

293 {531 {

294 "matcher": "",

295 "hooks": [532 "hooks": [

296 {533 {

297 "type": "command",534 "type": "prompt",

298 "command": "notify-send 'Claude Code' 'Awaiting your input'"535 "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."

299 }536 }

300 ]537 ]

301 }538 }


304}541}

305```542```

306 543 

307### File Protection Hook544For full configuration options, see [Prompt-based hooks](/en/hooks#prompt-based-hooks) in the reference.

545 

546## Agent-based hooks

547 

548When 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.

308 549 

309Block edits to sensitive files:550Agent 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.

551 

552This example verifies that tests pass before allowing Claude to stop:

310 553 

311```json theme={null}554```json theme={null}

312{555{

313 "hooks": {556 "hooks": {

314 "PreToolUse": [557 "Stop": [

315 {558 {

316 "matcher": "Edit|Write",

317 "hooks": [559 "hooks": [

318 {560 {

319 "type": "command",561 "type": "agent",

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)\""562 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

563 "timeout": 120

321 }564 }

322 ]565 ]

323 }566 }


326}569}

327```570```

328 571 

329## Learn more572Use 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.

573 

574For full configuration options, see [Agent-based hooks](/en/hooks#agent-based-hooks) in the reference.

575 

576## Limitations and troubleshooting

330 577 

331* For reference documentation on hooks, see [Hooks reference](/en/hooks).578### Limitations

332* For comprehensive security best practices and safety guidelines, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.

333* For troubleshooting steps and debugging techniques, see [Debugging](/en/hooks#debugging) in the hooks reference

334 documentation.

335 579 

580* Hooks communicate through stdout, stderr, and exit codes only. They cannot trigger slash commands or tool calls directly.

581* Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).

582* `PostToolUse` hooks cannot undo actions since the tool has already executed.

583* `PermissionRequest` hooks do not fire in [non-interactive mode](/en/headless) (`-p`). Use `PreToolUse` hooks for automated permission decisions.

584* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts.

336 585 

586### Hook not firing

587 

588The hook is configured but never executes.

589 

590* Run `/hooks` and confirm the hook appears under the correct event

591* Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)

592* Verify you're triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)

593* If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead

594 

595### Hook error in output

596 

597You see a message like "PreToolUse hook error: ..." in the transcript.

598 

599* Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON:

600 ```bash theme={null}

601 echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh

602 echo $? # Check the exit code

603 ```

604* If you see "command not found", use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts

605* If you see "jq: command not found", install `jq` or use Python/Node.js for JSON parsing

606* If the script isn't running at all, make it executable: `chmod +x ./my-hook.sh`

607 

608### `/hooks` shows no hooks configured

609 

610You edited a settings file but the hooks don't appear in the menu.

611 

612* Restart your session or open `/hooks` to reload. Hooks added through the `/hooks` menu take effect immediately, but manual file edits require a reload.

613* Verify your JSON is valid (trailing commas and comments are not allowed)

614* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks

615 

616### Stop hook runs forever

617 

618Claude keeps working in an infinite loop instead of stopping.

619 

620Your 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`:

621 

622```bash theme={null}

623#!/bin/bash

624INPUT=$(cat)

625if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then

626 exit 0 # Allow Claude to stop

627fi

628# ... rest of your hook logic

629```

630 

631### JSON validation failed

632 

633Claude Code shows a JSON parsing error even though your hook script outputs valid JSON.

634 

635When 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:

636 

637```

638Shell ready on arm64

639{"decision": "block", "reason": "Not allowed"}

640```

641 

642Claude 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:

643 

644```bash theme={null}

645# In ~/.zshrc or ~/.bashrc

646if [[ $- == *i* ]]; then

647 echo "Shell ready"

648fi

649```

650 

651The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.

652 

653### Debug techniques

654 

655Toggle 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.

656 

657## Learn more

337 658 

338> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt659* [Hooks reference](/en/hooks): full event schemas, JSON output format, async hooks, and MCP tool hooks

660* [Security considerations](/en/hooks#security-considerations): review before deploying hooks in shared or production environments

661* [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/TBPmHzr19mDCuhZi/images/agentic-loop.svg?fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=9d9cdb2102f397a0f57450ca5ca2a969" 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/TBPmHzr19mDCuhZi/images/agentic-loop.svg?w=280&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=9c6a590754c1c1b281d40fc9f10fed0d 280w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/agentic-loop.svg?w=560&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=9fb2f2fc174e285797cad25a9ca2a326 560w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/agentic-loop.svg?w=840&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=3a1b68dd7b861e8ff25391773d8ab60c 840w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/agentic-loop.svg?w=1100&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=e64edf9f5cbc62464617945cf08ef134 1100w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/agentic-loop.svg?w=1650&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=3bf3319e76669f11513c6bcc5bf86feb 1650w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/agentic-loop.svg?w=2500&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=9413880a191409ff3c81bafc8f7ab977 2500w" />

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 


33The built-in tools generally fall into four categories, each representing a different kind of agency.37The built-in tools generally fall into four categories, each representing a different kind of agency.

34 38 

35| Category | What Claude can do |39| Category | What Claude can do |

36| ------------------- | ------------------------------------------------------------------- |40| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |

37| **File operations** | Read files, edit code, create new files, rename and reorganize |41| **File operations** | Read files, edit code, create new files, rename and reorganize |

38| **Search** | Find files by pattern, search content with regex, explore codebases |42| **Search** | Find files by pattern, search content with regex, explore codebases |

39| **Execution** | Run shell commands, start servers, run tests, use git |43| **Execution** | Run shell commands, start servers, run tests, use git |

40| **Web** | Search the web, fetch documentation, look up error messages |44| **Web** | Search the web, fetch documentation, look up error messages |

45| **Code intelligence** | See type errors and warnings after edits, jump to definitions, find references (requires [code intelligence plugins](/en/discover-plugins#code-intelligence)) |

41 46 

42These 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/settings#tools-available-to-claude) for the complete list.

43 48 


72 77 

73Claude 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.78Claude 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.

74 79 

75**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).80**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).

76 81 

77### Work across branches82### Work across branches

78 83 


86 91 

87When 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.92When 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.

88 93 

89<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" />94<img src="https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/session-continuity.svg?fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=808da1b213c731bf98874c75981d688b" 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/TBPmHzr19mDCuhZi/images/session-continuity.svg?w=280&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=ba75f64bc571f3ef84a3237ef795bf22 280w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/session-continuity.svg?w=560&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=343ad422a171a2b909c87ed01c768745 560w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/session-continuity.svg?w=840&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=afce54d5e3b08cdb54d506332462b74c 840w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/session-continuity.svg?w=1100&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=28648c0a04cf7aef2de02d1c98491965 1100w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/session-continuity.svg?w=1650&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=a5287882beedaea54af606f682e4818d 1650w, https://mintcdn.com/claude-code/TBPmHzr19mDCuhZi/images/session-continuity.svg?w=2500&fit=max&auto=format&n=TBPmHzr19mDCuhZi&q=85&s=f392dbe67b63eead4a2aae67adfbfdbe 2500w" />

90 95 

91To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:96To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:

92 97 


138* **Auto-accept edits**: Claude edits files without asking, still asks for commands143* **Auto-accept edits**: Claude edits files without asking, still asks for commands

139* **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution144* **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution

140 145 

141You 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.146You 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.

142 147 

143***148***

144 149 


232 Step-by-step guides for typical tasks237 Step-by-step guides for typical tasks

233 </Card>238 </Card>

234</CardGroup>239</CardGroup>

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

iam.md +0 −234 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**WebFetch**

176 

177* `WebFetch(domain:example.com)` Matches fetch requests to example.com

178 

179**MCP**

180 

181* `mcp__puppeteer` Matches any tool provided by the `puppeteer` server (name configured in Claude Code)

182* `mcp__puppeteer__*` Wildcard syntax that also matches all tools from the `puppeteer` server

183* `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server

184 

185**Task (Subagents)**

186 

187Use `Task(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use:

188 

189* `Task(Explore)` Matches the Explore subagent

190* `Task(Plan)` Matches the Plan subagent

191* `Task(Verify)` Matches the Verify subagent

192 

193Add 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:

194 

195```json theme={null}

196{

197 "permissions": {

198 "deny": ["Task(Explore)"]

199 }

200}

201```

202 

203### Additional permission control with hooks

204 

205[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.

206 

207### Managed settings

208 

209For 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.

210 

211### Settings precedence

212 

213When multiple settings sources exist, they are applied in the following order (highest to lowest precedence):

214 

2151. Managed settings (`managed-settings.json`)

2162. Command line arguments

2173. Local project settings (`.claude/settings.local.json`)

2184. Shared project settings (`.claude/settings.json`)

2195. User settings (`~/.claude/settings.json`)

220 

221This hierarchy ensures that organizational policies are always enforced while still allowing flexibility at the project and user levels where appropriate.

222 

223## Credential management

224 

225Claude Code securely manages your authentication credentials:

226 

227* **Storage location**: On macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain.

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

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

230* **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.

231 

232 

233 

234> 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.


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 


85To create your own commands you can invoke with `/`, see [skills](/en/skills).91To create your own commands you can invoke with `/`, see [skills](/en/skills).

86 92 

87| Command | Purpose |93| Command | Purpose |

88| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------- |94| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

89| `/clear` | Clear conversation history |95| `/clear` | Clear conversation history |

90| `/compact [instructions]` | Compact conversation with optional focus instructions |96| `/compact [instructions]` | Compact conversation with optional focus instructions |

91| `/config` | Open the Settings interface (Config tab) |97| `/config` | Open the Settings interface (Config tab) |

92| `/context` | Visualize current context usage as a colored grid |98| `/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. |99| `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details. |

100| `/debug [description]` | Troubleshoot the current session by reading the session debug log. Optionally describe the issue |

94| `/doctor` | Checks the health of your Claude Code installation |101| `/doctor` | Checks the health of your Claude Code installation |

95| `/exit` | Exit the REPL |102| `/exit` | Exit the REPL |

96| `/export [filename]` | Export the current conversation to a file or clipboard |103| `/export [filename]` | Export the current conversation to a file or clipboard |


98| `/init` | Initialize project with `CLAUDE.md` guide |105| `/init` | Initialize project with `CLAUDE.md` guide |

99| `/mcp` | Manage MCP server connections and OAuth authentication |106| `/mcp` | Manage MCP server connections and OAuth authentication |

100| `/memory` | Edit `CLAUDE.md` memory files |107| `/memory` | Edit `CLAUDE.md` memory files |

101| `/model` | Select or change the AI model |108| `/model` | Select or change the AI model. With Opus 4.6, 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 |

102| `/permissions` | View or update [permissions](/en/iam#configuring-permissions) |109| `/permissions` | View or update [permissions](/en/permissions#manage-permissions) |

103| `/plan` | Enter plan mode directly from the prompt |110| `/plan` | Enter plan mode directly from the prompt |

104| `/rename <name>` | Rename the current session for easier identification |111| `/rename <name>` | Rename the current session for easier identification |

105| `/resume [session]` | Resume a conversation by ID or name, or open the session picker |112| `/resume [session]` | Resume a conversation by ID or name, or open the session picker |

106| `/rewind` | Rewind the conversation and/or code |113| `/rewind` | Rewind the conversation and/or code, or summarize from a selected message |

107| `/stats` | Visualize daily usage, session history, streaks, and model preferences |114| `/stats` | Visualize daily usage, session history, streaks, and model preferences |

108| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |115| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |

109| `/statusline` | Set up Claude Code's status line UI |116| `/statusline` | Set up Claude Code's status line UI |

117| `/copy` | Copy the last assistant response to clipboard |

110| `/tasks` | List and manage background tasks |118| `/tasks` | List and manage background tasks |

111| `/teleport` | Resume a remote session from claude.ai (subscribers only) |119| `/teleport` | Resume a remote session from claude.ai (subscribers only) |

120| `/desktop` | Hand off the current CLI session to the Claude Code Desktop app (macOS and Windows only) |

112| `/theme` | Change the color theme |121| `/theme` | Change the color theme |

113| `/todos` | List current TODO items |122| `/todos` | List current TODO items |

114| `/usage` | For subscription plans only: show plan usage limits and rate limit status |123| `/usage` | For subscription plans only: show plan usage limits and rate limit status |


153| `;` | Repeat last f/F/t/T motion |162| `;` | Repeat last f/F/t/T motion |

154| `,` | Repeat last f/F/t/T motion in reverse |163| `,` | Repeat last f/F/t/T motion in reverse |

155 164 

165<Note>

166 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.

167</Note>

168 

156### Editing (NORMAL mode)169### Editing (NORMAL mode)

157 170 

158| Command | Action |171| Command | Action |


261 274 

262This is useful for quick shell operations while maintaining conversation context.275This is useful for quick shell operations while maintaining conversation context.

263 276 

277## Prompt suggestions

278 

279When 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.

280 

281After 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.

282 

283* Press **Tab** to accept the suggestion, or press **Enter** to accept and submit

284* Start typing to dismiss it

285 

286The 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.

287 

288Suggestions are automatically skipped after the first turn of a conversation, in non-interactive mode, and in plan mode.

289 

290To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:

291 

292```bash theme={null}

293export CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false

294```

295 

296## Task list

297 

298When 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.

299 

300* Press `Ctrl+T` to toggle the task list view. The display shows up to 10 tasks at a time

301* To see all tasks or clear them, ask Claude directly: "show me all tasks" or "clear all tasks"

302* Tasks persist across context compactions, helping Claude stay organized on larger projects

303* 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`

304* To revert to the previous TODO list, set `CLAUDE_CODE_ENABLE_TASKS=false`.

305 

306## PR review status

307 

308When 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:

309 

310* Green: approved

311* Yellow: pending review

312* Red: changes requested

313* Gray: draft

314* Purple: merged

315 

316`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.

317 

318<Note>

319 PR status requires the `gh` CLI to be installed and authenticated (`gh auth login`).

320</Note>

321 

264## See also322## See also

265 323 

266* [Skills](/en/skills) - Custom prompts and workflows324* [Skills](/en/skills) - Custom prompts and workflows


268* [CLI reference](/en/cli-reference) - Command-line flags and options326* [CLI reference](/en/cli-reference) - Command-line flags and options

269* [Settings](/en/settings) - Configuration options327* [Settings](/en/settings) - Configuration options

270* [Memory management](/en/memory) - Managing CLAUDE.md files328* [Memory management](/en/memory) - Managing CLAUDE.md files

271 

272 

273 

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

jetbrains.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# 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


146* Being aware of which files Claude Code has access to modify150* Being aware of which files Claude Code has access to modify

147 151 

148For additional help, see our [troubleshooting guide](/en/troubleshooting).152For 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 +381 −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 

9Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`.

10 

11## Configuration file

12 

13The keybindings configuration file is an object with a `bindings` array. Each block specifies a context and a map of keystrokes to actions.

14 

15<Note>Changes to the keybindings file are automatically detected and applied without restarting Claude Code.</Note>

16 

17| Field | Description |

18| :--------- | :------------------------------------------------- |

19| `$schema` | Optional JSON Schema URL for editor autocompletion |

20| `$docs` | Optional documentation URL |

21| `bindings` | Array of binding blocks by context |

22 

23This example binds `Ctrl+E` to open an external editor in the chat context, and unbinds `Ctrl+U`:

24 

25```json theme={null}

26{

27 "$schema": "https://www.schemastore.org/claude-code-keybindings.json",

28 "$docs": "https://code.claude.com/docs/en/keybindings",

29 "bindings": [

30 {

31 "context": "Chat",

32 "bindings": {

33 "ctrl+e": "chat:externalEditor",

34 "ctrl+u": null

35 }

36 }

37 ]

38}

39```

40 

41## Contexts

42 

43Each binding block specifies a **context** where the bindings apply:

44 

45| Context | Description |

46| :---------------- | :----------------------------------------------- |

47| `Global` | Applies everywhere in the app |

48| `Chat` | Main chat input area |

49| `Autocomplete` | Autocomplete menu is open |

50| `Settings` | Settings menu (escape-only dismiss) |

51| `Confirmation` | Permission and confirmation dialogs |

52| `Tabs` | Tab navigation components |

53| `Help` | Help menu is visible |

54| `Transcript` | Transcript viewer |

55| `HistorySearch` | History search mode (Ctrl+R) |

56| `Task` | Background task is running |

57| `ThemePicker` | Theme picker dialog |

58| `Attachments` | Image/attachment bar navigation |

59| `Footer` | Footer indicator navigation (tasks, teams, diff) |

60| `MessageSelector` | Rewind and summarize dialog message selection |

61| `DiffDialog` | Diff viewer navigation |

62| `ModelPicker` | Model picker effort level |

63| `Select` | Generic select/list components |

64| `Plugin` | Plugin dialog (browse, discover, manage) |

65 

66## Available actions

67 

68Actions 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.

69 

70### App actions

71 

72Actions available in the `Global` context:

73 

74| Action | Default | Description |

75| :--------------------- | :------ | :-------------------------- |

76| `app:interrupt` | Ctrl+C | Cancel current operation |

77| `app:exit` | Ctrl+D | Exit Claude Code |

78| `app:toggleTodos` | Ctrl+T | Toggle task list visibility |

79| `app:toggleTranscript` | Ctrl+O | Toggle verbose transcript |

80 

81### History actions

82 

83Actions for navigating command history:

84 

85| Action | Default | Description |

86| :----------------- | :------ | :-------------------- |

87| `history:search` | Ctrl+R | Open history search |

88| `history:previous` | Up | Previous history item |

89| `history:next` | Down | Next history item |

90 

91### Chat actions

92 

93Actions available in the `Chat` context:

94 

95| Action | Default | Description |

96| :-------------------- | :------------------------ | :----------------------- |

97| `chat:cancel` | Escape | Cancel current input |

98| `chat:cycleMode` | Shift+Tab\* | Cycle permission modes |

99| `chat:modelPicker` | Cmd+P / Meta+P | Open model picker |

100| `chat:thinkingToggle` | Cmd+T / Meta+T | Toggle extended thinking |

101| `chat:submit` | Enter | Submit message |

102| `chat:undo` | Ctrl+\_ | Undo last action |

103| `chat:externalEditor` | Ctrl+G | Open in external editor |

104| `chat:stash` | Ctrl+S | Stash current prompt |

105| `chat:imagePaste` | Ctrl+V (Alt+V on Windows) | Paste image |

106 

107\*On Windows without VT mode (Node \<24.2.0/\<22.17.0, Bun \<1.2.23), defaults to Meta+M.

108 

109### Autocomplete actions

110 

111Actions available in the `Autocomplete` context:

112 

113| Action | Default | Description |

114| :---------------------- | :------ | :------------------ |

115| `autocomplete:accept` | Tab | Accept suggestion |

116| `autocomplete:dismiss` | Escape | Dismiss menu |

117| `autocomplete:previous` | Up | Previous suggestion |

118| `autocomplete:next` | Down | Next suggestion |

119 

120### Confirmation actions

121 

122Actions available in the `Confirmation` context:

123 

124| Action | Default | Description |

125| :-------------------------- | :-------- | :---------------------------- |

126| `confirm:yes` | Y, Enter | Confirm action |

127| `confirm:no` | N, Escape | Decline action |

128| `confirm:previous` | Up | Previous option |

129| `confirm:next` | Down | Next option |

130| `confirm:nextField` | Tab | Next field |

131| `confirm:previousField` | (unbound) | Previous field |

132| `confirm:cycleMode` | Shift+Tab | Cycle permission modes |

133| `confirm:toggleExplanation` | Ctrl+E | Toggle permission explanation |

134 

135### Permission actions

136 

137Actions available in the `Confirmation` context for permission dialogs:

138 

139| Action | Default | Description |

140| :----------------------- | :------ | :--------------------------- |

141| `permission:toggleDebug` | Ctrl+D | Toggle permission debug info |

142 

143### Transcript actions

144 

145Actions available in the `Transcript` context:

146 

147| Action | Default | Description |

148| :------------------------- | :------------- | :---------------------- |

149| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |

150| `transcript:exit` | Ctrl+C, Escape | Exit transcript view |

151 

152### History search actions

153 

154Actions available in the `HistorySearch` context:

155 

156| Action | Default | Description |

157| :---------------------- | :---------- | :----------------------- |

158| `historySearch:next` | Ctrl+R | Next match |

159| `historySearch:accept` | Escape, Tab | Accept selection |

160| `historySearch:cancel` | Ctrl+C | Cancel search |

161| `historySearch:execute` | Enter | Execute selected command |

162 

163### Task actions

164 

165Actions available in the `Task` context:

166 

167| Action | Default | Description |

168| :---------------- | :------ | :---------------------- |

169| `task:background` | Ctrl+B | Background current task |

170 

171### Theme actions

172 

173Actions available in the `ThemePicker` context:

174 

175| Action | Default | Description |

176| :------------------------------- | :------ | :------------------------- |

177| `theme:toggleSyntaxHighlighting` | Ctrl+T | Toggle syntax highlighting |

178 

179### Help actions

180 

181Actions available in the `Help` context:

182 

183| Action | Default | Description |

184| :------------- | :------ | :-------------- |

185| `help:dismiss` | Escape | Close help menu |

186 

187### Tabs actions

188 

189Actions available in the `Tabs` context:

190 

191| Action | Default | Description |

192| :-------------- | :-------------- | :----------- |

193| `tabs:next` | Tab, Right | Next tab |

194| `tabs:previous` | Shift+Tab, Left | Previous tab |

195 

196### Attachments actions

197 

198Actions available in the `Attachments` context:

199 

200| Action | Default | Description |

201| :--------------------- | :---------------- | :------------------------- |

202| `attachments:next` | Right | Next attachment |

203| `attachments:previous` | Left | Previous attachment |

204| `attachments:remove` | Backspace, Delete | Remove selected attachment |

205| `attachments:exit` | Down, Escape | Exit attachment bar |

206 

207### Footer actions

208 

209Actions available in the `Footer` context:

210 

211| Action | Default | Description |

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

213| `footer:next` | Right | Next footer item |

214| `footer:previous` | Left | Previous footer item |

215| `footer:openSelected` | Enter | Open selected footer item |

216| `footer:clearSelection` | Escape | Clear footer selection |

217 

218### Message selector actions

219 

220Actions available in the `MessageSelector` context:

221 

222| Action | Default | Description |

223| :----------------------- | :---------------------------------------- | :---------------- |

224| `messageSelector:up` | Up, K | Move up in list |

225| `messageSelector:down` | Down, J | Move down in list |

226| `messageSelector:top` | Ctrl+Up, Shift+Up, Meta+Up, Shift+K | Jump to top |

227| `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | Jump to bottom |

228| `messageSelector:select` | Enter | Select message |

229 

230### Diff actions

231 

232Actions available in the `DiffDialog` context:

233 

234| Action | Default | Description |

235| :-------------------- | :----------------- | :--------------------- |

236| `diff:dismiss` | Escape | Close diff viewer |

237| `diff:previousSource` | Left | Previous diff source |

238| `diff:nextSource` | Right | Next diff source |

239| `diff:previousFile` | Up | Previous file in diff |

240| `diff:nextFile` | Down | Next file in diff |

241| `diff:viewDetails` | Enter | View diff details |

242| `diff:back` | (context-specific) | Go back in diff viewer |

243 

244### Model picker actions

245 

246Actions available in the `ModelPicker` context:

247 

248| Action | Default | Description |

249| :--------------------------- | :------ | :-------------------- |

250| `modelPicker:decreaseEffort` | Left | Decrease effort level |

251| `modelPicker:increaseEffort` | Right | Increase effort level |

252 

253### Select actions

254 

255Actions available in the `Select` context:

256 

257| Action | Default | Description |

258| :---------------- | :-------------- | :--------------- |

259| `select:next` | Down, J, Ctrl+N | Next option |

260| `select:previous` | Up, K, Ctrl+P | Previous option |

261| `select:accept` | Enter | Accept selection |

262| `select:cancel` | Escape | Cancel selection |

263 

264### Plugin actions

265 

266Actions available in the `Plugin` context:

267 

268| Action | Default | Description |

269| :--------------- | :------ | :----------------------- |

270| `plugin:toggle` | Space | Toggle plugin selection |

271| `plugin:install` | I | Install selected plugins |

272 

273### Settings actions

274 

275Actions available in the `Settings` context:

276 

277| Action | Default | Description |

278| :---------------- | :------ | :---------------------------------- |

279| `settings:search` | / | Enter search mode |

280| `settings:retry` | R | Retry loading usage data (on error) |

281 

282## Keystroke syntax

283 

284### Modifiers

285 

286Use modifier keys with the `+` separator:

287 

288* `ctrl` or `control` - Control key

289* `alt`, `opt`, or `option` - Alt/Option key

290* `shift` - Shift key

291* `meta`, `cmd`, or `command` - Meta/Command key

292 

293For example:

294 

295```

296ctrl+k Single key with modifier

297shift+tab Shift + Tab

298meta+p Command/Meta + P

299ctrl+shift+c Multiple modifiers

300```

301 

302### Uppercase letters

303 

304A 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.

305 

306Uppercase letters with modifiers (e.g., `ctrl+K`) are treated as stylistic and do **not** imply Shift — `ctrl+K` is the same as `ctrl+k`.

307 

308### Chords

309 

310Chords are sequences of keystrokes separated by spaces:

311 

312```

313ctrl+k ctrl+s Press Ctrl+K, release, then Ctrl+S

314```

315 

316### Special keys

317 

318* `escape` or `esc` - Escape key

319* `enter` or `return` - Enter key

320* `tab` - Tab key

321* `space` - Space bar

322* `up`, `down`, `left`, `right` - Arrow keys

323* `backspace`, `delete` - Delete keys

324 

325## Unbind default shortcuts

326 

327Set an action to `null` to unbind a default shortcut:

328 

329```json theme={null}

330{

331 "bindings": [

332 {

333 "context": "Chat",

334 "bindings": {

335 "ctrl+s": null

336 }

337 }

338 ]

339}

340```

341 

342## Reserved shortcuts

343 

344These shortcuts cannot be rebound:

345 

346| Shortcut | Reason |

347| :------- | :------------------------- |

348| Ctrl+C | Hardcoded interrupt/cancel |

349| Ctrl+D | Hardcoded exit |

350 

351## Terminal conflicts

352 

353Some shortcuts may conflict with terminal multiplexers:

354 

355| Shortcut | Conflict |

356| :------- | :-------------------------------- |

357| Ctrl+B | tmux prefix (press twice to send) |

358| Ctrl+A | GNU screen prefix |

359| Ctrl+Z | Unix process suspend (SIGTSTP) |

360 

361## Vim mode interaction

362 

363When vim mode is enabled (`/vim`), keybindings and vim mode operate independently:

364 

365* **Vim mode** handles input at the text input level (cursor movement, modes, motions)

366* **Keybindings** handle actions at the component level (toggle todos, submit, etc.)

367* The Escape key in vim mode switches INSERT to NORMAL mode; it does not trigger `chat:cancel`

368* Most Ctrl+key shortcuts pass through vim mode to the keybinding system

369* In vim NORMAL mode, `?` shows the help menu (vim behavior)

370 

371## Validation

372 

373Claude Code validates your keybindings and shows warnings for:

374 

375* Parse errors (invalid JSON or structure)

376* Invalid context names

377* Reserved shortcut conflicts

378* Terminal multiplexer conflicts

379* Duplicate bindings in the same context

380 

381Run `/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 +97 −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# 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.


216 220 

217Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project's path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn't be shared.221Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project's path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn't be shared.

218 222 

223<Note>

224 The term "local scope" for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](/en/settings#settings-files) for details on settings file locations.

225</Note>

226 

219```bash theme={null}227```bash theme={null}

220# Add a local-scoped server (default)228# Add a local-scoped server (default)

221claude mcp add --transport http stripe https://mcp.stripe.com229claude mcp add --transport http stripe https://mcp.stripe.com


405 * OAuth authentication works with HTTP servers413 * OAuth authentication works with HTTP servers

406</Tip>414</Tip>

407 415 

416### Use pre-configured OAuth credentials

417 

418Some 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.

419 

420<Steps>

421 <Step title="Register an OAuth app with the server">

422 Create an app through the server's developer portal and note your client ID and client secret.

423 

424 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.

425 </Step>

426 

427 <Step title="Add the server with your credentials">

428 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.

429 

430 <Tabs>

431 <Tab title="claude mcp add">

432 Use `--client-id` to pass your app's client ID. The `--client-secret` flag prompts for the secret with masked input:

433 

434 ```bash theme={null}

435 claude mcp add --transport http \

436 --client-id your-client-id --client-secret --callback-port 8080 \

437 my-server https://mcp.example.com/mcp

438 ```

439 </Tab>

440 

441 <Tab title="claude mcp add-json">

442 Include the `oauth` object in the JSON config and pass `--client-secret` as a separate flag:

443 

444 ```bash theme={null}

445 claude mcp add-json my-server \

446 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \

447 --client-secret

448 ```

449 </Tab>

450 

451 <Tab title="CI / env var">

452 Set the secret via environment variable to skip the interactive prompt:

453 

454 ```bash theme={null}

455 MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \

456 --client-id your-client-id --client-secret --callback-port 8080 \

457 my-server https://mcp.example.com/mcp

458 ```

459 </Tab>

460 </Tabs>

461 </Step>

462 

463 <Step title="Authenticate in Claude Code">

464 Run `/mcp` in Claude Code and follow the browser login flow.

465 </Step>

466</Steps>

467 

468<Tip>

469 Tips:

470 

471 * The client secret is stored securely in your system keychain (macOS) or a credentials file, not in your config

472 * If the server uses a public OAuth client with no secret, use only `--client-id` without `--client-secret`

473 * These flags only apply to HTTP and SSE transports. They have no effect on stdio servers

474 * Use `claude mcp get <name>` to verify that OAuth credentials are configured for a server

475</Tip>

476 

408## Add MCP servers from JSON configuration477## Add MCP servers from JSON configuration

409 478 

410If you have a JSON configuration for an MCP server, you can add it directly:479If you have a JSON configuration for an MCP server, you can add it directly:


420 489 

421 # Example: Adding a stdio server with JSON configuration490 # Example: Adding a stdio server with JSON configuration

422 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'491 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'

492 

493 # Example: Adding an HTTP server with pre-configured OAuth credentials

494 claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret

423 ```495 ```

424 </Step>496 </Step>

425 497 


471 * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)543 * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)

472</Tip>544</Tip>

473 545 

546## Use MCP servers from Claude.ai

547 

548If 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:

549 

550<Steps>

551 <Step title="Configure MCP servers in Claude.ai">

552 Add servers at [claude.ai/settings/connectors](https://claude.ai/settings/connectors). On Team and Enterprise plans, only admins can add servers.

553 </Step>

554 

555 <Step title="Authenticate the MCP server">

556 Complete any required authentication steps in Claude.ai.

557 </Step>

558 

559 <Step title="View and manage servers in Claude Code">

560 In Claude Code, use the command:

561 

562 ```

563 # Within Claude Code, see all MCP servers including Claude.ai ones

564 > /mcp

565 ```

566 

567 Claude.ai servers appear in the list with indicators showing they come from Claude.ai.

568 </Step>

569</Steps>

570 

474## Use Claude Code as an MCP server571## Use Claude Code as an MCP server

475 572 

476You can use Claude Code itself as an MCP server that other applications can connect to:573You can use Claude Code itself as an MCP server that other applications can connect to:


919<Note>1016<Note>

920 **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.1017 **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.

921</Note>1018</Note>

922 

923 

924 

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

memory.md +82 −8

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 Claude's memory5# Manage Claude's memory

2 6 

3> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.7> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.

4 8 

5Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow.9Claude Code has two kinds of memory that persist across sessions:

10 

11* **Auto memory**: Claude automatically saves useful context like project patterns, key commands, and your preferences. This persists across sessions.

12* **CLAUDE.md files**: Markdown files you write and maintain with instructions, rules, and preferences for Claude to follow.

13 

14Both are loaded into Claude's context at the start of every session, though auto memory loads only the first 200 lines of its main file.

6 15 

7## Determine memory type16## Determine memory type

8 17 

9Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose:18Claude Code offers several memory locations in a hierarchical structure, each serving a different purpose:

10 19 

11| Memory Type | Location | Purpose | Use Case Examples | Shared With |20| Memory Type | Location | Purpose | Use Case Examples | Shared With |

12| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |21| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |


15| **Project rules** | `./.claude/rules/*.md` | Modular, topic-specific project instructions | Language-specific guidelines, testing conventions, API standards | Team members via source control |24| **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) |25| **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) |26| **Project memory (local)** | `./CLAUDE.local.md` | Personal project-specific preferences | Your sandbox URLs, preferred test data | Just you (current project) |

27| **Auto memory** | `~/.claude/projects/<project>/memory/` | Claude's automatic notes and learnings | Project patterns, debugging insights, architecture notes | Just you (per project) |

18 28 

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.29CLAUDE.md files in the directory hierarchy above the working directory are loaded in full at launch. CLAUDE.md files in child directories load on demand when Claude reads files in those directories. Auto memory loads only the first 200 lines of `MEMORY.md`. More specific instructions take precedence over broader ones.

20 30 

21<Note>31<Note>

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.32 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>33</Note>

24 34 

35## Auto memory

36 

37Auto memory is a persistent directory where Claude records learnings, patterns, and insights as it works. Unlike CLAUDE.md files that contain instructions you write for Claude, auto memory contains notes Claude writes for itself based on what it discovers during sessions.

38 

39<Note>

40 Auto memory is being rolled out gradually. If you aren't seeing auto memory, you can opt in by setting `CLAUDE_CODE_DISABLE_AUTO_MEMORY=0` in your environment.

41</Note>

42 

43### What Claude remembers

44 

45As Claude works, it may save things like:

46 

47* Project patterns: build commands, test conventions, code style preferences

48* Debugging insights: solutions to tricky problems, common error causes

49* Architecture notes: key files, module relationships, important abstractions

50* Your preferences: communication style, workflow habits, tool choices

51 

52### Where auto memory is stored

53 

54Each project gets its own memory directory at `~/.claude/projects/<project>/memory/`. The `<project>` path is derived from the git repository root, so all subdirectories within the same repo share one auto memory directory. Git worktrees get separate memory directories. Outside a git repo, the working directory is used instead.

55 

56The directory contains a `MEMORY.md` entrypoint and optional topic files:

57 

58```text theme={null}

59~/.claude/projects/<project>/memory/

60├── MEMORY.md # Concise index, loaded into every session

61├── debugging.md # Detailed notes on debugging patterns

62├── api-conventions.md # API design decisions

63└── ... # Any other topic files Claude creates

64```

65 

66`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.

67 

68### How it works

69 

70* The first 200 lines of `MEMORY.md` are loaded into Claude's system prompt at the start of every session. Content beyond 200 lines is not loaded automatically, and Claude is instructed to keep it concise by moving detailed notes into separate topic files.

71* Topic 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.

72* Claude reads and writes memory files during your session, so you'll see memory updates happen as you work.

73 

74### Manage auto memory

75 

76Auto memory files are markdown files you can edit at any time. Use `/memory` to open the file selector, which includes your auto memory entrypoint alongside your CLAUDE.md files.

77 

78To ask Claude to save something specific, tell it directly: "remember that we use pnpm, not npm" or "save to memory that the API tests require a local Redis instance".

79 

80When neither variable is set, auto memory follows the gradual rollout. The variable name uses double-negative logic: `DISABLE=0` means "don't disable" and forces auto memory on.

81 

82```bash theme={null}

83export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 # Force off

84export CLAUDE_CODE_DISABLE_AUTO_MEMORY=0 # Force on

85```

86 

25## CLAUDE.md imports87## CLAUDE.md imports

26 88 

27CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files:89CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files:


33- git workflow @docs/git-instructions.md95- git workflow @docs/git-instructions.md

34```96```

35 97 

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.98Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. For private per-project preferences that shouldn't be checked into version control, prefer `CLAUDE.local.md`: it is automatically loaded and added to `.gitignore`.

99 

100If you work across multiple git worktrees, `CLAUDE.local.md` only exists in one. Use a home-directory import instead so all worktrees share the same personal instructions:

37 101 

38```102```

39# Individual Preferences103# Individual Preferences

40- @~/.claude/my-project-instructions.md104- @~/.claude/my-project-instructions.md

41```105```

42 106 

107<Warning>

108 The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the specific files. Approve to load them; decline to skip them. This is a one-time decision per project: once declined, the dialog does not resurface and the imports remain disabled.

109</Warning>

110 

43To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.111To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.

44 112 

45```113```


54 122 

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.123Claude 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.

56 124 

125### Load memory from additional directories

126 

127The `--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.

128 

129To also load memory files (CLAUDE.md, .claude/CLAUDE.md, and .claude/rules/\*.md) from additional directories, set the `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable:

130 

131```bash theme={null}

132CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config

133```

134 

57## Directly edit memories with `/memory`135## Directly edit memories with `/memory`

58 136 

59Use the `/memory` command during a session to open any memory file in your system editor for more extensive additions or organization.137Use the `/memory` command during a session to open any memory file in your system editor for more extensive additions or organization.


219* **Be specific**: "Use 2-space indentation" is better than "Format code properly".297* **Be specific**: "Use 2-space indentation" is better than "Format code properly".

220* **Use structure to organize**: Format each individual memory as a bullet point and group related memories under descriptive markdown headings.298* **Use structure to organize**: Format each individual memory as a bullet point and group related memories under descriptive markdown headings.

221* **Review periodically**: Update memories as your project evolves to ensure Claude is always using the most up to date information and context.299* **Review periodically**: Update memories as your project evolves to ensure Claude is always using the most up to date information and context.

222 

223 

224 

225> 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 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 +121 −22

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 |

28| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |32| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |

29 33 

34Aliases 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`.

35 

30### Setting your model36### Setting your model

31 37 

32You can configure your model in several ways, listed in order of priority:38You can configure your model in several ways, listed in order of priority:


58}64}

59```65```

60 66 

67## Restrict model selection

68 

69Enterprise administrators can use `availableModels` in [managed or policy settings](/en/settings#settings-files) to restrict which models users can select.

70 

71When `availableModels` is set, users cannot switch to models not in the list via `/model`, `--model` flag, Config tool, or `ANTHROPIC_MODEL` environment variable.

72 

73```json theme={null}

74{

75 "availableModels": ["sonnet", "haiku"]

76}

77```

78 

79### Default model behavior

80 

81The 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:

82 

83| User type | Default model |

84| :---------------------------- | :------------ |

85| Max, Team, or Pro subscribers | Opus 4.6 |

86| Pay-as-you-go (API) users | Sonnet 4.5 |

87 

88Even with `availableModels: []`, users can still use Claude Code with the Default model for their tier.

89 

90### Control the model users run on

91 

92To fully control the model experience, use `availableModels` together with the `model` setting:

93 

94* **availableModels**: restricts what users can switch to

95* **model**: sets the explicit model override, taking precedence over the Default

96 

97This example ensures all users run Sonnet 4.5 and can only choose between Sonnet and Haiku:

98 

99```json theme={null}

100{

101 "model": "sonnet",

102 "availableModels": ["sonnet", "haiku"]

103}

104```

105 

106### Merge behavior

107 

108When `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.

109 

61## Special model behavior110## Special model behavior

62 111 

63### `default` model setting112### `default` model setting

64 113 

65The behavior of `default` depends on your account type.114The behavior of `default` depends on your account type:

115 

116* **Max and Team Premium**: defaults to Opus 4.6

117* **Pro and Team Standard**: defaults to Sonnet 4.6

118* **Enterprise**: Opus 4.6 is available but not the default

66 119 

67For certain Max users, Claude Code will automatically fall back to Sonnet if you120Claude Code may automatically fall back to Sonnet if you hit a usage threshold with Opus.

68hit a usage threshold with Opus.

69 121 

70### `opusplan` model setting122### `opusplan` model setting

71 123 


79This gives you the best of both worlds: Opus's superior reasoning for planning,131This gives you the best of both worlds: Opus's superior reasoning for planning,

80and Sonnet's efficiency for execution.132and Sonnet's efficiency for execution.

81 133 

82### Extended context with \[1m]134### Adjust effort level

135 

136[Effort levels](https://platform.claude.com/docs/en/build-with-claude/effort) control Opus 4.6's 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.

83 137 

84For Console/API users, the `[1m]` suffix can be added to full model names to138Three levels are available: **low**, **medium**, and **high** (default).

85enable a139 

86[1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window).140**Setting effort:**

141 

142* **In `/model`**: use left/right arrow keys to adjust the effort slider when selecting a model

143* **Environment variable**: set `CLAUDE_CODE_EFFORT_LEVEL=low|medium|high`

144* **Settings**: set `effortLevel` in your settings file

145 

146Effort is currently supported on Opus 4.6. The effort slider appears in `/model` when a supported model is selected.

147 

148### Extended context

149 

150Opus 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.

151 

152<Note>

153 The 1M context window is currently in beta. Features, pricing, and availability may change.

154</Note>

155 

156Extended context is available for:

157 

158* **API and pay-as-you-go users**: full access to 1M context

159* **Pro, Max, Teams, and Enterprise subscribers**: available with [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) enabled

160 

161Selecting a 1M model does not immediately change billing. Your session uses standard rates until it exceeds 200K tokens of context. Beyond 200K tokens, requests are charged at [long-context pricing](https://platform.claude.com/docs/en/about-claude/pricing#long-context-pricing) with dedicated [rate limits](https://platform.claude.com/docs/en/api/rate-limits#long-context-rate-limits). For subscribers, tokens beyond 200K are billed as extra usage rather than through the subscription.

162 

163If 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.

164 

165You can also use the `[1m]` suffix with model aliases or full model names:

87 166 

88```bash theme={null}167```bash theme={null}

89# Example of using a full model name with the [1m] suffix168# Use the sonnet[1m] alias

90/model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]169/model sonnet[1m]

91```

92 170 

93Note: Extended context models have171# Or append [1m] to a full model name

94[different pricing](https://docs.claude.com/en/docs/about-claude/pricing#long-context-pricing).172/model claude-sonnet-4-6[1m]

173```

95 174 

96## Checking your current model175## Checking your current model

97 176 


115Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of194Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of

116`ANTHROPIC_DEFAULT_HAIKU_MODEL`.195`ANTHROPIC_DEFAULT_HAIKU_MODEL`.

117 196 

197### Pin models for third-party deployments

198 

199When 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.

200 

201Without 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.

202 

203<Warning>

204 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.

205</Warning>

206 

207Use the following environment variables with version-specific model IDs for your provider:

208 

209| Provider | Example |

210| :-------- | :---------------------------------------------------------------------- |

211| Bedrock | `export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'` |

212| Vertex AI | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |

213| Foundry | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |

214 

215Apply 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.

216 

217<Note>

218 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.

219</Note>

220 

118### Prompt caching configuration221### Prompt caching configuration

119 222 

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:223Claude 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 224 

122| Environment variable | Description |225| Environment variable | Description |

123| ------------------------------- | ---------------------------------------------------------------------------------------------- |226| ------------------------------- | ---------------------------------------------------------------------------------------------- |


127| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only |230| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only |

128 231 

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.232These 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 


88* [Claude Code settings](/en/settings)91* [Claude Code settings](/en/settings)

89* [Environment variables reference](/en/settings#environment-variables)92* [Environment variables reference](/en/settings#environment-variables)

90* [Troubleshooting guide](/en/troubleshooting)93* [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

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


106### Output Styles vs. [Skills](/en/skills)110### Output Styles vs. [Skills](/en/skills)

107 111 

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.112Output 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 +141 −69

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) 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 


56 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.62 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

57 </Info>63 </Info>

58 </Tab>64 </Tab>

59</Tabs>65 </Tabs>

60 66 

61**Start using Claude Code:**67 Then start Claude Code in any project:

62 68 

63```bash theme={null}69 ```bash theme={null}

64cd your-project70 cd your-project

65claude71 claude

66```72 ```

67 73 

68You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 minutes) →](/en/quickstart)74 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/en/quickstart)

69 75 

70<Tip>76 <Tip>

71 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.77 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.

72</Tip>78 </Tip>

79 </Tab>

73 80 

74## What Claude Code does for you81 <Tab title="VS Code">

82 The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.

75 83 

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.84 * [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.85 * [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 86 

81## Why developers love Claude Code87 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 88 

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.89 [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.90 </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 91 

88## Next steps92 <Tab title="Desktop app">

93 A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, and kick off cloud sessions.

94 

95 Download and install:

96 

97 * [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) (Intel and Apple Silicon)

98 * [Windows](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs) (x64)

99 * [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs) (remote sessions only)

89 100 

90<CardGroup>101 After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](https://claude.com/pricing) is required.

91 <Card title="Quickstart" icon="rocket" href="/en/quickstart">

92 See Claude Code in action with practical examples

93 </Card>

94 102 

95 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">103 [Learn more about the desktop app →](/en/desktop#get-started)

96 Step-by-step guides for common workflows104 </Tab>

97 </Card>

98 105 

99 <Card title="Troubleshooting" icon="wrench" href="/en/troubleshooting">106 <Tab title="Web">

100 Solutions for common issues with Claude Code107 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.

101 </Card>

102 108 

103 <Card title="IDE setup" icon="laptop" href="/en/vs-code">109 Start coding at [claude.ai/code](https://claude.ai/code).

104 Add Claude Code to your IDE

105 </Card>

106</CardGroup>

107 110 

108## Additional resources111 [Get started on the web →](/en/claude-code-on-the-web#getting-started)

112 </Tab>

109 113 

110<CardGroup>114 <Tab title="JetBrains">

111 <Card title="About Claude Code" icon="sparkles" href="https://claude.com/product/claude-code">115 A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.

112 Learn more about Claude Code on claude.com

113 </Card>

114 116 

115 <Card title="Build with the Agent SDK" icon="code-branch" href="https://docs.claude.com/en/docs/agent-sdk/overview">117 Install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains Marketplace and restart your IDE.

116 Create custom AI agents with the Claude Agent SDK

117 </Card>

118 118 

119 <Card title="Host on AWS or GCP" icon="cloud" href="/en/third-party-integrations">119 [Get started with JetBrains →](/en/jetbrains)

120 Configure Claude Code with Amazon Bedrock or Google Vertex AI120 </Tab>

121 </Card>121</Tabs>

122 122 

123 <Card title="Settings" icon="gear" href="/en/settings">123## What you can do

124 Customize Claude Code for your workflow

125 </Card>

126 124 

127 <Card title="Commands" icon="terminal" href="/en/cli-reference">125Here are some of the ways you can use Claude Code:

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">127<AccordionGroup>

132 Clone our development container reference implementation128 <Accordion title="Automate the work you keep putting off" icon="wand-magic-sparkles">

133 </Card>129 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.

134 130 

135 <Card title="Security" icon="shield" href="/en/security">131 ```bash theme={null}

136 Discover Claude Code's safeguards and best practices for safe usage132 claude "write tests for the auth module, run them, and fix any failures"

137 </Card>133 ```

134 </Accordion>

138 135 

139 <Card title="Privacy and data usage" icon="lock" href="/en/data-usage">136 <Accordion title="Build features and fix bugs" icon="hammer">

140 Understand how Claude Code handles your data137 Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.

141 </Card>138 

142</CardGroup>139 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.

140 </Accordion>

141 

142 <Accordion title="Create commits and pull requests" icon="code-branch">

143 Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests.

144 

145 ```bash theme={null}

146 claude "commit my changes with a descriptive message"

147 ```

143 148 

149 In CI, you can automate code review and issue triage with [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd).

150 </Accordion>

151 

152 <Accordion title="Connect your tools with MCP" icon="plug">

153 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.

154 </Accordion>

155 

156 <Accordion title="Customize with instructions, skills, and hooks" icon="sliders">

157 [`CLAUDE.md`](/en/claude-md) 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.

158 

159 Create [custom slash commands](/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.

160 

161 [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.

162 </Accordion>

163 

164 <Accordion title="Run agent teams and build custom agents" icon="users">

165 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.

166 

167 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.

168 </Accordion>

169 

170 <Accordion title="Pipe, script, and automate with the CLI" icon="terminal">

171 Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:

172 

173 ```bash theme={null}

174 # Monitor logs and get alerted

175 tail -f app.log | claude -p "Slack me if you see any anomalies"

176 

177 # Automate translations in CI

178 claude -p "translate new strings into French and raise a PR for review"

179 

180 # Bulk operations across files

181 git diff main --name-only | claude -p "review these changed files for security issues"

182 ```

183 

184 See the [CLI reference](/en/cli-reference) for the full set of commands and flags.

185 </Accordion>

186 

187 <Accordion title="Work from anywhere" icon="globe">

188 Sessions aren't tied to a single surface. Move work between environments as your context changes:

189 

190 * 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`

191 * Hand off a terminal session to the [Desktop app](/en/desktop) with `/desktop` for visual diff review

192 * Route tasks from team chat: mention `@Claude` in [Slack](/en/slack) with a bug report and get a pull request back

193 </Accordion>

194</AccordionGroup>

195 

196## Use Claude Code everywhere

197 

198Each surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them.

199 

200Beyond 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:

201 

202| I want to... | Best option |

203| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |

204| 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) |

205| Automate PR reviews and issue triage | [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd) |

206| Route bug reports from Slack to pull requests | [Slack](/en/slack) |

207| Debug live web applications | [Chrome](/en/chrome) |

208| Build custom agents for your own workflows | [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) |

209 

210## Next steps

144 211 

212Once you've installed Claude Code, these guides help you go deeper.

145 213 

146> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt214* [Quickstart](/en/quickstart): walk through your first real task, from exploring a codebase to committing a fix

215* Level up with [best practices](/en/best-practices) and [common workflows](/en/common-workflows)

216* [Settings](/en/settings): customize Claude Code for your workflow

217* [Troubleshooting](/en/troubleshooting): solutions for common issues

218* [code.claude.com](https://code.claude.com/): demos, pricing, and product details

permissions.md +257 −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 settings file** | `Edit(/src/**/*.ts)` | `<settings file path>/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 your settings file. Use `//Users/alice/file` for absolute paths.

147</Warning>

148 

149Examples:

150 

151* `Edit(/docs/**)`: edits in `<project>/docs/` (NOT `/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### Task (subagents)

171 

172Use `Task(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use:

173 

174* `Task(Explore)` matches the Explore subagent

175* `Task(Plan)` matches the Plan subagent

176* `Task(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": ["Task(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.json` files to system directories. These policy files follow the same format as regular settings files and cannot be overridden by user or project settings. For organizations without device management infrastructure, [server-managed settings](/en/server-managed-settings) provide an alternative that delivers configurations from Anthropic's servers.

219 

220**Managed settings file locations**:

221 

222* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`

223* **Linux and WSL**: `/etc/claude-code/managed-settings.json`

224* **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json`

225 

226<Note>

227 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.

228</Note>

229 

230### Managed-only settings

231 

232Some settings are only effective in managed settings:

233 

234| Setting | Description |

235| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |

236| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode and the `--dangerously-skip-permissions` flag |

237| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |

238| `allowManagedHooksOnly` | When `true`, prevents loading of user, project, and plugin hooks. Only managed hooks and SDK hooks are allowed |

239| `strictKnownMarketplaces` | Controls which plugin marketplaces users can add. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

240 

241## Settings precedence

242 

243Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings: managed settings have the highest precedence, followed by command line arguments, local project, shared project, and user settings.

244 

245If a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked.

246 

247## Example configurations

248 

249This [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.

250 

251## See also

252 

253* [Settings](/en/settings): complete configuration reference including the permission settings table

254* [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands

255* [Authentication](/en/authentication): set up user access to Claude Code

256* [Security](/en/security): security safeguards and best practices

257* [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 


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| `npm` | object | `package`, `version?`, `registry?` | Installed via `npm install` |

228| `pip` | object | `package`, `version?`, `registry?` | Installed via pip |

229 

230<Note>

231 **Marketplace sources vs plugin sources**: These are different concepts that control different things.

232 

233 * **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`.

234 * **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).

235 

236 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.

237</Note>

238 

214### Relative paths239### Relative paths

215 240 

216For plugins in the same repository:241For plugins in the same repository:


345 370 

346* **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root.371* **`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.372* **`${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.373* **`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.

374 

375### Strict mode

376 

377The `strict` field controls whether `plugin.json` is the authority for component definitions (commands, agents, hooks, skills, MCP servers, output styles).

378 

379| Value | Behavior |

380| :--------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |

381| `true` (default) | `plugin.json` is the authority. The marketplace entry can supplement it with additional components, and both sources are merged. |

382| `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. |

383 

384**When to use each mode:**

385 

386* **`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.

387* **`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 388 

350## Host and distribute marketplaces389## Host and distribute marketplaces

351 390 


369 408 

370### Private repositories409### Private repositories

371 410 

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.411Claude 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`.

412 

413Background 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 414 

374| Provider | Environment variables | Notes |415| Provider | Environment variables | Notes |

375| :-------- | :--------------------------- | :---------------------------------------- |416| :-------- | :--------------------------- | :---------------------------------------- |


383export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx424export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

384```425```

385 426 

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>427<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.428 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>429</Note>


474}513}

475```514```

476 515 

516Allow all marketplaces from an internal git server using regex pattern matching:

517 

518```json theme={null}

519{

520 "strictKnownMarketplaces": [

521 {

522 "source": "hostPattern",

523 "hostPattern": "^github\\.example\\.com$"

524 }

525 ]

526}

527```

528 

477#### How restrictions work529#### How restrictions work

478 530 

479Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.531Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.

480 532 

481The allowlist uses exact matching. For a marketplace to be allowed, all specified fields must match exactly:533The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly:

482 534 

483* For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist535* 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 exactly536* For URL sources: the full URL must match exactly

537* For `hostPattern` sources: the marketplace host is matched against the regex pattern

485 538 

486Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.539Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.

487 540 

488For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).541For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).

489 542 

543### Version resolution and release channels

544 

545Plugin 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`).

546 

547<Warning>

548 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.

549</Warning>

550 

551#### Set up release channels

552 

553To 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).

554 

555<Warning>

556 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.

557</Warning>

558 

559##### Example

560 

561```json theme={null}

562{

563 "name": "stable-tools",

564 "plugins": [

565 {

566 "name": "code-formatter",

567 "source": {

568 "source": "github",

569 "repo": "acme-corp/code-formatter",

570 "ref": "stable"

571 }

572 }

573 ]

574}

575```

576 

577```json theme={null}

578{

579 "name": "latest-tools",

580 "plugins": [

581 {

582 "name": "code-formatter",

583 "source": {

584 "source": "github",

585 "repo": "acme-corp/code-formatter",

586 "ref": "latest"

587 }

588 }

589 ]

590}

591```

592 

593##### Assign channels to user groups

594 

595Assign each marketplace to the appropriate user group through managed settings. For example, the stable group receives:

596 

597```json theme={null}

598{

599 "extraKnownMarketplaces": {

600 "stable-tools": {

601 "source": {

602 "source": "github",

603 "repo": "acme-corp/stable-tools"

604 }

605 }

606 }

607}

608```

609 

610The early-access group receives `latest-tools` instead:

611 

612```json theme={null}

613{

614 "extraKnownMarketplaces": {

615 "latest-tools": {

616 "source": {

617 "source": "github",

618 "repo": "acme-corp/latest-tools"

619 }

620 }

621 }

622}

623```

624 

490## Validation and testing625## Validation and testing

491 626 

492Test your marketplace before sharing.627Test your marketplace before sharing.


560 695 

561### Private repository authentication fails696### Private repository authentication fails

562 697 

563**Symptoms**: Authentication errors when installing plugins from private repositories, even with tokens configured698**Symptoms**: Authentication errors when installing plugins from private repositories

564 699 

565**Solutions**:700**Solutions**:

566 701 

567* Verify your token is set in the current shell session: `echo $GITHUB_TOKEN`702For manual installation and updates:

703 

704* Verify you're authenticated with your git provider (for example, run `gh auth status` for GitHub)

705* Check that your credential helper is configured correctly: `git config --global credential.helper`

706* Try cloning the repository manually to verify your credentials work

707 

708For background auto-updates:

709 

710* Set the appropriate token in your environment: `echo $GITHUB_TOKEN`

568* Check that the token has the required permissions (read access to the repository)711* 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 repositories712* For GitHub, ensure the token has the `repo` scope for private repositories

570* For GitLab, ensure the token has at least `read_repository` scope713* For GitLab, ensure the token has at least `read_repository` scope

571* Verify the token hasn't expired714* Verify the token hasn't expired

572* If using multiple git providers, ensure you've set the token for the correct provider

573 715 

574### Plugins with relative paths fail in URL-based marketplaces716### Plugins with relative paths fail in URL-based marketplaces

575 717 


602* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas744* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas

603* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options745* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options

604* [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions746* [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 +31 −16

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.


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 Restart Claude Code 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).


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).


264 283 

265As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components:284As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components:

266 285 

267* Try your commands with `/command-name`286* Try your skills with `/plugin-name:skill-name`

268* Check that agents appear in `/agents`287* Check that agents appear in `/agents`

269* Verify hooks work as expected288* Verify hooks work as expected

270 289 


346 mkdir my-plugin/hooks365 mkdir my-plugin/hooks

347 ```366 ```

348 367 

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:368 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 369 

351 ```json my-plugin/hooks/hooks.json theme={null}370 ```json my-plugin/hooks/hooks.json theme={null}

352 {371 {


354 "PostToolUse": [373 "PostToolUse": [

355 {374 {

356 "matcher": "Write|Edit",375 "matcher": "Write|Edit",

357 "hooks": [{ "type": "command", "command": "npm run lint:fix $FILE" }]376 "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }]

358 }377 }

359 ]378 ]

360 }379 }


404 * [Subagents](/en/sub-agents): agent configuration and capabilities423 * [Subagents](/en/sub-agents): agent configuration and capabilities

405 * [Hooks](/en/hooks): event handling and automation424 * [Hooks](/en/hooks): event handling and automation

406 * [MCP](/en/mcp): external tool integration425 * [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 


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.


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 


432 410 

433```411```

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 


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 +51 −62

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!


10 14 

11* A terminal or command prompt open15* A terminal or command prompt open

12* A code project to work with16* 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/) account17* A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/en/third-party-integrations)

18 

19<Note>

20 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).

21</Note>

14 22 

15## Step 1: Install Claude Code23## Step 1: Install Claude Code

16 24 


79You can log in using any of these account types:87You can log in using any of these account types:

80 88 

81* [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended)89* [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended)

82* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits)90* [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.

91* [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) (enterprise cloud providers)

83 92 

84Once logged in, your credentials are stored and you won't need to log in again.93Once 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 94 

94## Step 3: Start your first session95## Step 3: Start your first session

95 96 


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.104You'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 105 

105<Tip>106<Tip>

106 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/iam#credential-management).107 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/authentication#credential-management).

107</Tip>108</Tip>

108 109 

109## Step 4: Ask your first question110## Step 4: Ask your first question


111Let's start with understanding your codebase. Try one of these commands:112Let's start with understanding your codebase. Try one of these commands:

112 113 

113```114```

114> what does this project do?115what does this project do?

115```116```

116 117 

117Claude will analyze your files and provide a summary. You can also ask more specific questions:118Claude will analyze your files and provide a summary. You can also ask more specific questions:

118 119 

119```120```

120> what technologies does this project use?121what technologies does this project use?

121```122```

122 123 

123```124```

124> where is the main entry point?125where is the main entry point?

125```126```

126 127 

127```128```

128> explain the folder structure129explain the folder structure

129```130```

130 131 

131You can also ask Claude about its own capabilities:132You can also ask Claude about its own capabilities:

132 133 

133```134```

134> what can Claude Code do?135what can Claude Code do?

135```136```

136 137 

137```138```

138> how do I create custom skills in Claude Code?139how do I create custom skills in Claude Code?

139```140```

140 141 

141```142```

142> can Claude Code work with Docker?143can Claude Code work with Docker?

143```144```

144 145 

145<Note>146<Note>


151Now let's make Claude Code do some actual coding. Try a simple task:152Now let's make Claude Code do some actual coding. Try a simple task:

152 153 

153```154```

154> add a hello world function to the main file155add a hello world function to the main file

155```156```

156 157 

157Claude Code will:158Claude Code will:


170Claude Code makes Git operations conversational:171Claude Code makes Git operations conversational:

171 172 

172```173```

173> what files have I changed?174what files have I changed?

174```175```

175 176 

176```177```

177> commit my changes with a descriptive message178commit my changes with a descriptive message

178```179```

179 180 

180You can also prompt for more complex Git operations:181You can also prompt for more complex Git operations:

181 182 

182```183```

183> create a new branch called feature/quickstart184create a new branch called feature/quickstart

184```185```

185 186 

186```187```

187> show me the last 5 commits188show me the last 5 commits

188```189```

189 190 

190```191```

191> help me resolve merge conflicts192help me resolve merge conflicts

192```193```

193 194 

194## Step 7: Fix a bug or add a feature195## Step 7: Fix a bug or add a feature


198Describe what you want in natural language:199Describe what you want in natural language:

199 200 

200```201```

201> add input validation to the user registration form202add input validation to the user registration form

202```203```

203 204 

204Or fix existing issues:205Or fix existing issues:

205 206 

206```207```

207> there's a bug where users can submit empty forms - fix it208there's a bug where users can submit empty forms - fix it

208```209```

209 210 

210Claude Code will:211Claude Code will:


221**Refactor code**222**Refactor code**

222 223 

223```224```

224> refactor the authentication module to use async/await instead of callbacks225refactor the authentication module to use async/await instead of callbacks

225```226```

226 227 

227**Write tests**228**Write tests**

228 229 

229```230```

230> write unit tests for the calculator functions231write unit tests for the calculator functions

231```232```

232 233 

233**Update documentation**234**Update documentation**

234 235 

235```236```

236> update the README with installation instructions237update the README with installation instructions

237```238```

238 239 

239**Code review**240**Code review**

240 241 

241```242```

242> review my changes and suggest improvements243review my changes and suggest improvements

243```244```

244 245 

245<Tip>246<Tip>


258| `claude -c` | Continue most recent conversation in current directory | `claude -c` |259| `claude -c` | Continue most recent conversation in current directory | `claude -c` |

259| `claude -r` | Resume a previous conversation | `claude -r` |260| `claude -r` | Resume a previous conversation | `claude -r` |

260| `claude commit` | Create a Git commit | `claude commit` |261| `claude commit` | Create a Git commit | `claude commit` |

261| `/clear` | Clear conversation history | `> /clear` |262| `/clear` | Clear conversation history | `/clear` |

262| `/help` | Show available commands | `> /help` |263| `/help` | Show available commands | `/help` |

263| `exit` or Ctrl+C | Exit Claude Code | `> exit` |264| `exit` or Ctrl+C | Exit Claude Code | `exit` |

264 265 

265See the [CLI reference](/en/cli-reference) for a complete list of commands.266See the [CLI reference](/en/cli-reference) for a complete list of commands.

266 267 

267## Pro tips for beginners268## Pro tips for beginners

268 269 

270For more, see [best practices](/en/best-practices) and [common workflows](/en/common-workflows).

271 

269<AccordionGroup>272<AccordionGroup>

270 <Accordion title="Be specific with your requests">273 <Accordion title="Be specific with your requests">

271 Instead of: "fix the bug"274 Instead of: "fix the bug"


277 Break complex tasks into steps:280 Break complex tasks into steps:

278 281 

279 ```282 ```

280 > 1. create a new database table for user profiles283 1. create a new database table for user profiles

281 ```284 2. create an API endpoint to get and update user profiles

282 285 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 ```286 ```

290 </Accordion>287 </Accordion>

291 288 


293 Before making changes, let Claude understand your code:290 Before making changes, let Claude understand your code:

294 291 

295 ```292 ```

296 > analyze the database schema293 analyze the database schema

297 ```294 ```

298 295 

299 ```296 ```

300 > build a dashboard showing products that are most frequently returned by our UK customers297 build a dashboard showing products that are most frequently returned by our UK customers

301 ```298 ```

302 </Accordion>299 </Accordion>

303 300 


313 310 

314Now that you've learned the basics, explore more advanced features:311Now that you've learned the basics, explore more advanced features:

315 312 

316<CardGroup cols={3}>313<CardGroup cols={2}>

317 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">314 <Card title="How Claude Code works" icon="microchip" href="/en/how-claude-code-works">

318 Step-by-step guides for common tasks315 Understand the agentic loop, built-in tools, and how Claude Code interacts with your project

319 </Card>316 </Card>

320 317 

321 <Card title="CLI reference" icon="terminal" href="/en/cli-reference">318 <Card title="Best practices" icon="star" href="/en/best-practices">

322 Master all commands and options319 Get better results with effective prompting and project setup

323 </Card>320 </Card>

324 321 

325 <Card title="Configuration" icon="gear" href="/en/settings">322 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">

326 Customize Claude Code for your workflow323 Step-by-step guides for common tasks

327 </Card>

328 

329 <Card title="Claude Code on the web" icon="cloud" href="/en/claude-code-on-the-web">

330 Run tasks asynchronously in the cloud

331 </Card>324 </Card>

332 325 

333 <Card title="About Claude Code" icon="sparkles" href="https://claude.com/product/claude-code">326 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">

334 Learn more on claude.com327 Customize with CLAUDE.md, skills, hooks, MCP, and more

335 </Card>328 </Card>

336</CardGroup>329</CardGroup>

337 330 


340* **In Claude Code**: Type `/help` or ask "how do I..."333* **In Claude Code**: Type `/help` or ask "how do I..."

341* **Documentation**: You're here! Browse other guides334* **Documentation**: You're here! Browse other guides

342* **Community**: Join our [Discord](https://www.anthropic.com/discord) for tips and support335* **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

sandboxing.md +48 −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# 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.


51 55 

52The sandboxed bash tool leverages operating system security primitives:56The sandboxed bash tool leverages operating system security primitives:

53 57 

54* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation

55* **macOS**: Uses Seatbelt for sandbox enforcement58* **macOS**: Uses Seatbelt for sandbox enforcement

59* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation

60* **WSL2**: Uses bubblewrap, same as Linux

61 

62WSL1 is not supported because bubblewrap requires kernel features only available in WSL2.

56 63 

57These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries.64These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries.

58 65 

59## Getting started66## Getting started

60 67 

68### Prerequisites

69 

70On **macOS**, sandboxing works out of the box using the built-in Seatbelt framework.

71 

72On **Linux and WSL2**, install the required packages first:

73 

74<Tabs>

75 <Tab title="Ubuntu/Debian">

76 ```bash theme={null}

77 sudo apt-get install bubblewrap socat

78 ```

79 </Tab>

80 

81 <Tab title="Fedora">

82 ```bash theme={null}

83 sudo dnf install bubblewrap socat

84 ```

85 </Tab>

86</Tabs>

87 

61### Enable sandboxing88### Enable sandboxing

62 89 

63You can enable sandboxing by running the `/sandbox` command:90You can enable sandboxing by running the `/sandbox` command:


66> /sandbox93> /sandbox

67```94```

68 95 

69This opens a menu where you can choose between sandbox modes.96This 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.

70 97 

71### Sandbox modes98### Sandbox modes

72 99 


110 137 

111* Cannot modify critical config files such as `~/.bashrc`138* Cannot modify critical config files such as `~/.bashrc`

112* Cannot modify system-level files in `/bin/`139* Cannot modify system-level files in `/bin/`

113* Cannot read files that are denied in your [Claude permission settings](/en/iam#configuring-permissions)140* Cannot read files that are denied in your [Claude permission settings](/en/permissions#manage-permissions)

114 141 

115**Network protection:**142**Network protection:**

116 143 


157* 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.184* 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.

158* 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.185* 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.

159 186 

187## How sandboxing relates to permissions

188 

189Sandboxing and [permissions](/en/permissions) are complementary security layers that work together:

190 

191* **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.

192* **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.

193 

194Filesystem and network restrictions are configured through permission rules, not sandbox settings:

195 

196* Use `Read` and `Edit` deny rules to block access to specific files or directories

197* Use `WebFetch` allow/deny rules to control domain access

198* Use sandbox `allowedDomains` to control which domains Bash commands can reach

199 

200This [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.

201 

160## Advanced usage202## Advanced usage

161 203 

162### Custom proxy configuration204### Custom proxy configuration


183 225 

184The sandboxed bash tool works alongside:226The sandboxed bash tool works alongside:

185 227 

186* **IAM policies**: Combine with [permission settings](/en/iam) for defense-in-depth228* **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth

187* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation229* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation

188* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)230* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)

189 231 


209 251 

210* **Performance overhead**: Minimal, but some filesystem operations may be slightly slower252* **Performance overhead**: Minimal, but some filesystem operations may be slightly slower

211* **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox253* **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox

212* **Platform support**: Currently supports Linux and macOS; Windows support planned254* **Platform support**: Supports macOS, Linux, and WSL2. WSL1 is not supported. Native Windows support is planned.

213 255 

214## See also256## See also

215 257 

216* [Security](/en/security) - Comprehensive security features and best practices258* [Security](/en/security) - Comprehensive security features and best practices

217* [IAM](/en/iam) - Permission configuration and access control259* [Permissions](/en/permissions) - Permission configuration and access control

218* [Settings](/en/settings) - Complete configuration reference260* [Settings](/en/settings) - Complete configuration reference

219* [CLI reference](/en/cli-reference) - Command-line options261* [CLI reference](/en/cli-reference) - Command-line options

220 

221 

222 

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

security.md +10 −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.


113 117 

114### Team security118### Team security

115 119 

116* Use [managed settings](/en/iam#managed-settings) to enforce organizational standards120* Use [managed settings](/en/permissions#managed-settings) to enforce organizational standards

117* Share approved permission configurations through version control121* Share approved permission configurations through version control

118* Train team members on security best practices122* Train team members on security best practices

119* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)123* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)

124* Audit or block settings changes during sessions with [`ConfigChange` hooks](/en/hooks#configchange)

120 125 

121### Reporting security issues126### Reporting security issues

122 127 


130## Related resources135## Related resources

131 136 

132* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands137* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands

133* [Identity and Access Management](/en/iam) - Configure permissions and access controls138* [Permissions](/en/permissions) - Configure permissions and access controls

134* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity139* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity

135* [Development containers](/en/devcontainer) - Secure, isolated environments140* [Development containers](/en/devcontainer) - Secure, isolated environments

136* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance141* [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#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales) 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/permissions#managed-settings) deploy a `managed-settings.json` file to system directories via MDM (mobile device management).

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/permissions#managed-settings)** | Organizations with MDM or endpoint management | Settings deployed to protected system directories by IT |

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 },

58 "disableBypassPermissionsMode": "disable"

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/permissions#managed-settings) both occupy the highest tier in the Claude Code [settings hierarchy](/en/settings#settings-precedence), and user or project settings cannot override them. When both are present, server-managed settings take precedence and the local `managed-settings.json` file is 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/permissions#managed-settings) 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/permissions#managed-settings): file-based managed settings deployed by IT

163* [Authentication](/en/authentication): set up user access to Claude Code

164* [Security](/en/security): security safeguards and best practices

settings.md +184 −190

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.


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.93 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.

90 </Note>94 </Note>

91 95 

92 See [Managed settings](/en/iam#managed-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details.96 See [Managed settings](/en/permissions#managed-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details. For organizations without device management infrastructure, see [server-managed settings](/en/server-managed-settings).

93 97 

94 <Note>98 <Note>

95 Managed deployments can also restrict **plugin marketplace additions** using99 Managed deployments can also restrict **plugin marketplace additions** using


97 </Note>101 </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`.102* **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 103 

104<Note>

105 Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.

106</Note>

107 

100```JSON Example settings.json theme={null}108```JSON Example settings.json theme={null}

101{109{

110 "$schema": "https://json.schemastore.org/claude-code-settings.json",

102 "permissions": {111 "permissions": {

103 "allow": [112 "allow": [

104 "Bash(npm run lint)",113 "Bash(npm run lint)",

105 "Bash(npm run test:*)",114 "Bash(npm run test *)",

106 "Read(~/.zshrc)"115 "Read(~/.zshrc)"

107 ],116 ],

108 "deny": [117 "deny": [

109 "Bash(curl:*)",118 "Bash(curl *)",

110 "Read(./.env)",119 "Read(./.env)",

111 "Read(./.env.*)",120 "Read(./.env.*)",

112 "Read(./secrets/**)"121 "Read(./secrets/**)"


124}133}

125```134```

126 135 

136The `$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.

137 

127### Available settings138### Available settings

128 139 

129`settings.json` supports a number of options:140`settings.json` supports a number of options:

130 141 

131| Key | Description | Example |142| Key | Description | Example |

132| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- |143| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- |

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` |144| `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` |145| `cleanupPeriodDays` | Sessions inactive for longer than this period are deleted at startup. Setting to `0` immediately deletes all sessions. (default: 30 days) | `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"]` |146| `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"]` |


137| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |148| `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` |149| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |

139| `permissions` | See table below for structure of permissions. | |150| `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...'"}}` |151| `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` |152| `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` |153| `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"` |154| `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` |

155| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-6"` |

156| `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"]` |

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` |157| `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"}` |158| `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"}` |159| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.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` |172| `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"` |173| `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` |174| `showTurnDuration` | Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to `false` to hide these messages | `true` |

175| `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"` |176| `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"` |177| `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` |178| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |

179| `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` |180| `terminalProgressBarEnabled` | Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: `true`) | `false` |

181| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |

182| `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"` |

166 183 

167### Permission settings184### Permission settings

168 185 

169| Keys | Description | Example |186| Keys | Description | Example |

170| :----------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |187| :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |

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:*)" ]` |188| `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:*)" ]` |189| `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/**)" ]` |190| `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/**)" ]` |

174| `additionalDirectories` | Additional [working directories](/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` |191| `additionalDirectories` | Additional [working directories](/en/permissions#working-directories) that Claude has access to | `[ "../docs/" ]` |

175| `defaultMode` | Default [permission mode](/en/iam#permission-modes) when opening Claude Code | `"acceptEdits"` |192| `defaultMode` | Default [permission mode](/en/permissions#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"` |193| `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-settings) | `"disable"` |

177 194 

178### Permission rule syntax195### Permission rule syntax

179 196 

180Permission rules follow the format `Tool` or `Tool(specifier)`. Understanding the syntax helps you write rules that match exactly what you intend.197Permission 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.

181 

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 198 

190The first matching rule determines the behavior. This means deny rules always take precedence over allow rules, even if both match the same command.199Quick examples:

191 

192#### Matching all uses of a tool

193 

194To match all uses of a tool, use just the tool name without parentheses:

195 

196| Rule | Effect |

197| :--------- | :--------------------------------- |

198| `Bash` | Matches **all** Bash commands |

199| `WebFetch` | Matches **all** web fetch requests |

200| `Read` | Matches **all** file reads |

201 

202<Warning>

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 

206#### Using specifiers for fine-grained control

207 

208Add a specifier in parentheses to match specific tool uses:

209 200 

210| Rule | Effect |201| Rule | Effect |

211| :----------------------------- | :------------------------------------------------------- |202| :----------------------------- | :--------------------------------------- |

212| `Bash(npm run build)` | Matches the exact command `npm run build` |203| `Bash` | Matches all Bash commands |

213| `Read(./.env)` | Matches reading the `.env` file in the current directory |204| `Bash(npm run *)` | Matches commands starting with `npm run` |

205| `Read(./.env)` | Matches reading the `.env` file |

214| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |206| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

215 207 

216#### Wildcard patterns208For the complete rule syntax reference, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Task 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 209 

266### Sandbox settings210### Sandbox settings

267 211 


270**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.214**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.

271 215 

272| Keys | Description | Example |216| Keys | Description | Example |

273| :-------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------ |217| :---------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ |

274| `enabled` | Enable bash sandboxing (macOS/Linux only). Default: false | `true` |218| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |

275| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |219| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |

276| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |220| `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` |221| `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` |

278| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |222| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |

223| `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` |224| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |

225| `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` |

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` |226| `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` |227| `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 only). **Reduces security.** Default: false | `true` |228| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |

283 229 

284**Configuration example:**230**Configuration example:**

285 231 


290 "autoAllowBashIfSandboxed": true,236 "autoAllowBashIfSandboxed": true,

291 "excludedCommands": ["docker"],237 "excludedCommands": ["docker"],

292 "network": {238 "network": {

239 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],

293 "allowUnixSockets": [240 "allowUnixSockets": [

294 "/var/run/docker.sock"241 "/var/run/docker.sock"

295 ],242 ],


329```276```

330🤖 Generated with [Claude Code](https://claude.com/claude-code)277🤖 Generated with [Claude Code](https://claude.com/claude-code)

331 278 

332 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>279 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

333```280```

334 281 

335**Default pull request attribution:**282**Default pull request attribution:**


409 356 

410Settings apply in order of precedence. From highest to lowest:357Settings apply in order of precedence. From highest to lowest:

411 358 

4121. **Managed settings** (`managed-settings.json`)3591. **Managed settings** ([`managed-settings.json`](/en/permissions#managed-settings) or [server-managed settings](/en/server-managed-settings))

413 * Policies deployed by IT/DevOps to system directories360 * Policies deployed by IT/DevOps to system directories, or delivered from Anthropic's servers for Claude for Enterprise customers

414 * Cannot be overridden by user or project settings361 * Cannot be overridden by user or project settings

415 362 

4162. **Command line arguments**3632. **Command line arguments**


427 374 

428This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience.375This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience.

429 376 

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.377For 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.

431 378 

432### Key points about the configuration system379### Key points about the configuration system

433 380 


460}407}

461```408```

462 409 

463This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns will be completely invisible to Claude Code, preventing any accidental exposure of sensitive data.410This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns are excluded from file discovery and search results, and read operations on these files are denied.

464 411 

465## Subagent configuration412## Subagent configuration

466 413 


554* `github`: GitHub repository (uses `repo`)501* `github`: GitHub repository (uses `repo`)

555* `git`: Any git URL (uses `url`)502* `git`: Any git URL (uses `url`)

556* `directory`: Local filesystem path (uses `path`, for development only)503* `directory`: Local filesystem path (uses `path`, for development only)

504* `hostPattern`: regex pattern to match marketplace hosts (uses `hostPattern`)

557 505 

558#### `strictKnownMarketplaces`506#### `strictKnownMarketplaces`

559 507 

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.508**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [`managed-settings.json`](/en/permissions#managed-settings) and provides administrators with strict control over marketplace sources.

561 509 

562**Managed settings file locations**:510**Managed settings file locations**:

563 511 


570* Only available in managed settings (`managed-settings.json`)518* Only available in managed settings (`managed-settings.json`)

571* Cannot be overridden by user or project settings (highest precedence)519* Cannot be overridden by user or project settings (highest precedence)

572* Enforced BEFORE network/filesystem operations (blocked sources never execute)520* Enforced BEFORE network/filesystem operations (blocked sources never execute)

573* Uses exact matching for source specifications (including `ref`, `path` for git sources)521* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching

574 522 

575**Allowlist behavior**:523**Allowlist behavior**:

576 524 


580 528 

581**All supported source types**:529**All supported source types**:

582 530 

583The allowlist supports six marketplace source types. Each source must match exactly for a user's marketplace addition to be allowed.531The allowlist supports seven marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host.

584 532 

5851. **GitHub repositories**:5331. **GitHub repositories**:

586 534 


642 590 

643Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)591Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)

644 592 

5937. **Host pattern matching**:

594 

595```json theme={null}

596{ "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" }

597{ "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" }

598```

599 

600Fields: `hostPattern` (required: regex pattern to match against the marketplace host)

601 

602Use 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.

603 

604Host extraction by source type:

605 

606* `github`: always matches against `github.com`

607* `git`: extracts hostname from the URL (supports both HTTPS and SSH formats)

608* `url`: extracts hostname from the URL

609* `npm`, `file`, `directory`: not supported for host pattern matching

610 

645**Configuration examples**:611**Configuration examples**:

646 612 

647Example - Allow specific marketplaces only:613Example: allow specific marketplaces only:

648 614 

649```json theme={null}615```json theme={null}

650{616{


678}644}

679```645```

680 646 

647Example: allow all marketplaces from an internal git server:

648 

649```json theme={null}

650{

651 "strictKnownMarketplaces": [

652 {

653 "source": "hostPattern",

654 "hostPattern": "^github\\.example\\.com$"

655 }

656 ]

657}

658```

659 

681**Exact matching requirements**:660**Exact matching requirements**:

682 661 

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:662Marketplace sources must match **exactly** for a user's addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:


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.742 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>743</Note>

765 744 

766| Variable | Purpose |745| Variable | Purpose | |

767| :-------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |746| :--------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- |

768| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |747| `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 `) |748| `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) |749| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) | |

771| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) |750| `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) |751| `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) |752| `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)) |753| `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)) |754| `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)) | |

776| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |755| `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)) | |

777| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |756| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) | |

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/)) |757| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) | |

779| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |758| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock | |

780| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |759| `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/)) | |

781| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |760| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout 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) |761| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated | |

783| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |762| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands | |

784| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) |763| `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) | |

785| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |764| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command | |

786| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |765| `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 | `1` |

787| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |766| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Set to `1` to enable [agent teams](/en/agent-teams). Agent teams are experimental and disabled by default | |

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 |767| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) | |

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 |768| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication | |

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 |769| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) | |

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 |770| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication | |

792| `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 |771| `CLAUDE_CODE_EFFORT_LEVEL` | Set the effort level for supported models. Values: `low`, `medium`, `high` (default). Lower effort is faster and cheaper, higher effort provides deeper reasoning. Currently supported with Opus 4.6 only. See [Adjust effort level](/en/model-config#adjust-effort-level) | |

793| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |772| `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 | |

794| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |773| `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 | |

795| `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 |774| `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 | |

796| `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 |775| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Also disabled when using third-party providers or when telemetry is disabled. See [Session quality surveys](/en/data-usage#session-quality-surveys) | |

797| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |776| `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 | |

798| `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. |777| `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 | |

799| `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) |778| `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) | |

800| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |779| `CLAUDE_CODE_TEAM_NAME` | Name of the agent team this teammate belongs to. Set automatically on [agent team](/en/agent-teams) members | |

801| `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>` |780| `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 | |

802| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |781| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` | |

803| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |782| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context | |

804| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) |783| `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) | |

805| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) |784| `CLAUDE_CODE_ENABLE_TASKS` | Set to `false` to temporarily revert to the previous TODO list instead of the task tracking system. Default: `true`. See [Task list](/en/interactive-mode#task-list) | |

806| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |785| `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) | |

807| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) |786| `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 | |

808| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |787| `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 | |

809| `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files |788| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions | |

810| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. |789| `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. | |

811| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |790| `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) | |

812| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |791| `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) | |

813| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |792| `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 | |

814| `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 |793| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) | |

815| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text |794| `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>` | |

816| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |795| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) | |

817| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |796| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) | |

818| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |797| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) | |

819| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |798| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) | |

820| `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) |799| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) | |

821| `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) |800| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) | |

822| `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |801| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) | |

823| `HTTP_PROXY` | Specify HTTP proxy server for network connections |802| `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files | |

824| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |803| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. | |

825| `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 |804| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command | |

826| `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) |805| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages | |

827| `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). |806| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting | |

828| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |807| `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 | |

829| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |808| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text | |

830| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |809| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) | |

831| `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. |810| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models | |

832| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code |811| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models | |

833| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |812| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models | |

834| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |813| `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) | |

835| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |814| `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) | |

836| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |815| `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` | |

837| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |816| `HTTP_PROXY` | Specify HTTP proxy server for network connections | |

817| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections | |

818| `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 | |

819| `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) | |

820| `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. | |

821| `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` | |

822| `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) | |

823| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup | |

824| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution | |

825| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy | |

826| `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 | |

827| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code | |

828| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI | |

829| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI | |

830| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI | |

831| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI | |

832| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI | |

838 833 

839## Tools available to Claude834## Tools available to Claude

840 835 

841Claude Code has access to a set of powerful tools that help it understand and modify your codebase:836Claude Code has access to a set of powerful tools that help it understand and modify your codebase:

842 837 

843| Tool | Description | Permission Required |838| Tool | Description | Permission Required |

844| :------------------ | :------------------------------------------------------------------------------------------------- | :------------------ |839| :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |

845| **AskUserQuestion** | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |840| **AskUserQuestion** | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |

846| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes |841| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes |

847| **TaskOutput** | Retrieves output from a background task (bash shell or subagent) | No |842| **TaskOutput** | Retrieves output from a background task (bash shell or subagent) | No |


855| **Read** | Reads the contents of files | No |850| **Read** | Reads the contents of files | No |

856| **Skill** | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |851| **Skill** | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

857| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |852| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |

858| **TodoWrite** | Creates and manages structured task lists | No |853| **TaskCreate** | Creates a new task in the task list | No |

854| **TaskGet** | Retrieves full details for a specific task | No |

855| **TaskList** | Lists all tasks with their current status | No |

856| **TaskUpdate** | Updates task status, dependencies, details, or deletes tasks | No |

859| **WebFetch** | Fetches content from a specified URL | Yes |857| **WebFetch** | Fetches content from a specified URL | Yes |

860| **WebSearch** | Performs web searches with domain filtering | Yes |858| **WebSearch** | Performs web searches with domain filtering | Yes |

861| **Write** | Creates or overwrites files | Yes |859| **Write** | Creates or overwrites files | Yes |

860| **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 |

862 861 

863Permission 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).862Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/permissions#tool-specific-permission-rules).

864 863 

865### Bash tool behavior864### Bash tool behavior

866 865 


922 921 

923The hook writes to `$CLAUDE_ENV_FILE`, which is then sourced before each Bash command. This is ideal for team-shared project configurations.922The hook writes to `$CLAUDE_ENV_FILE`, which is then sourced before each Bash command. This is ideal for team-shared project configurations.

924 923 

925See [SessionStart hooks](/en/hooks#persisting-environment-variables) for more details on Option 3.924See [SessionStart hooks](/en/hooks#persist-environment-variables) for more details on Option 3.

926 925 

927### Extending tools with hooks926### Extending tools with hooks

928 927 


935 934 

936## See also935## See also

937 936 

938* [Identity and Access Management](/en/iam#configuring-permissions) - Permission system overview and how allow/ask/deny rules interact937* [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies

939* [Tool-specific permission rules](/en/iam#tool-specific-permission-rules) - Detailed patterns for Bash, Read, Edit, WebFetch, MCP, and Task tools, including security limitations938* [Authentication](/en/authentication): set up user access to Claude Code

940* [Managed settings](/en/iam#managed-settings) - Managed policy configuration for organizations939* [Troubleshooting](/en/troubleshooting): solutions for common configuration issues

941* [Troubleshooting](/en/troubleshooting) - Solutions for common configuration issues

942 

943 

944 

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

setup.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# Set up Claude Code5# Set up Claude Code

2 6 

3> Install, authenticate, and start using Claude Code on your development machine.7> Install, authenticate, and start using Claude Code on your development machine.

4 8 

5## System requirements9## System requirements

6 10 

7* **Operating Systems**: macOS 13.0+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows)11* **Operating System**:

12 * macOS 13.0+

13 * Windows 10 1809+ or Windows Server 2019+ ([see setup notes](#platform-specific-setup))

14 * Ubuntu 20.04+

15 * Debian 10+

16 * Alpine Linux 3.19+ ([additional dependencies required](#platform-specific-setup))

8* **Hardware**: 4 GB+ RAM17* **Hardware**: 4 GB+ RAM

9* **Network**: Internet connection required (see [network configuration](/en/network-config#network-access-requirements))18* **Network**: Internet connection required (see [network configuration](/en/network-config#network-access-requirements))

10* **Shell**: Works best in Bash or Zsh19* **Shell**: Works best in Bash or Zsh


78 Run `claude doctor` after installation to check your installation type and version.87 Run `claude doctor` after installation to check your installation type and version.

79</Tip>88</Tip>

80 89 

81<Note>90### Platform-specific setup

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`.91 

83</Note>92**Windows**: Run Claude Code natively (requires [Git Bash](https://git-scm.com/downloads/win)) or inside WSL. Both WSL 1 and WSL 2 are supported, but WSL 1 has limited support and does not support features like Bash tool sandboxing.

93 

94**Alpine Linux and other musl/uClibc-based distributions**:

95 

96The 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`.

97 

98On Alpine:

99 

100```bash theme={null}

101apk add libgcc libstdc++ ripgrep

102```

84 103 

85### Authentication104### Authentication

86 105 


192**Option 1: Claude Code within WSL**211**Option 1: Claude Code within WSL**

193 212 

194* Both WSL 1 and WSL 2 are supported213* Both WSL 1 and WSL 2 are supported

214* WSL 2 supports [sandboxing](/en/sandboxing) for enhanced security. WSL 1 does not support sandboxing.

195 215 

196**Option 2: Claude Code on native Windows with Git Bash**216**Option 2: Claude Code on native Windows with Git Bash**

197 217 


233}253}

234```254```

235 255 

236For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/iam#managed-settings).256For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/permissions#managed-settings).

237 257 

238### Disable auto-updates258### Disable auto-updates

239 259 


339rmdir /s /q ".claude"359rmdir /s /q ".claude"

340del ".mcp.json"360del ".mcp.json"

341```361```

342 

343 

344 

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

skills.md +53 −19

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 slash commands.


73Where you store a skill determines who can use it:77Where you store a skill determines who can use it:

74 78 

75| Location | Path | Applies to |79| Location | Path | Applies to |

76| :--------- | :----------------------------------------------- | :----------------------------- |80| :--------- | :------------------------------------------------------- | :----------------------------- |

77| Enterprise | See [managed settings](/en/iam#managed-settings) | All users in your organization |81| Enterprise | See [managed settings](/en/permissions#managed-settings) | All users in your organization |

78| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |82| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |

79| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |83| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |

80| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |84| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |

81 85 

82Project skills override personal skills with the same name. If you have files in `.claude/commands/`, those work the same way but a skill takes precedence over a command with the same name.86When skills share the same name across levels, higher-priority locations win: enterprise > personal > project. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict with other levels. If you have files in `.claude/commands/`, those work the same way, but if a skill and a command share the same name, the skill takes precedence.

83 87 

84#### Automatic discovery from nested directories88#### Automatic discovery from nested directories

85 89 


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.107 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>108</Note>

105 109 

110#### Skills from additional directories

111 

112Skills 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.

113 

114<Note>

115 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 memory from additional directories](/en/memory#load-memory-from-additional-directories).

116</Note>

117 

106## Configure skills118## Configure skills

107 119 

108Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.120Skills 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. |183| `model` | No | Model to use when this skill is active. |

172| `context` | No | Set to `fork` to run in a forked subagent context. |184| `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. |185| `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. |186| `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 187 

176#### Available string substitutions188#### Available string substitutions

177 189 


180| Variable | Description |192| Variable | Description |

181| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |193| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |

182| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |194| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |

195| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |

196| `$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. |197| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |

184 198 

185**Example using substitutions:**199**Example using substitutions:**


294 308 

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.309If 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 310 

311To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`:

312 

313```yaml theme={null}

314---

315name: migrate-component

316description: Migrate a component from one framework to another

317---

318 

319Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2].

320Preserve all existing behavior and tests.

321```

322 

323Running `/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:

324 

325```yaml theme={null}

326---

327name: migrate-component

328description: Migrate a component from one framework to another

329---

330 

331Migrate the $0 component from $1 to $2.

332Preserve all existing behavior and tests.

333```

334 

297## Advanced patterns335## Advanced patterns

298 336 

299### Inject dynamic context337### Inject dynamic context


308description: Summarize changes in a pull request346description: Summarize changes in a pull request

309context: fork347context: fork

310agent: Explore348agent: Explore

311allowed-tools: Bash(gh:*)349allowed-tools: Bash(gh *)

312---350---

313 351 

314## Pull request context352## Pull request context


379 417 

380### Restrict Claude's skill access418### Restrict Claude's skill access

381 419 

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.420By 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 421 

384Three ways to control which skills Claude can invoke:422Three ways to control which skills Claude can invoke:

385 423 


390Skill428Skill

391```429```

392 430 

393**Allow or deny specific skills** using [permission rules](/en/iam):431**Allow or deny specific skills** using [permission rules](/en/permissions):

394 432 

395```433```

396# Allow only specific skills434# Allow only specific skills

397Skill(commit)435Skill(commit)

398Skill(review-pr:*)436Skill(review-pr *)

399 437 

400# Deny specific skills438# Deny specific skills

401Skill(deploy:*)439Skill(deploy *)

402```440```

403 441 

404Permission syntax: `Skill(name)` for exact match, `Skill(name:*)` for prefix match with any arguments.442Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments.

405 443 

406**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.444**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.

407 445 


415 453 

416* **Project skills**: Commit `.claude/skills/` to version control454* **Project skills**: Commit `.claude/skills/` to version control

417* **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins)455* **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins)

418* **Managed**: Deploy organization-wide through [managed settings](/en/iam#managed-settings)456* **Managed**: Deploy organization-wide through [managed settings](/en/permissions#managed-settings)

419 457 

420### Generate visual output458### Generate visual output

421 459 


435---473---

436name: codebase-visualizer474name: 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.475description: 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:*)476allowed-tools: Bash(python *)

439---477---

440 478 

441# Codebase Visualizer479# Codebase Visualizer


626 664 

627### Claude doesn't see all my skills665### Claude doesn't see all my skills

628 666 

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.667Skill 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 668 

631To increase the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.669To override the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.

632 670 

633## Related resources671## Related resources

634 672 


637* **[Hooks](/en/hooks)**: automate workflows around tool events675* **[Hooks](/en/hooks)**: automate workflows around tool events

638* **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context676* **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context

639* **[Interactive mode](/en/interactive-mode#built-in-commands)**: built-in commands and shortcuts677* **[Interactive mode](/en/interactive-mode#built-in-commands)**: built-in commands and shortcuts

640* **[Permissions](/en/iam)**: control tool and skill access678* **[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 +748 −167

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" data-og-width="776" width="776" data-og-height="212" height="212" data-path="images/statusline-multiline.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=2e448b44c332620e6c9c2be4ded992e5 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f796af2db9c68ab2ddbc5136840b9551 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d29c13d6164773198a0b2c47b31f6c09 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d7720e5f51310185c0c02152f6c10d8b 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=b4e008cde27990a8d5783e41e5b93246 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=40ab24813303dc2e4c09f2675f3faf6e 2500w" />

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```

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, you can run Bash scripts through [WSL (Windows Subsystem for Linux)](https://learn.microsoft.com/en-us/windows/wsl/install) or rewrite them in PowerShell.

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" data-og-width="726" width="726" data-og-height="164" height="164" data-path="images/statusline-quickstart.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=728c4bd06c8559cb46ddffffad983373 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f9d28e0f8f48f695167dd1d632a6cf4f 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=57a2803a18cafe8cf1aa05619444f20c 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=52cdd52865842f0cda24489dd5310d3b 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f8876ea1f72bf40bd0aeec483ee20164 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=6b1524305c7c71122cde65d0c3822374 2500w" />

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 

169<Accordion title="Full JSON schema">

170 Your status line command receives this JSON structure via stdin:

171 

172 ```json theme={null}

173 {

42 "cwd": "/current/working/directory",174 "cwd": "/current/working/directory",

175 "session_id": "abc123...",

176 "transcript_path": "/path/to/transcript.jsonl",

43 "model": {177 "model": {

44 "id": "claude-opus-4-1",178 "id": "claude-opus-4-6",

45 "display_name": "Opus"179 "display_name": "Opus"

46 },180 },

47 "workspace": {181 "workspace": {


63 "total_input_tokens": 15234,197 "total_input_tokens": 15234,

64 "total_output_tokens": 4521,198 "total_output_tokens": 4521,

65 "context_window_size": 200000,199 "context_window_size": 200000,

66 "used_percentage": 42.5,200 "used_percentage": 8,

67 "remaining_percentage": 57.5,201 "remaining_percentage": 92,

68 "current_usage": {202 "current_usage": {

69 "input_tokens": 8500,203 "input_tokens": 8500,

70 "output_tokens": 1200,204 "output_tokens": 1200,

71 "cache_creation_input_tokens": 5000,205 "cache_creation_input_tokens": 5000,

72 "cache_read_input_tokens": 2000206 "cache_read_input_tokens": 2000

73 }207 }

208 },

209 "exceeds_200k_tokens": false,

210 "vim": {

211 "mode": "NORMAL"

212 },

213 "agent": {

214 "name": "security-reviewer"

74 }215 }

75}216 }

76```217 ```

77 218 

78## Example Scripts219 **Fields that may be absent** (not present in JSON):

79 220 

80### Simple Status Line221 * `vim`: appears only when vim mode is enabled

222 * `agent`: appears only when running with the `--agent` flag or agent settings configured

81 223 

82```bash theme={null}224 **Fields that may be `null`**:

83#!/bin/bash

84# Read JSON input from stdin

85input=$(cat)

86 225 

87# Extract values using jq226 * `context_window.current_usage`: `null` before the first API call in a session

88MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')227 * `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 228 

91echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}"229 Handle missing fields with conditional access and null values with fallback defaults in your scripts.

92```230</Accordion>

231 

232### Context window fields

233 

234The `context_window` object provides two ways to track context usage:

235 

236* **Cumulative totals** (`total_input_tokens`, `total_output_tokens`): sum of all tokens across the entire session, useful for tracking total consumption

237* **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

238 

239The `current_usage` object contains:

240 

241* `input_tokens`: input tokens in current context

242* `output_tokens`: output tokens generated

243* `cache_creation_input_tokens`: tokens written to cache

244* `cache_read_input_tokens`: tokens read from cache

245 

246The `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`.

247 

248If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.

249 

250The `current_usage` object is `null` before the first API call in a session.

251 

252## Examples

253 

254These examples show common status line patterns. To use any example:

255 

2561. Save the script to a file like `~/.claude/statusline.sh` (or `.py`/`.js`)

2572. Make it executable: `chmod +x ~/.claude/statusline.sh`

2583. Add the path to your [settings](#manually-configure-a-status-line)

259 

260The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.

261 

262### Context window usage

263 

264Display 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:

265 

266<Frame>

267 <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" data-og-width="448" width="448" data-og-height="152" height="152" data-path="images/statusline-context-window-usage.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=a18fecd31f06b16e984b1ab3310acbc0 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=2f4b3caff156efede2ded995dbaf167f 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=8f6b8c7e7d3a999c570e96ad2ea13d5a 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d9334e6a08e6f11a253733c8592774a9 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e79490da8f62952e4d92837c408e63dc 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=6f7c9ef8e629a794969c54b24163f92d 2500w" />

268</Frame>

269 

270<CodeGroup>

271 ```bash Bash theme={null}

272 #!/bin/bash

273 # Read all of stdin into a variable

274 input=$(cat)

275 

276 # Extract fields with jq, "// 0" provides fallback for null

277 MODEL=$(echo "$input" | jq -r '.model.display_name')

278 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

279 

280 # Build progress bar: printf creates spaces, tr replaces with blocks

281 BAR_WIDTH=10

282 FILLED=$((PCT * BAR_WIDTH / 100))

283 EMPTY=$((BAR_WIDTH - FILLED))

284 BAR=""

285 [ "$FILLED" -gt 0 ] && BAR=$(printf "%${FILLED}s" | tr ' ' '▓')

286 [ "$EMPTY" -gt 0 ] && BAR="${BAR}$(printf "%${EMPTY}s" | tr ' ' '░')"

93 287 

94### Git-Aware Status Line288 echo "[$MODEL] $BAR $PCT%"

289 ```

95 290 

96```bash theme={null}291 ```python Python theme={null}

97#!/bin/bash292 #!/usr/bin/env python3

98# Read JSON input from stdin293 import json, sys

99input=$(cat)

100 294 

101# Extract values using jq295 # json.load reads and parses stdin in one step

102MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')296 data = json.load(sys.stdin)

103CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')297 model = data['model']['display_name']

298 # "or 0" handles null values

299 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

104 300 

105# Show git branch if in a git repo301 # String multiplication builds the bar

106GIT_BRANCH=""302 filled = pct * 10 // 100

107if git rev-parse --git-dir > /dev/null 2>&1; then303 bar = '▓' * filled + '░' * (10 - filled)

304 

305 print(f"[{model}] {bar} {pct}%")

306 ```

307 

308 ```javascript Node.js theme={null}

309 #!/usr/bin/env node

310 // Node.js reads stdin asynchronously with events

311 let input = '';

312 process.stdin.on('data', chunk => input += chunk);

313 process.stdin.on('end', () => {

314 const data = JSON.parse(input);

315 const model = data.model.display_name;

316 // Optional chaining (?.) safely handles null fields

317 const pct = Math.floor(data.context_window?.used_percentage || 0);

318 

319 // String.repeat() builds the bar

320 const filled = Math.floor(pct * 10 / 100);

321 const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);

322 

323 console.log(`[${model}] ${bar} ${pct}%`);

324 });

325 ```

326</CodeGroup>

327 

328### Git status with colors

329 

330Show 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.

331 

332<Frame>

333 <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" data-og-width="742" width="742" data-og-height="178" height="178" data-path="images/statusline-git-context.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=c1bced5f46afdc9aae549702591f8457 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=debe46a7a888234ec692751243bba492 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=3a069d5c8b0395908e42f0e295fd4854 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=26aff0978865756d5ea299a22e5e9afd 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d5ac1d59881e6f2032af053557dc4590 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=46febbf34b0ee646502d095433132709 2500w" />

334</Frame>

335 

336Each script checks if the current directory is a git repository, counts staged and modified files, and displays color-coded indicators:

337 

338<CodeGroup>

339 ```bash Bash theme={null}

340 #!/bin/bash

341 input=$(cat)

342 

343 MODEL=$(echo "$input" | jq -r '.model.display_name')

344 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

345 

346 GREEN='\033[32m'

347 YELLOW='\033[33m'

348 RESET='\033[0m'

349 

350 if git rev-parse --git-dir > /dev/null 2>&1; then

108 BRANCH=$(git branch --show-current 2>/dev/null)351 BRANCH=$(git branch --show-current 2>/dev/null)

109 if [ -n "$BRANCH" ]; then352 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

110 GIT_BRANCH=" | 🌿 $BRANCH"353 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

111 fi

112fi

113 354 

114echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH"355 GIT_STATUS=""

115```356 [ "$STAGED" -gt 0 ] && GIT_STATUS="${GREEN}+${STAGED}${RESET}"

357 [ "$MODIFIED" -gt 0 ] && GIT_STATUS="${GIT_STATUS}${YELLOW}~${MODIFIED}${RESET}"

116 358 

117### Python Example359 echo -e "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH $GIT_STATUS"

360 else

361 echo "[$MODEL] 📁 ${DIR##*/}"

362 fi

363 ```

118 364 

119```python theme={null}365 ```python Python theme={null}

120#!/usr/bin/env python3366 #!/usr/bin/env python3

121import json367 import json, sys, subprocess, os

122import sys

123import os

124 368 

125# Read JSON from stdin369 data = json.load(sys.stdin)

126data = json.load(sys.stdin)370 model = data['model']['display_name']

371 directory = os.path.basename(data['workspace']['current_dir'])

127 372 

128# Extract values373 GREEN, YELLOW, RESET = '\033[32m', '\033[33m', '\033[0m'

129model = data['model']['display_name']

130current_dir = os.path.basename(data['workspace']['current_dir'])

131 374 

132# Check for git branch

133git_branch = ""

134if os.path.exists('.git'):

135 try:375 try:

136 with open('.git/HEAD', 'r') as f:376 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

137 ref = f.read().strip()377 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

138 if ref.startswith('ref: refs/heads/'):378 staged_output = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

139 git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}"379 modified_output = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

380 staged = len(staged_output.split('\n')) if staged_output else 0

381 modified = len(modified_output.split('\n')) if modified_output else 0

382 

383 git_status = f"{GREEN}+{staged}{RESET}" if staged else ""

384 git_status += f"{YELLOW}~{modified}{RESET}" if modified else ""

385 

386 print(f"[{model}] 📁 {directory} | 🌿 {branch} {git_status}")

140 except:387 except:

141 pass388 print(f"[{model}] 📁 {directory}")

389 ```

142 390 

143print(f"[{model}] 📁 {current_dir}{git_branch}")391 ```javascript Node.js theme={null}

144```392 #!/usr/bin/env node

393 const { execSync } = require('child_process');

394 const path = require('path');

395 

396 let input = '';

397 process.stdin.on('data', chunk => input += chunk);

398 process.stdin.on('end', () => {

399 const data = JSON.parse(input);

400 const model = data.model.display_name;

401 const dir = path.basename(data.workspace.current_dir);

145 402 

146### Node.js Example403 const GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RESET = '\x1b[0m';

147 404 

148```javascript theme={null}405 try {

149#!/usr/bin/env node406 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

407 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

408 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

409 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

150 410 

151const fs = require('fs');411 let gitStatus = staged ? `${GREEN}+${staged}${RESET}` : '';

152const path = require('path');412 gitStatus += modified ? `${YELLOW}~${modified}${RESET}` : '';

153 413 

154// Read JSON from stdin414 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} ${gitStatus}`);

155let input = '';415 } catch {

156process.stdin.on('data', chunk => input += chunk);416 console.log(`[${model}] 📁 ${dir}`);

157process.stdin.on('end', () => {417 }

418 });

419 ```

420</CodeGroup>

421 

422### Cost and duration tracking

423 

424Track 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.

425 

426Each script formats cost as currency and converts milliseconds to minutes and seconds:

427 

428<Frame>

429 <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" data-og-width="588" width="588" data-og-height="180" height="180" data-path="images/statusline-cost-tracking.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=b1d35fa8acd792f559b6b1662ed10204 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=a3ed4330c3645fc28b87a6cab55be0b7 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=386ee2ed68a7d520eba20eac54f7fe52 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=479c2515e53f46d5d1da3b87a6dd993a 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=1340c7589a4cb89ec071234aba3571d1 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=69056cf4fe3271770cac4dc1704bcd0a 2500w" />

430</Frame>

431 

432<CodeGroup>

433 ```bash Bash theme={null}

434 #!/bin/bash

435 input=$(cat)

436 

437 MODEL=$(echo "$input" | jq -r '.model.display_name')

438 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

439 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

440 

441 COST_FMT=$(printf '$%.2f' "$COST")

442 DURATION_SEC=$((DURATION_MS / 1000))

443 MINS=$((DURATION_SEC / 60))

444 SECS=$((DURATION_SEC % 60))

445 

446 echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"

447 ```

448 

449 ```python Python theme={null}

450 #!/usr/bin/env python3

451 import json, sys

452 

453 data = json.load(sys.stdin)

454 model = data['model']['display_name']

455 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

456 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

457 

458 duration_sec = duration_ms // 1000

459 mins, secs = duration_sec // 60, duration_sec % 60

460 

461 print(f"[{model}] 💰 ${cost:.2f} | ⏱️ {mins}m {secs}s")

462 ```

463 

464 ```javascript Node.js theme={null}

465 #!/usr/bin/env node

466 let input = '';

467 process.stdin.on('data', chunk => input += chunk);

468 process.stdin.on('end', () => {

158 const data = JSON.parse(input);469 const data = JSON.parse(input);

470 const model = data.model.display_name;

471 const cost = data.cost?.total_cost_usd || 0;

472 const durationMs = data.cost?.total_duration_ms || 0;

473 

474 const durationSec = Math.floor(durationMs / 1000);

475 const mins = Math.floor(durationSec / 60);

476 const secs = durationSec % 60;

477 

478 console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`);

479 });

480 ```

481</CodeGroup>

482 

483### Display multiple lines

484 

485Your script can output multiple lines to create a richer display. Each `echo` statement produces a separate row in the status area.

486 

487<Frame>

488 <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" data-og-width="776" width="776" data-og-height="212" height="212" data-path="images/statusline-multiline.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=2e448b44c332620e6c9c2be4ded992e5 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f796af2db9c68ab2ddbc5136840b9551 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d29c13d6164773198a0b2c47b31f6c09 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d7720e5f51310185c0c02152f6c10d8b 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=b4e008cde27990a8d5783e41e5b93246 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=40ab24813303dc2e4c09f2675f3faf6e 2500w" />

489</Frame>

490 

491This 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:

492 

493<CodeGroup>

494 ```bash Bash theme={null}

495 #!/bin/bash

496 input=$(cat)

497 

498 MODEL=$(echo "$input" | jq -r '.model.display_name')

499 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

500 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

501 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

502 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

503 

504 CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

505 

506 # Pick bar color based on context usage

507 if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"

508 elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"

509 else BAR_COLOR="$GREEN"; fi

510 

511 FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))

512 BAR=$(printf "%${FILLED}s" | tr ' ' '█')$(printf "%${EMPTY}s" | tr ' ' '░')

159 513 

160 // Extract values514 MINS=$((DURATION_MS / 60000)); SECS=$(((DURATION_MS % 60000) / 1000))

515 

516 BRANCH=""

517 git rev-parse --git-dir > /dev/null 2>&1 && BRANCH=" | 🌿 $(git branch --show-current 2>/dev/null)"

518 

519 echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"

520 COST_FMT=$(printf '$%.2f' "$COST")

521 echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"

522 ```

523 

524 ```python Python theme={null}

525 #!/usr/bin/env python3

526 import json, sys, subprocess, os

527 

528 data = json.load(sys.stdin)

529 model = data['model']['display_name']

530 directory = os.path.basename(data['workspace']['current_dir'])

531 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

532 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

533 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

534 

535 CYAN, GREEN, YELLOW, RED, RESET = '\033[36m', '\033[32m', '\033[33m', '\033[31m', '\033[0m'

536 

537 bar_color = RED if pct >= 90 else YELLOW if pct >= 70 else GREEN

538 filled = pct // 10

539 bar = '█' * filled + '░' * (10 - filled)

540 

541 mins, secs = duration_ms // 60000, (duration_ms % 60000) // 1000

542 

543 try:

544 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True, stderr=subprocess.DEVNULL).strip()

545 branch = f" | 🌿 {branch}" if branch else ""

546 except:

547 branch = ""

548 

549 print(f"{CYAN}[{model}]{RESET} 📁 {directory}{branch}")

550 print(f"{bar_color}{bar}{RESET} {pct}% | {YELLOW}${cost:.2f}{RESET} | ⏱️ {mins}m {secs}s")

551 ```

552 

553 ```javascript Node.js theme={null}

554 #!/usr/bin/env node

555 const { execSync } = require('child_process');

556 const path = require('path');

557 

558 let input = '';

559 process.stdin.on('data', chunk => input += chunk);

560 process.stdin.on('end', () => {

561 const data = JSON.parse(input);

161 const model = data.model.display_name;562 const model = data.model.display_name;

162 const currentDir = path.basename(data.workspace.current_dir);563 const dir = path.basename(data.workspace.current_dir);

564 const cost = data.cost?.total_cost_usd || 0;

565 const pct = Math.floor(data.context_window?.used_percentage || 0);

566 const durationMs = data.cost?.total_duration_ms || 0;

567 

568 const CYAN = '\x1b[36m', GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RED = '\x1b[31m', RESET = '\x1b[0m';

569 

570 const barColor = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;

571 const filled = Math.floor(pct / 10);

572 const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);

163 573 

164 // Check for git branch574 const mins = Math.floor(durationMs / 60000);

165 let gitBranch = '';575 const secs = Math.floor((durationMs % 60000) / 1000);

576 

577 let branch = '';

166 try {578 try {

167 const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim();579 branch = execSync('git branch --show-current', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

168 if (headContent.startsWith('ref: refs/heads/')) {580 branch = branch ? ` | 🌿 ${branch}` : '';

169 gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`;581 } catch {}

170 }582 

171 } catch (e) {583 console.log(`${CYAN}[${model}]${RESET} 📁 ${dir}${branch}`);

172 // Not a git repo or can't read HEAD584 console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`);

585 });

586 ```

587</CodeGroup>

588 

589### Clickable links

590 

591This 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.

592 

593<Frame>

594 <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" data-og-width="726" width="726" data-og-height="198" height="198" data-path="images/statusline-links.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=9386f78056f7be99599bcefe9e838180 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d748012a0866c37dddc6babd4b7a88c4 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=bade8fbfcde957c1033c376c58b89131 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=9f7e0c729ea093c3b39682619fd3f201 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=ccec17e90a89d82381888a4a9a8fa40e 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=4d2e34a4d2f24e174cae1256c84f9a52 2500w" />

595</Frame>

596 

597Each 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:

598 

599<CodeGroup>

600 ```bash Bash theme={null}

601 #!/bin/bash

602 input=$(cat)

603 

604 MODEL=$(echo "$input" | jq -r '.model.display_name')

605 

606 # Convert git SSH URL to HTTPS

607 REMOTE=$(git remote get-url origin 2>/dev/null | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//')

608 

609 if [ -n "$REMOTE" ]; then

610 REPO_NAME=$(basename "$REMOTE")

611 # OSC 8 format: \e]8;;URL\a then TEXT then \e]8;;\a

612 # printf %b interprets escape sequences reliably across shells

613 printf '%b' "[$MODEL] 🔗 \e]8;;${REMOTE}\a${REPO_NAME}\e]8;;\a\n"

614 else

615 echo "[$MODEL]"

616 fi

617 ```

618 

619 ```python Python theme={null}

620 #!/usr/bin/env python3

621 import json, sys, subprocess, re, os

622 

623 data = json.load(sys.stdin)

624 model = data['model']['display_name']

625 

626 # Get git remote URL

627 try:

628 remote = subprocess.check_output(

629 ['git', 'remote', 'get-url', 'origin'],

630 stderr=subprocess.DEVNULL, text=True

631 ).strip()

632 # Convert SSH to HTTPS format

633 remote = re.sub(r'^git@github\.com:', 'https://github.com/', remote)

634 remote = re.sub(r'\.git$', '', remote)

635 repo_name = os.path.basename(remote)

636 # OSC 8 escape sequences

637 link = f"\033]8;;{remote}\a{repo_name}\033]8;;\a"

638 print(f"[{model}] 🔗 {link}")

639 except:

640 print(f"[{model}]")

641 ```

642 

643 ```javascript Node.js theme={null}

644 #!/usr/bin/env node

645 const { execSync } = require('child_process');

646 const path = require('path');

647 

648 let input = '';

649 process.stdin.on('data', chunk => input += chunk);

650 process.stdin.on('end', () => {

651 const data = JSON.parse(input);

652 const model = data.model.display_name;

653 

654 try {

655 let remote = execSync('git remote get-url origin', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

656 // Convert SSH to HTTPS format

657 remote = remote.replace(/^git@github\.com:/, 'https://github.com/').replace(/\.git$/, '');

658 const repoName = path.basename(remote);

659 // OSC 8 escape sequences

660 const link = `\x1b]8;;${remote}\x07${repoName}\x1b]8;;\x07`;

661 console.log(`[${model}] 🔗 ${link}`);

662 } catch {

663 console.log(`[${model}]`);

173 }664 }

665 });

666 ```

667</CodeGroup>

174 668 

175 console.log(`[${model}] 📁 ${currentDir}${gitBranch}`);669### Cache expensive operations

176});

177```

178 670 

179### Helper Function Approach671Your 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.

180 

181For more complex bash scripts, you can create helper functions:

182 

183```bash theme={null}

184#!/bin/bash

185# Read JSON input once

186input=$(cat)

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 672 

207### Context Window Usage673Use 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.

208 674 

209Display the percentage of context window consumed. The `context_window` object contains:675Each script checks if the cache file is missing or older than 5 seconds before running git commands:

210 676 

211* `total_input_tokens` / `total_output_tokens`: Cumulative totals across the entire session677<CodeGroup>

212* `used_percentage`: Pre-calculated percentage of context window used (0-100)678 ```bash Bash theme={null}

213* `remaining_percentage`: Pre-calculated percentage of context window remaining (0-100)679 #!/bin/bash

214* `current_usage`: Current context window usage from the last API call (may be `null` if no messages yet)680 input=$(cat)

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 681 

220You can use the pre-calculated `used_percentage` and `remaining_percentage` fields directly, or calculate from `current_usage` for more control.682 MODEL=$(echo "$input" | jq -r '.model.display_name')

683 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

221 684 

222**Simple approach using pre-calculated percentages:**685 CACHE_FILE="/tmp/statusline-git-cache"

686 CACHE_MAX_AGE=5 # seconds

223 687 

224```bash theme={null}688 cache_is_stale() {

225#!/bin/bash689 [ ! -f "$CACHE_FILE" ] || \

226input=$(cat)690 # stat -f %m is macOS, stat -c %Y is Linux

691 [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0))) -gt $CACHE_MAX_AGE ]

692 }

693 

694 if cache_is_stale; then

695 if git rev-parse --git-dir > /dev/null 2>&1; then

696 BRANCH=$(git branch --show-current 2>/dev/null)

697 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

698 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

699 echo "$BRANCH|$STAGED|$MODIFIED" > "$CACHE_FILE"

700 else

701 echo "||" > "$CACHE_FILE"

702 fi

703 fi

227 704 

228MODEL=$(echo "$input" | jq -r '.model.display_name')705 IFS='|' read -r BRANCH STAGED MODIFIED < "$CACHE_FILE"

229PERCENT_USED=$(echo "$input" | jq -r '.context_window.used_percentage // 0')

230 706 

231echo "[$MODEL] Context: ${PERCENT_USED}%"707 if [ -n "$BRANCH" ]; then

232```708 echo "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH +$STAGED ~$MODIFIED"

709 else

710 echo "[$MODEL] 📁 ${DIR##*/}"

711 fi

712 ```

233 713 

234**Advanced approach with manual calculation:**714 ```python Python theme={null}

715 #!/usr/bin/env python3

716 import json, sys, subprocess, os, time

235 717 

236```bash theme={null}718 data = json.load(sys.stdin)

237#!/bin/bash719 model = data['model']['display_name']

238input=$(cat)720 directory = os.path.basename(data['workspace']['current_dir'])

239 721 

240MODEL=$(echo "$input" | jq -r '.model.display_name')722 CACHE_FILE = "/tmp/statusline-git-cache"

241CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size')723 CACHE_MAX_AGE = 5 # seconds

242USAGE=$(echo "$input" | jq '.context_window.current_usage')

243 724 

244if [ "$USAGE" != "null" ]; then725 def cache_is_stale():

245 # Calculate current context from current_usage fields726 if not os.path.exists(CACHE_FILE):

246 CURRENT_TOKENS=$(echo "$USAGE" | jq '.input_tokens + .cache_creation_input_tokens + .cache_read_input_tokens')727 return True

247 PERCENT_USED=$((CURRENT_TOKENS * 100 / CONTEXT_SIZE))728 return time.time() - os.path.getmtime(CACHE_FILE) > CACHE_MAX_AGE

248 echo "[$MODEL] Context: ${PERCENT_USED}%"729 

249else730 if cache_is_stale():

250 echo "[$MODEL] Context: 0%"731 try:

251fi732 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

252```733 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

734 staged = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

735 modified = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

736 staged_count = len(staged.split('\n')) if staged else 0

737 modified_count = len(modified.split('\n')) if modified else 0

738 with open(CACHE_FILE, 'w') as f:

739 f.write(f"{branch}|{staged_count}|{modified_count}")

740 except:

741 with open(CACHE_FILE, 'w') as f:

742 f.write("||")

743 

744 with open(CACHE_FILE) as f:

745 branch, staged, modified = f.read().strip().split('|')

746 

747 if branch:

748 print(f"[{model}] 📁 {directory} | 🌿 {branch} +{staged} ~{modified}")

749 else:

750 print(f"[{model}] 📁 {directory}")

751 ```

752 

753 ```javascript Node.js theme={null}

754 #!/usr/bin/env node

755 const { execSync } = require('child_process');

756 const fs = require('fs');

757 const path = require('path');

758 

759 let input = '';

760 process.stdin.on('data', chunk => input += chunk);

761 process.stdin.on('end', () => {

762 const data = JSON.parse(input);

763 const model = data.model.display_name;

764 const dir = path.basename(data.workspace.current_dir);

765 

766 const CACHE_FILE = '/tmp/statusline-git-cache';

767 const CACHE_MAX_AGE = 5; // seconds

768 

769 const cacheIsStale = () => {

770 if (!fs.existsSync(CACHE_FILE)) return true;

771 return (Date.now() / 1000) - fs.statSync(CACHE_FILE).mtimeMs / 1000 > CACHE_MAX_AGE;

772 };

773 

774 if (cacheIsStale()) {

775 try {

776 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

777 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

778 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

779 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

780 fs.writeFileSync(CACHE_FILE, `${branch}|${staged}|${modified}`);

781 } catch {

782 fs.writeFileSync(CACHE_FILE, '||');

783 }

784 }

785 

786 const [branch, staged, modified] = fs.readFileSync(CACHE_FILE, 'utf8').trim().split('|');

787 

788 if (branch) {

789 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} +${staged} ~${modified}`);

790 } else {

791 console.log(`[${model}] 📁 ${dir}`);

792 }

793 });

794 ```

795</CodeGroup>

253 796 

254## Tips797## Tips

255 798 

256* Keep your status line concise - it should fit on one line799* **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 scannable800* **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)801* **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`802 

260* Consider caching expensive operations (like git status) if needed803Community 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 804 

262## Troubleshooting805## Troubleshooting

263 806 

264* If your status line doesn't appear, check that your script is executable (`chmod +x`)807**Status line not appearing**

265* Ensure your script outputs to stdout (not stderr)808 

809* Verify your script is executable: `chmod +x ~/.claude/statusline.sh`

810* Check that your script outputs to stdout, not stderr

811* Run your script manually to verify it produces output

812* 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.

813 

814**Status line shows `--` or empty values**

815 

816* Fields may be `null` before the first API response completes

817* Handle null values in your script with fallbacks such as `// 0` in jq

818* Restart Claude Code if values remain empty after multiple messages

819 

820**Context percentage shows unexpected values**

821 

822* Use `used_percentage` for accurate context state rather than cumulative totals

823* The `total_input_tokens` and `total_output_tokens` are cumulative across the session and may exceed the context window size

824* Context percentage may differ from `/context` output due to when each is calculated

825 

826**OSC 8 links not clickable**

827 

828* Verify your terminal supports OSC 8 hyperlinks (iTerm2, Kitty, WezTerm)

829* Terminal.app does not support clickable links

830* SSH and tmux sessions may strip OSC sequences depending on configuration

831* If escape sequences appear as literal text like `\e]8;;`, use `printf '%b'` instead of `echo -e` for more reliable escape handling

832 

833**Display glitches with escape sequences**

834 

835* Complex escape sequences (ANSI colors, OSC 8 links) can occasionally cause garbled output if they overlap with other UI updates

836* If you see corrupted text, try simplifying your script to plain text output

837* Multi-line status lines with escape codes are more prone to rendering issues than single-line plain text

838 

839**Script errors or hangs**

266 840 

841* Scripts that exit with non-zero codes or produce no output cause the status line to go blank

842* Slow scripts block the status line from updating until they complete. Keep scripts fast to avoid stale output.

843* If a new update triggers while a slow script is running, the in-flight script is cancelled

844* Test your script independently with mock input before configuring it

267 845 

846**Notifications share the status line row**

268 847 

269> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt848* System notifications like MCP server errors, auto-updates, and token warnings display on the right side of the same row as your status line

849* Enabling verbose mode adds a token counter to this area

850* On narrow terminals, these notifications may truncate your status line output

sub-agents.md +94 −17

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


166}'174}'

167```175```

168 176 

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.177The `--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. See the [CLI reference](/en/cli-reference#agents-flag-format) for the full JSON format.

170 178 

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.179**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 180 


197The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.205The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.

198 206 

199| Field | Required | Description |207| Field | Required | Description |

200| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |208| :---------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

201| `name` | Yes | Unique identifier using lowercase letters and hyphens |209| `name` | Yes | Unique identifier using lowercase letters and hyphens |

202| `description` | Yes | When Claude should delegate to this subagent |210| `description` | Yes | When Claude should delegate to this subagent |

203| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |211| `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 |212| `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` |213| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `inherit` |

206| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |214| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |

215| `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 |216| `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 |

217| `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 |218| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |

219| `memory` | No | [Persistent memory scope](#enable-persistent-memory): `user`, `project`, or `local`. Enables cross-session learning |

220| `background` | No | Set to `true` to always run this subagent as a [background task](#run-subagents-in-foreground-or-background). Default: `false` |

221| `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 222 

210### Choose a model223### Choose a model

211 224 


234---247---

235```248```

236 249 

250#### Restrict which subagents can be spawned

251 

252When an agent runs as the main thread with `claude --agent`, it can spawn subagents using the Task tool. To restrict which subagent types it can spawn, use `Task(agent_type)` syntax in the `tools` field:

253 

254```yaml theme={null}

255---

256name: coordinator

257description: Coordinates work across specialized agents

258tools: Task(worker, researcher), Read, Bash

259---

260```

261 

262This 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.

263 

264To allow spawning any subagent without restrictions, use `Task` without parentheses:

265 

266```yaml theme={null}

267tools: Task, Read, Bash

268```

269 

270If `Task` 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 `Task(agent_type)` has no effect in subagent definitions.

271 

237#### Permission modes272#### Permission modes

238 273 

239The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.274The `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.309 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>310</Note>

276 311 

312#### Enable persistent memory

313 

314The `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.

315 

316```yaml theme={null}

317---

318name: code-reviewer

319description: Reviews code for quality and best practices

320memory: user

321---

322 

323You are a code reviewer. As you review code, update your agent memory with

324patterns, conventions, and recurring issues you discover.

325```

326 

327Choose a scope based on how broadly the memory should apply:

328 

329| Scope | Location | Use when |

330| :-------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------ |

331| `user` | `~/.claude/agent-memory/<name-of-agent>/` | the subagent should remember learnings across all projects |

332| `project` | `.claude/agent-memory/<name-of-agent>/` | the subagent's knowledge is project-specific and shareable via version control |

333| `local` | `.claude/agent-memory-local/<name-of-agent>/` | the subagent's knowledge is project-specific but should not be checked into version control |

334 

335When memory is enabled:

336 

337* The subagent's system prompt includes instructions for reading and writing to the memory directory.

338* 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.

339* Read, Write, and Edit tools are automatically enabled so the subagent can manage its memory files.

340 

341##### Persistent memory tips

342 

343* `user` is the recommended default scope. Use `project` or `local` when the subagent's knowledge is only relevant to a specific codebase.

344* Ask the subagent to consult its memory before starting work: "Review this PR, and check your memory for patterns you've seen before."

345* 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.

346* Include memory instructions directly in the subagent's markdown file so it proactively maintains its own knowledge base:

347 

348 ```markdown theme={null}

349 Update your agent memory as you discover codepaths, patterns, library

350 locations, and key architectural decisions. This builds up institutional

351 knowledge across conversations. Write concise notes about what you found

352 and where.

353 ```

354 

277#### Conditional rules with hooks355#### Conditional rules with hooks

278 356 

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.357For 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---372---

295```373```

296 374 

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:375Claude 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 376 

299```bash theme={null}377```bash theme={null}

300#!/bin/bash378#!/bin/bash


312exit 0390exit 0

313```391```

314 392 

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.393See [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 394 

317#### Disable specific subagents395#### Disable specific subagents

318 396 


332claude --disallowedTools "Task(Explore)"410claude --disallowedTools "Task(Explore)"

333```411```

334 412 

335See [IAM documentation](/en/iam#tool-specific-permission-rules) for more details on permission rules.413See [Permissions documentation](/en/permissions#tool-specific-permission-rules) for more details on permission rules.

336 414 

337### Define hooks for subagents415### Define hooks for subagents

338 416 


345 423 

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.424Define 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 425 

426All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are:

427 

348| Event | Matcher input | When it fires |428| Event | Matcher input | When it fires |

349| :------------ | :------------ | :------------------------------ |429| :------------ | :------------ | :------------------------------------------------------------------ |

350| `PreToolUse` | Tool name | Before the subagent uses a tool |430| `PreToolUse` | Tool name | Before the subagent uses a tool |

351| `PostToolUse` | Tool name | After the subagent uses a tool |431| `PostToolUse` | Tool name | After the subagent uses a tool |

352| `Stop` | (none) | When the subagent finishes |432| `Stop` | (none) | When the subagent finishes (converted to `SubagentStop` at runtime) |

353 433 

354This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:434This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:

355 435 


375 455 

376#### Project-level hooks for subagent events456#### Project-level hooks for subagent events

377 457 

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.458Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session.

379 459 

380| Event | Matcher input | When it fires |460| Event | Matcher input | When it fires |

381| :-------------- | :-------------- | :------------------------------- |461| :-------------- | :-------------- | :------------------------------- |

382| `SubagentStart` | Agent type name | When a subagent begins execution |462| `SubagentStart` | Agent type name | When a subagent begins execution |

383| `SubagentStop` | Agent type name | When a subagent completes |463| `SubagentStop` | Agent type name | When a subagent completes |

384 464 

385This example runs setup and cleanup scripts only when the `db-agent` subagent starts and stops:465Both 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 466 

387```json theme={null}467```json theme={null}

388{468{


397 ],477 ],

398 "SubagentStop": [478 "SubagentStop": [

399 {479 {

400 "matcher": "db-agent",

401 "hooks": [480 "hooks": [

402 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }481 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }

403 ]482 ]


427Subagents can run in the foreground (blocking) or background (concurrent):506Subagents can run in the foreground (blocking) or background (concurrent):

428 507 

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.508* **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.

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.509* **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. MCP tools are not available in background subagents.

431 510 

432If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.511If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.

433 512 


462 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.541 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.

463</Warning>542</Warning>

464 543 

544For tasks that need sustained parallelism or exceed your context window, [agent teams](/en/agent-teams) give each worker its own independent context.

545 

465#### Chain subagents546#### Chain subagents

466 547 

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.548For 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.


687You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.768You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.

688```769```

689 770 

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.771Claude 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 772 

692Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:773Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:

693 774 


720chmod +x ./scripts/validate-readonly-query.sh801chmod +x ./scripts/validate-readonly-query.sh

721```802```

722 803 

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.804The 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 805 

725## Next steps806## Next steps

726 807 


729* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects810* [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 automation811* [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 data812* [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

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.


78* Line operations: `J` (join lines)82* Line operations: `J` (join lines)

79 83 

80See [Interactive mode](/en/interactive-mode#vim-editor-mode) for the complete reference.84See [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.


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)


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

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.


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.57 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.

54</Warning>58</Warning>

55 59 

60### WSL2 sandbox setup

61 

62[Sandboxing](/en/sandboxing) is supported on WSL2 but requires installing additional packages. If you see an error like "Sandbox requires socat and bubblewrap" when running `/sandbox`, install the dependencies:

63 

64<Tabs>

65 <Tab title="Ubuntu/Debian">

66 ```bash theme={null}

67 sudo apt-get install bubblewrap socat

68 ```

69 </Tab>

70 

71 <Tab title="Fedora">

72 ```bash theme={null}

73 sudo dnf install bubblewrap socat

74 ```

75 </Tab>

76</Tabs>

77 

78WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing.

79 

56### Linux and Mac installation issues: permission or command not found errors80### Linux and Mac installation issues: permission or command not found errors

57 81 

58When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.82When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.


143### Repeated permission prompts167### Repeated permission prompts

144 168 

145If you find yourself repeatedly approving the same commands, you can allow specific tools169If you find yourself repeatedly approving the same commands, you can allow specific tools

146to run without approval using the `/permissions` command. See [Permissions docs](/en/iam#configuring-permissions).170to run without approval using the `/permissions` command. See [Permissions docs](/en/permissions#manage-permissions).

147 171 

148### Authentication issues172### Authentication issues

149 173 


173| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |197| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |

174| `.claude/settings.json` | Project settings (checked into source control) |198| `.claude/settings.json` | Project settings (checked into source control) |

175| `.claude/settings.local.json` | Local project settings (not committed) |199| `.claude/settings.local.json` | Local project settings (not committed) |

176| `~/.claude.json` | Global state (theme, OAuth, MCP servers, allowed tools) |200| `~/.claude.json` | Global state (theme, OAuth, MCP servers) |

177| `.mcp.json` | Project MCP servers (checked into source control) |201| `.mcp.json` | Project MCP servers (checked into source control) |

178| `managed-settings.json` | [Managed settings](/en/settings#settings-files) |202| `managed-settings.json` | [Managed settings](/en/settings#settings-files) |

179| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |203| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |


203```227```

204 228 

205<Warning>229<Warning>

206 This will remove all your settings, allowed tools, MCP server configurations, and session history.230 This will remove all your settings, MCP server configurations, and session history.

207</Warning>231</Warning>

208 232 

209## Performance and stability233## Performance and stability


359 383 

3601. **Ask Claude to add language tags**: Request "Add appropriate language tags to all code blocks in this markdown file."3841. **Ask Claude to add language tags**: Request "Add appropriate language tags to all code blocks in this markdown file."

361 385 

3622. **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.3862. **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.

363 387 

3643. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.3883. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.

365 389 


398 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)422 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)

399 * Plugin and agent loading errors423 * Plugin and agent loading errors

4004. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation4244. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation

401 

402 

403 

404> 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 +103 −19

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.


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"49 * **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.50 * **Status Bar**: Click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open.

47 51 

52 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.

53 

48 You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.54 You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.

49 </Step>55 </Step>

50 56 


68For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows).74For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows).

69 75 

70<Tip>76<Tip>

71 The extension includes two built-in tutorials:77 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>78</Tip>

76 79 

77## Use the prompt box80## Use the prompt box


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.85* **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.86* **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.87* **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.88* **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 89 

87### Reference files and folders90### Reference files and folders

88 91 


93> What's in @src/components/ (include a trailing slash for folders)96> What's in @src/components/ (include a trailing slash for folders)

94```97```

95 98 

99For 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.

100 

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.101When 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 102 

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.103You 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.


101 106 

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).107Click 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).

103 108 

109### Resume remote sessions from Claude.ai

110 

111If you use [Claude Code on the web](/en/claude-code-on-the-web), you can resume those remote sessions directly in VS Code. This requires signing in with **Claude.ai Subscription**, not Anthropic Console.

112 

113<Steps>

114 <Step title="Open Past Conversations">

115 Click the **Past Conversations** dropdown at the top of the Claude Code panel.

116 </Step>

117 

118 <Step title="Select the Remote tab">

119 The dialog shows two tabs: Local and Remote. Click **Remote** to see sessions from claude.ai.

120 </Step>

121 

122 <Step title="Select a session to resume">

123 Browse or search your remote sessions. Click any session to download it and continue the conversation locally.

124 </Step>

125</Steps>

126 

127<Note>

128 Only web sessions started with a GitHub repository appear in the Remote tab. Resuming loads the conversation history locally; changes are not synced back to claude.ai.

129</Note>

130 

104## Customize your workflow131## Customize your workflow

105 132 

106Once you're up and running, you can reposition the Claude panel, run multiple sessions, or switch to terminal mode.133Once you're up and running, you can reposition the Claude panel, run multiple sessions, or switch to terminal mode.


129 156 

130You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), go to Extensions → Claude Code, and check **Use Terminal**.157You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), go to Extensions → Claude Code, and check **Use Terminal**.

131 158 

159## Manage plugins

160 

161The VS Code extension includes a graphical interface for installing and managing [plugins](/en/plugins). Type `/plugins` in the prompt box to open the **Manage plugins** interface.

162 

163### Install plugins

164 

165The plugin dialog shows two tabs: **Plugins** and **Marketplaces**.

166 

167In the Plugins tab:

168 

169* **Installed plugins** appear at the top with toggle switches to enable or disable them

170* **Available plugins** from your configured marketplaces appear below

171* Search to filter plugins by name or description

172* Click **Install** on any available plugin

173 

174When you install a plugin, choose the installation scope:

175 

176* **Install for you**: Available in all your projects (user scope)

177* **Install for this project**: Shared with project collaborators (project scope)

178* **Install locally**: Only for you, only in this repository (local scope)

179 

180### Manage marketplaces

181 

182Switch to the **Marketplaces** tab to add or remove plugin sources:

183 

184* Enter a GitHub repo, URL, or local path to add a new marketplace

185* Click the refresh icon to update a marketplace's plugin list

186* Click the trash icon to remove a marketplace

187 

188After making changes, a banner prompts you to restart Claude Code to apply the updates.

189 

190<Note>

191 Plugin management in VS Code uses the same CLI commands under the hood. Plugins and marketplaces you configure in the extension are also available in the CLI, and vice versa.

192</Note>

193 

194For more about the plugin system, see [Plugins](/en/plugins) and [Plugin marketplaces](/en/plugin-marketplaces).

195 

196## Automate browser tasks with Chrome

197 

198Connect 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.

199 

200Type `@browser` in the prompt box followed by what you want Claude to do:

201 

202```text theme={null}

203@browser go to localhost:3000 and check the console for errors

204```

205 

206You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content.

207 

208Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into.

209 

210For setup instructions, the full list of capabilities, and troubleshooting, see [Use Claude Code with Chrome](/en/chrome).

211 

132## VS Code commands and shortcuts212## VS Code commands and shortcuts

133 213 

134Open 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.214Open 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.


158* **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.238* **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.

159* **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.239* **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.

160 240 

241<Tip>

242 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.

243</Tip>

244 

161### Extension settings245### Extension settings

162 246 

163| Setting | Default | Description |247| Setting | Default | Description |


184| ------------------- | --------------------------------------------- | ---------------------------------------- |268| ------------------- | --------------------------------------------- | ---------------------------------------- |

185| Commands and skills | [All](/en/interactive-mode#built-in-commands) | Subset (type `/` to see available) |269| Commands and skills | [All](/en/interactive-mode#built-in-commands) | Subset (type `/` to see available) |

186| MCP server config | Yes | No (configure via CLI, use in extension) |270| MCP server config | Yes | No (configure via CLI, use in extension) |

187| Checkpoints | Yes | Coming soon |271| Checkpoints | Yes | Yes |

188| `!` bash shortcut | Yes | No |272| `!` bash shortcut | Yes | No |

189| Tab completion | Yes | No |273| Tab completion | Yes | No |

190 274 

275### Rewind with checkpoints

276 

277The 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:

278 

279* **Fork conversation from here**: start a new conversation branch from this message while keeping all code changes intact

280* **Rewind code to here**: revert file changes back to this point in the conversation while keeping the full conversation history

281* **Fork conversation and rewind code**: start a new conversation branch and revert file changes to this point

282 

283For full details on how checkpoints work and their limitations, see [Checkpointing](/en/checkpointing).

284 

191### Run CLI in VS Code285### Run CLI in VS Code

192 286 

193To 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.287To 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.


236 330 

237### Use git worktrees for parallel tasks331### Use git worktrees for parallel tasks

238 332 

239Git worktrees allow multiple Claude Code sessions to work on separate branches simultaneously, each with isolated files:333Use the `--worktree` flag to start Claude in an isolated worktree with its own files and branch:

240 334 

241```bash theme={null}335```bash theme={null}

242# Create a worktree for a new feature336claude -w feature-auth

243git worktree add ../project-feature-a -b feature-a

244 

245# Run Claude Code in each worktree

246cd ../project-feature-a && claude

247```337```

248 338 

249Each worktree maintains independent file state while sharing git history. This prevents Claude instances from interfering with each other when working on different tasks.339Each 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).

250 

251For detailed git workflows including PR reviews and branch management, see [Common workflows](/en/common-workflows#create-pull-requests).

252 340 

253## Use third-party providers341## Use third-party providers

254 342 


335* [Explore common workflows](/en/common-workflows) to get the most out of Claude Code423* [Explore common workflows](/en/common-workflows) to get the most out of Claude Code

336* [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.424* [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.

337* [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.425* [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.

338 

339 

340 

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