SpyBara
Go Premium Account
2026
15 Apr 2026, 04:00
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
9 May 2026, 04:01
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
Fri 1 00:20 Fri 1 04:22 Fri 1 18:19 Sat 2 00:19 Sat 2 04:05 Sat 2 18:14 Mon 4 04:18 Mon 4 06:55 Mon 4 15:35 Mon 4 18:58 Mon 4 22:01 Mon 4 22:58 Tue 5 00:02 Tue 5 14:57 Tue 5 15:59 Tue 5 17:00 Tue 5 21:00 Tue 5 23:00 Thu 7 17:08 Thu 7 21:57 Thu 7 22:59 Fri 8 00:02 Fri 8 01:02 Fri 8 02:03 Fri 8 03:01 Fri 8 06:02 Fri 8 07:02 Fri 8 16:57 Fri 8 18:00 Fri 8 19:00 Fri 8 22:00 Sat 9 03:01 Sat 9 04:01 Sat 9 04:57 Sun 10 04:02 Sun 10 17:00 Sun 10 23:03 Mon 11 15:00 Mon 11 18:00 Mon 11 18:59 Mon 11 20:02 Mon 11 21:57 Mon 11 23:00 Tue 12 00:01 Tue 12 01:59 Tue 12 14:59 Tue 12 16:02

admin-setup.md +132 −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# Set up Claude Code for your organization

6 

7> A decision map for administrators deploying Claude Code, covering API providers, managed settings, policy enforcement, usage monitoring, and data handling.

8 

9Claude Code enforces organization policy through managed settings that take precedence over local developer configuration. You deliver those settings from the Claude admin console, your mobile device management (MDM) system, or a file on disk. The settings control which tools, commands, servers, and network destinations Claude can reach.

10 

11This page walks through the deployment decisions in order. Each row links to the section below and to the reference page for that area.

12 

13<Note>

14 SSO, SCIM provisioning, and seat assignment are configured at the Claude account level. See the [Claude Enterprise Administrator Guide](https://claude.com/resources/tutorials/claude-enterprise-administrator-guide) and [seat assignment](https://support.claude.com/en/articles/11845131-use-claude-code-with-your-team-or-enterprise-plan) for those steps.

15</Note>

16 

17| Decision | What you're choosing | Reference |

18| :---------------------------------------------------------------------- | :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |

19| [Choose your API provider](#choose-your-api-provider) | Where Claude Code authenticates and how it's billed | [Authentication](/en/authentication), [Bedrock](/en/amazon-bedrock), [Vertex AI](/en/google-vertex-ai), [Foundry](/en/microsoft-foundry) |

20| [Decide how settings reach devices](#decide-how-settings-reach-devices) | How managed policy reaches developer machines | [Server-managed settings](/en/server-managed-settings), [Settings files](/en/settings#settings-files) |

21| [Decide what to enforce](#decide-what-to-enforce) | Which tools, commands, and integrations are allowed | [Permissions](/en/permissions), [Sandboxing](/en/sandboxing) |

22| [Set up usage visibility](#set-up-usage-visibility) | How you track spend and adoption | [Analytics](/en/analytics), [Monitoring](/en/monitoring-usage), [Costs](/en/costs) |

23| [Review data handling](#review-data-handling) | Data retention and compliance posture | [Data usage](/en/data-usage), [Security](/en/security) |

24 

25## Choose your API provider

26 

27Claude Code connects to Claude through one of several API providers. Your choice affects billing, authentication, and which compliance posture you inherit.

28 

29| Provider | Choose this when |

30| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |

31| Claude for Teams / Enterprise | You want Claude Code and claude.ai under one per-seat subscription with no infrastructure to run. This is the default recommendation. |

32| Claude Console | You're API-first or want pay-as-you-go billing |

33| Amazon Bedrock | You want to inherit existing AWS compliance controls and billing |

34| Google Vertex AI | You want to inherit existing GCP compliance controls and billing |

35| Microsoft Foundry | You want to inherit existing Azure compliance controls and billing |

36 

37For the full provider comparison covering authentication, regions, and feature parity, see the [enterprise deployment overview](/en/third-party-integrations). Each provider's auth setup is in [Authentication](/en/authentication).

38 

39Proxy and firewall requirements in [Network configuration](/en/network-config) apply regardless of provider. If you want a single endpoint in front of multiple providers or centralized request logging, see [LLM gateway](/en/llm-gateway).

40 

41## Decide how settings reach devices

42 

43Managed settings define policy that takes precedence over local developer configuration. Claude Code looks for them in four places and uses the first one it finds on a given device.

44 

45| Mechanism | Delivery | Priority | Platforms |

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

47| Server-managed | Claude.ai admin console | Highest | All |

48| plist / registry policy | macOS: `com.anthropic.claudecode` plist<br />Windows: `HKLM\SOFTWARE\Policies\ClaudeCode` | High | macOS, Windows |

49| File-based managed | macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`<br />Linux and WSL: `/etc/claude-code/managed-settings.json`<br />Windows: `C:\Program Files\ClaudeCode\managed-settings.json` | Medium | All |

50| Windows user registry | `HKCU\SOFTWARE\Policies\ClaudeCode` | Lowest | Windows only |

51 

52Server-managed settings reach devices at authentication time and refresh hourly during active sessions, with no endpoint infrastructure. They require a Claude for Teams or Enterprise plan, so deployments on other providers need one of the file-based or OS-level mechanisms instead.

53 

54If your organization mixes providers, configure [server-managed settings](/en/server-managed-settings) for Claude.ai users plus a [file-based or plist/registry fallback](/en/settings#settings-files) so other users still receive managed policy.

55 

56The plist and HKLM registry locations work with any provider and resist tampering because they require admin privileges to write. The Windows user registry at HKCU is writable without elevation, so treat it as a convenience default rather than an enforcement channel.

57 

58By default WSL reads only the Linux file path at `/etc/claude-code`. To extend your Windows registry and `C:\Program Files\ClaudeCode` policy to WSL on the same machine, set [`wslInheritsWindowsSettings: true`](/en/settings#available-settings) in either of those admin-only Windows sources.

59 

60Whichever mechanism you choose, managed values take precedence over user and project settings. Array settings such as `permissions.allow` and `permissions.deny` merge entries from all sources, so developers can extend managed lists but not remove from them.

61 

62See [Server-managed settings](/en/server-managed-settings) and [Settings files and precedence](/en/settings#settings-files).

63 

64## Decide what to enforce

65 

66Managed settings can lock down tools, sandbox execution, restrict MCP servers and plugin sources, and control which hooks run. Each row is a control surface with the setting keys that drive it.

67 

68| Control | What it does | Key settings |

69| :------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------- | :---------------------------------------------------------------------------- |

70| [Permission rules](/en/permissions) | Allow, ask, or deny specific tools and commands | `permissions.allow`, `permissions.deny` |

71| [Permission lockdown](/en/permissions#managed-only-settings) | Only managed permission rules apply; disable `--dangerously-skip-permissions` | `allowManagedPermissionRulesOnly`, `permissions.disableBypassPermissionsMode` |

72| [Sandboxing](/en/sandboxing) | OS-level filesystem and network isolation with domain allowlists | `sandbox.enabled`, `sandbox.network.allowedDomains` |

73| [Managed policy CLAUDE.md](/en/memory#deploy-organization-wide-claude-md) | Org-wide instructions loaded in every session, cannot be excluded | File at the managed policy path |

74| [MCP server control](/en/mcp#managed-mcp-configuration) | Restrict which MCP servers users can add or connect to | `allowedMcpServers`, `deniedMcpServers`, `allowManagedMcpServersOnly` |

75| [Plugin marketplace control](/en/plugin-marketplaces#managed-marketplace-restrictions) | Restrict which marketplace sources users can add and install from | `strictKnownMarketplaces`, `blockedMarketplaces` |

76| [Hook restrictions](/en/settings#hook-configuration) | Only managed hooks load; restrict HTTP hook URLs | `allowManagedHooksOnly`, `allowedHttpHookUrls` |

77| [Version floor](/en/settings) | Prevent auto-update from installing below an org-wide minimum | `minimumVersion` |

78 

79Permission rules and sandboxing cover different layers. Denying WebFetch blocks Claude's fetch tool, but if Bash is allowed, `curl` and `wget` can still reach any URL. Sandboxing closes that gap with a network domain allowlist enforced at the OS level.

80 

81For the threat model these controls defend against, see [Security](/en/security).

82 

83## Set up usage visibility

84 

85Choose monitoring based on what you need to report on.

86 

87| Capability | What you get | Availability | Where to start |

88| :------------------ | :--------------------------------------------------- | :------------- | :--------------------------------------- |

89| Usage monitoring | OpenTelemetry export of sessions, tools, and tokens | All providers | [Monitoring usage](/en/monitoring-usage) |

90| Analytics dashboard | Per-user metrics, contribution tracking, leaderboard | Anthropic only | [Analytics](/en/analytics) |

91| Cost tracking | Spend limits, rate limits, and usage attribution | Anthropic only | [Costs](/en/costs) |

92 

93Cloud providers expose spend through AWS Cost Explorer, GCP Billing, or Azure Cost Management. Claude for Teams and Enterprise plans include a usage dashboard at [claude.ai/analytics/claude-code](https://claude.ai/analytics/claude-code).

94 

95## Review data handling

96 

97On Team, Enterprise, Claude API, and cloud provider plans, Anthropic does not train models on your code or prompts. Your API provider determines retention and compliance posture.

98 

99| Topic | What to know | Where to start |

100| :------------------------ | :------------------------------------------------------------------------------ | :--------------------------------------------- |

101| Data usage policy | What Anthropic collects, how long it's retained, what's never used for training | [Data usage](/en/data-usage) |

102| Zero Data Retention (ZDR) | Nothing stored after the request completes. Available on Claude for Enterprise | [Zero data retention](/en/zero-data-retention) |

103| Security architecture | Network model, encryption, authentication, audit trail | [Security](/en/security) |

104 

105If you need request-level audit logging or to route traffic by data sensitivity, place an [LLM gateway](/en/llm-gateway) between developers and your provider. For regulatory requirements and certifications, see [Legal and compliance](/en/legal-and-compliance).

106 

107## Verify and onboard

108 

109After configuring managed settings, have a developer run `/status` inside Claude Code. The output includes a line beginning with `Enterprise managed settings` followed by the source in parentheses, one of `(remote)`, `(plist)`, `(HKLM)`, `(HKCU)`, or `(file)`. See [Verify active settings](/en/settings#verify-active-settings).

110 

111Share these resources to help developers get started:

112 

113* [Quickstart](/en/quickstart): first-session walkthrough from install to working with a project

114* [Common workflows](/en/common-workflows): patterns for everyday tasks like code review, refactoring, and debugging

115* [Claude 101](https://anthropic.skilljar.com/claude-101) and [Claude Code in Action](https://anthropic.skilljar.com/claude-code-in-action): self-paced Anthropic Academy courses

116 

117For login issues, point developers to [authentication troubleshooting](/en/troubleshoot-install#login-and-authentication). The most common fixes are:

118 

119* Run `/logout` then `/login` to switch accounts

120* Run `claude update` if the enterprise auth option is missing

121* Restart the terminal after updating

122 

123If a developer sees "You haven't been added to your organization yet," their seat doesn't include Claude Code access and needs to be updated in the admin console.

124 

125## Next steps

126 

127With provider and delivery mechanism chosen, move on to detailed configuration:

128 

129* [Server-managed settings](/en/server-managed-settings): deliver managed policy from the Claude admin console

130* [Settings reference](/en/settings): every setting key, file location, and precedence rule

131* [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), [Microsoft Foundry](/en/microsoft-foundry): provider-specific deployment

132* [Claude Enterprise Administrator Guide](https://claude.com/resources/tutorials/claude-enterprise-administrator-guide): SSO, SCIM, seat management, and rollout playbook

Details

47 47 

48As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are:48As the loop runs, the SDK yields a stream of messages. Each message carries a type that tells you what stage of the loop it came from. The five core types are:

49 49 

50* **`SystemMessage`:** session lifecycle events. The `subtype` field distinguishes them: `"init"` is the first message (session metadata), and `"compact_boundary"` fires after [compaction](#automatic-compaction). In TypeScript, the compact boundary is its own [`SDKCompactBoundaryMessage`](/en/agent-sdk/typescript#sdk-compact-boundary-message) type rather than a subtype of `SDKSystemMessage`.50* **`SystemMessage`:** session lifecycle events. The `subtype` field distinguishes them: `"init"` is the first message (session metadata), and `"compact_boundary"` fires after [compaction](#automatic-compaction). In TypeScript, the compact boundary is its own [`SDKCompactBoundaryMessage`](/en/agent-sdk/typescript#sdkcompactboundarymessage) type rather than a subtype of `SDKSystemMessage`.

51* **`AssistantMessage`:** emitted after each Claude response, including the final text-only one. Contains text content blocks and tool call blocks from that turn.51* **`AssistantMessage`:** emitted after each Claude response, including the final text-only one. Contains text content blocks and tool call blocks from that turn.

52* **`UserMessage`:** emitted after each tool execution with the tool result content sent back to Claude. Also emitted for any user inputs you stream mid-loop.52* **`UserMessage`:** emitted after each tool execution with the tool result content sent back to Claude. Also emitted for any user inputs you stream mid-loop.

53* **`StreamEvent`:** only emitted when partial messages are enabled. Contains raw API streaming events (text deltas, tool input chunks). See [Stream responses](/en/agent-sdk/streaming-output).53* **`StreamEvent`:** only emitted when partial messages are enabled. Contains raw API streaming events (text deltas, tool input chunks). See [Stream responses](/en/agent-sdk/streaming-output).

54* **`ResultMessage`:** the last message, always. Contains the final text result, token usage, cost, and session ID. Check the `subtype` field to determine whether the task succeeded or hit a limit. See [Handle the result](#handle-the-result).54* **`ResultMessage`:** marks the end of the agent loop. Contains the final text result, token usage, cost, and session ID. Check the `subtype` field to determine whether the task succeeded or hit a limit. A small number of trailing system events, such as `prompt_suggestion`, can arrive after it, so iterate the stream to completion rather than breaking on the result. See [Handle the result](#handle-the-result).

55 55 

56These five types cover the full agent loop lifecycle in both SDKs. The TypeScript SDK also yields additional observability events (hook events, tool progress, rate limits, task notifications) that provide extra detail but are not required to drive the loop. See the [Python message types reference](/en/agent-sdk/python#message-types) and [TypeScript message types reference](/en/agent-sdk/typescript#message-types) for the complete lists.56These five types cover the full agent loop lifecycle in both SDKs. The TypeScript SDK also yields additional observability events (hook events, tool progress, rate limits, task notifications) that provide extra detail but are not required to drive the loop. See the [Python message types reference](/en/agent-sdk/python#message-types) and [TypeScript message types reference](/en/agent-sdk/typescript#message-types) for the complete lists.

57 57 


133* **`disallowed_tools` / `disallowedTools`** blocks listed tools, regardless of other settings. See [Permissions](/en/agent-sdk/permissions) for the order that rules are checked before a tool runs.133* **`disallowed_tools` / `disallowedTools`** blocks listed tools, regardless of other settings. See [Permissions](/en/agent-sdk/permissions) for the order that rules are checked before a tool runs.

134* **`permission_mode` / `permissionMode`** controls what happens to tools that aren't covered by allow or deny rules. See [Permission mode](#permission-mode) for available modes.134* **`permission_mode` / `permissionMode`** controls what happens to tools that aren't covered by allow or deny rules. See [Permission mode](#permission-mode) for available modes.

135 135 

136You can also scope individual tools with rules like `"Bash(npm:*)"` to allow only specific commands. See [Permissions](/en/agent-sdk/permissions) for the full rule syntax.136You can also scope individual tools with rules like `"Bash(npm *)"` to allow only specific commands. See [Permissions](/en/agent-sdk/permissions) for the full rule syntax.

137 137 

138When a tool is denied, Claude receives a rejection message as the tool result and typically attempts a different approach or reports that it couldn't proceed.138When a tool is denied, Claude receives a rejection message as the tool result and typically attempts a different approach or reports that it couldn't proceed.

139 139 


141 141 

142When Claude requests multiple tool calls in a single turn, both SDKs can run them concurrently or sequentially depending on the tool. Read-only tools (like `Read`, `Glob`, `Grep`, and MCP tools marked as read-only) can run concurrently. Tools that modify state (like `Edit`, `Write`, and `Bash`) run sequentially to avoid conflicts.142When Claude requests multiple tool calls in a single turn, both SDKs can run them concurrently or sequentially depending on the tool. Read-only tools (like `Read`, `Glob`, `Grep`, and MCP tools marked as read-only) can run concurrently. Tools that modify state (like `Edit`, `Write`, and `Bash`) run sequentially to avoid conflicts.

143 143 

144Custom tools default to sequential execution. To enable parallel execution for a custom tool, mark it as read-only in its annotations: `readOnly` in [TypeScript](/en/agent-sdk/typescript#tool) or `readOnlyHint` in [Python](/en/agent-sdk/python#tool).144Custom tools default to sequential execution. To enable parallel execution for a custom tool, set `readOnlyHint` in its annotations. Both the [TypeScript](/en/agent-sdk/typescript#tool) and [Python](/en/agent-sdk/python#tool) SDKs use this field name from the MCP SDK.

145 145 

146## Control how the loop runs146## Control how the loop runs

147 147 

148You can limit how many turns the loop takes, how much it costs, how deeply Claude reasons, and whether tools require approval before running. All of these are fields on [`ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options) (Python) / [`Options`](/en/agent-sdk/typescript#options) (TypeScript).148You can limit how many turns the loop takes, how much it costs, how deeply Claude reasons, and whether tools require approval before running. All of these are fields on [`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) (Python) / [`Options`](/en/agent-sdk/typescript#options) (TypeScript).

149 149 

150### Turns and budget150### Turns and budget

151 151 


154| Max turns (`max_turns` / `maxTurns`) | Maximum tool-use round trips | No limit |154| Max turns (`max_turns` / `maxTurns`) | Maximum tool-use round trips | No limit |

155| Max budget (`max_budget_usd` / `maxBudgetUsd`) | Maximum cost before stopping | No limit |155| Max budget (`max_budget_usd` / `maxBudgetUsd`) | Maximum cost before stopping | No limit |

156 156 

157When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See [Handle the result](#handle-the-result) for how to check these subtypes and [`ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options) / [`Options`](/en/agent-sdk/typescript#options) for syntax.157When either limit is hit, the SDK returns a `ResultMessage` with a corresponding error subtype (`error_max_turns` or `error_max_budget_usd`). See [Handle the result](#handle-the-result) for how to check these subtypes and [`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) / [`Options`](/en/agent-sdk/typescript#options) for syntax.

158 158 

159### Effort level159### Effort level

160 160 

161The `effort` option controls how much reasoning Claude applies. Lower effort levels use fewer tokens per turn and reduce cost. Not all models support the effort parameter. See [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) for which models support it.161The `effort` option controls how much reasoning Claude applies. Lower effort levels use fewer tokens per turn and reduce cost. Not all models support the effort parameter. See [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) for which models support it.

162 162 

163| Level | Behavior | Good for |163| Level | Behavior | Good for |

164| :--------- | :-------------------------------- | :------------------------------------------ |164| :--------- | :-------------------------------- | :------------------------------------------------ |

165| `"low"` | Minimal reasoning, fast responses | File lookups, listing directories |165| `"low"` | Minimal reasoning, fast responses | File lookups, listing directories |

166| `"medium"` | Balanced reasoning | Routine edits, standard tasks |166| `"medium"` | Balanced reasoning | Routine edits, standard tasks |

167| `"high"` | Thorough analysis | Refactors, debugging |167| `"high"` | Thorough analysis | Refactors, debugging |

168| `"xhigh"` | Extended reasoning depth | Coding and agentic tasks; recommended on Opus 4.7 |

168| `"max"` | Maximum reasoning depth | Multi-step problems requiring deep analysis |169| `"max"` | Maximum reasoning depth | Multi-step problems requiring deep analysis |

169 170 

170If you don't set `effort`, the Python SDK leaves the parameter unset and defers to the model's default behavior. The TypeScript SDK defaults to `"high"`.171If you don't set `effort`, the Python SDK leaves the parameter unset and defers to the model's default behavior. The TypeScript SDK defaults to `"high"`.


173 `effort` trades latency and token cost for reasoning depth within each response. [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) is a separate feature that produces visible chain-of-thought blocks in the output. They are independent: you can set `effort: "low"` with extended thinking enabled, or `effort: "max"` without it.174 `effort` trades latency and token cost for reasoning depth within each response. [Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) is a separate feature that produces visible chain-of-thought blocks in the output. They are independent: you can set `effort: "low"` with extended thinking enabled, or `effort: "max"` without it.

174</Note>175</Note>

175 176 

176Use lower effort for agents doing simple, well-scoped tasks (like listing files or running a single grep) to reduce cost and latency. `effort` is set at the top-level `query()` options, not per-subagent.177Use lower effort for agents doing simple, well-scoped tasks (like listing files or running a single grep) to reduce cost and latency. Set `effort` in the top-level `query()` options for the whole session, or per subagent with the `effort` field on [`AgentDefinition`](/en/agent-sdk/subagents#agentdefinition-configuration) to override the session level.

177 178 

178### Permission mode179### Permission mode

179 180 


183| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |184| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

184| `"default"` | Tools not covered by allow rules trigger your approval callback; no callback means deny |185| `"default"` | Tools not covered by allow rules trigger your approval callback; no callback means deny |

185| `"acceptEdits"` | Auto-approves file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.); other Bash commands follow default rules |186| `"acceptEdits"` | Auto-approves file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.); other Bash commands follow default rules |

186| `"plan"` | No tool execution; Claude produces a plan for review |187| `"plan"` | Read-only tools run; Claude explores and produces a plan without editing your source files |

187| `"dontAsk"` | Never prompts. Tools pre-approved by [permission rules](/en/settings#permission-settings) run, everything else is denied |188| `"dontAsk"` | Never prompts. Tools pre-approved by [permission rules](/en/settings#permission-settings) run, everything else is denied |

188| `"auto"` (TypeScript only) | Uses a model classifier to approve or deny each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability and behavior |189| `"auto"` (TypeScript only) | Uses a model classifier to approve or deny each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability and behavior |

189| `"bypassPermissions"` | Runs all allowed tools without asking. Cannot be used when running as root on Unix. Use only in isolated environments where the agent's actions cannot affect systems you care about |190| `"bypassPermissions"` | Runs all allowed tools without asking. Cannot be used when running as root on Unix. Use only in isolated environments where the agent's actions cannot affect systems you care about |


203Here's how each component affects context in the SDK:204Here's how each component affects context in the SDK:

204 205 

205| Source | When it loads | Impact |206| Source | When it loads | Impact |

206| :----------------------- | :------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------- |207| :----------------------- | :------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------- |

207| **System prompt** | Every request | Small fixed cost, always present |208| **System prompt** | Every request | Small fixed cost, always present |

208| **CLAUDE.md files** | Session start, when [`settingSources`](/en/agent-sdk/claude-code-features) is enabled | Full content in every request (but prompt-cached, so only the first request pays full cost) |209| **CLAUDE.md files** | Session start, via [`settingSources`](/en/agent-sdk/claude-code-features) | Full content in every request (but prompt-cached, so only the first request pays full cost) |

209| **Tool definitions** | Every request | Each tool adds its schema; use [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) to load tools on-demand instead of all at once |210| **Tool definitions** | Every request | Each tool adds its schema; use [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) to load tools on-demand instead of all at once |

210| **Conversation history** | Accumulates over turns | Grows with each turn: prompts, responses, tool inputs, tool outputs |211| **Conversation history** | Accumulates over turns | Grows with each turn: prompts, responses, tool inputs, tool outputs |

211| **Skill descriptions** | Session start (with setting sources enabled) | Short summaries; full content loads only when invoked |212| **Skill descriptions** | Session start, via setting sources | Short summaries; full content loads only when invoked |

212 213 

213Large tool outputs consume significant context. Reading a big file or running a command with verbose output can use thousands of tokens in a single turn. Context accumulates across turns, so longer sessions with many tool calls build up significantly more context than short ones.214Large tool outputs consume significant context. Reading a big file or running a command with verbose output can use thousands of tokens in a single turn. Context accumulates across turns, so longer sessions with many tool calls build up significantly more context than short ones.

214 215 


243A few strategies for long-running agents:244A few strategies for long-running agents:

244 245 

245* **Use subagents for subtasks.** Each subagent starts with a fresh conversation (no prior message history, though it does load its own system prompt and project-level context like CLAUDE.md). It does not see the parent's turns, and only its final response returns to the parent as a tool result. The main agent's context grows by that summary, not by the full subtask transcript. See [What subagents inherit](/en/agent-sdk/subagents#what-subagents-inherit) for details.246* **Use subagents for subtasks.** Each subagent starts with a fresh conversation (no prior message history, though it does load its own system prompt and project-level context like CLAUDE.md). It does not see the parent's turns, and only its final response returns to the parent as a tool result. The main agent's context grows by that summary, not by the full subtask transcript. See [What subagents inherit](/en/agent-sdk/subagents#what-subagents-inherit) for details.

246* **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](/en/agent-sdk/subagents#agent-definition-configuration) to scope subagents to the minimum set they need, and use [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) to load tools on demand instead of preloading all of them.247* **Be selective with tools.** Every tool definition takes context space. Use the `tools` field on [`AgentDefinition`](/en/agent-sdk/subagents#agentdefinition-configuration) to scope subagents to the minimum set they need, and use [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) to load tools on demand instead of preloading all of them.

247* **Watch MCP server costs.** Each MCP server adds all its tool schemas to every request. A few servers with many tools can consume significant context before the agent does any work. The `ToolSearch` tool can help by loading tools on-demand instead of preloading all of them. See [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) for configuration.248* **Watch MCP server costs.** Each MCP server adds all its tool schemas to every request. A few servers with many tools can consume significant context before the agent does any work. The `ToolSearch` tool can help by loading tools on-demand instead of preloading all of them. See [MCP tool search](/en/agent-sdk/mcp#mcp-tool-search) for configuration.

248* **Use lower effort for routine tasks.** Set [effort](#effort-level) to `"low"` for agents that only need to read files or list directories. This reduces token usage and cost.249* **Use lower effort for routine tasks.** Set [effort](#effort-level) to `"low"` for agents that only need to read files or list directories. This reduces token usage and cost.

249 250 


258See [Session management](/en/agent-sdk/sessions) for the full guide on resume, continue, and fork patterns.259See [Session management](/en/agent-sdk/sessions) for the full guide on resume, continue, and fork patterns.

259 260 

260<Note>261<Note>

261 In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client) for details.262 In Python, `ClaudeSDKClient` handles session IDs automatically across multiple calls. See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claudesdkclient) for details.

262</Note>263</Note>

263 264 

264## Handle the result265## Handle the result


275 276 

276The `result` field (the final text output) is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. In Python, `total_cost_usd` and `usage` are typed as optional and may be `None` on some error paths, so guard before formatting them. See [Tracking costs and usage](/en/agent-sdk/cost-tracking) for details on interpreting the `usage` fields.277The `result` field (the final text output) is only present on the `success` variant, so always check the subtype before reading it. All result subtypes carry `total_cost_usd`, `usage`, `num_turns`, and `session_id` so you can track cost and resume even after errors. In Python, `total_cost_usd` and `usage` are typed as optional and may be `None` on some error paths, so guard before formatting them. See [Tracking costs and usage](/en/agent-sdk/cost-tracking) for details on interpreting the `usage` fields.

277 278 

278The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error result subtypes, `stop_reason` carries the value from the last assistant response before the loop ended. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](/en/agent-sdk/typescript#sdk-result-message) (TypeScript) or [`ResultMessage`](/en/agent-sdk/python#result-message) (Python) for the full type.279The result also includes a `stop_reason` field (`string | null` in TypeScript, `str | None` in Python) indicating why the model stopped generating on its final turn. Common values are `end_turn` (model finished normally), `max_tokens` (hit the output token limit), and `refusal` (the model declined the request). On error result subtypes, `stop_reason` carries the value from the last assistant response before the loop ended. To detect refusals, check `stop_reason === "refusal"` (TypeScript) or `stop_reason == "refusal"` (Python). See [`SDKResultMessage`](/en/agent-sdk/typescript#sdkresultmessage) (TypeScript) or [`ResultMessage`](/en/agent-sdk/python#resultmessage) (Python) for the full type.

279 280 

280## Hooks281## Hooks

281 282 

Details

8 8 

9The Agent SDK is built on the same foundation as Claude Code, which means your SDK agents have access to the same filesystem-based features: project instructions (`CLAUDE.md` and rules), skills, hooks, and more.9The Agent SDK is built on the same foundation as Claude Code, which means your SDK agents have access to the same filesystem-based features: project instructions (`CLAUDE.md` and rules), skills, hooks, and more.

10 10 

11By default, the SDK loads no filesystem settings. Your agent runs in isolation mode with only what you pass programmatically. To load CLAUDE.md, skills, or filesystem hooks, set `settingSources` to tell the SDK where to look.11When you omit `settingSources`, `query()` reads the same filesystem settings as the Claude Code CLI: user, project, and local settings, CLAUDE.md files, and `.claude/` skills, agents, and commands. To run without these, pass `settingSources: []`, which limits the agent to what you configure programmatically. Managed policy settings and the global `~/.claude.json` config are read regardless of this option. See [What settingSources does not control](#what-settingsources-does-not-control).

12 12 

13For a conceptual overview of what each feature does and when to use it, see [Extend Claude Code](/en/features-overview).13For a conceptual overview of what each feature does and when to use it, see [Extend Claude Code](/en/features-overview).

14 14 

15## Enable Claude Code features with settingSources15## Control filesystem settings with settingSources

16 16 

17The setting sources option ([`setting_sources`](/en/agent-sdk/python#claude-agent-options) in Python, [`settingSources`](/en/agent-sdk/typescript#setting-source) in TypeScript) controls which filesystem-based settings the SDK loads. Without it, your agent won't discover skills, `CLAUDE.md` files, or project-level hooks.17The setting sources option ([`setting_sources`](/en/agent-sdk/python#claudeagentoptions) in Python, [`settingSources`](/en/agent-sdk/typescript#settingsource) in TypeScript) controls which filesystem-based settings the SDK loads. Pass an explicit list to opt in to specific sources, or pass an empty array to disable user, project, and local settings.

18 18 

19This example loads both user-level and project-level settings by setting `settingSources` to `["user", "project"]`:19This example loads both user-level and project-level settings by setting `settingSources` to `["user", "project"]`:

20 20 


65 ```65 ```

66</CodeGroup>66</CodeGroup>

67 67 

68Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option (or the process's current directory if unset). For the full type definition, see [`SettingSource`](/en/agent-sdk/typescript#setting-source) (TypeScript) or [`SettingSource`](/en/agent-sdk/python#setting-source) (Python).68Each source loads settings from a specific location, where `<cwd>` is the working directory you pass via the `cwd` option, or the process's current directory if unset. For the full type definition, see [`SettingSource`](/en/agent-sdk/typescript#settingsource) (TypeScript) or [`SettingSource`](/en/agent-sdk/python#settingsource) (Python).

69 69 

70| Source | What it loads | Location |70| Source | What it loads | Location |

71| :---------- | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |71| :---------- | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |


73| `"user"` | User CLAUDE.md, `~/.claude/rules/*.md`, user skills, user settings | `~/.claude/` |73| `"user"` | User CLAUDE.md, `~/.claude/rules/*.md`, user skills, user settings | `~/.claude/` |

74| `"local"` | CLAUDE.local.md (gitignored), `.claude/settings.local.json` | `<cwd>/` |74| `"local"` | CLAUDE.local.md (gitignored), `.claude/settings.local.json` | `<cwd>/` |

75 75 

76To match the full Claude Code CLI behavior, use `["user", "project", "local"]`.76Omitting `settingSources` is equivalent to `["user", "project", "local"]`.

77 

78The `cwd` option determines where the SDK looks for project settings. If neither `cwd` nor any of its parent directories contains a `.claude/` folder, project-level features won't load.

79 

80### What settingSources does not control

81 

82`settingSources` covers user, project, and local settings. A few inputs are read regardless of its value:

83 

84| Input | Behavior | To disable |

85| :---------------------------------------------------- | :--------------------------------------- | :------------------------------------------------------------------------------------------ |

86| Managed policy settings | Always loaded when present on the host | Remove the managed settings file |

87| `~/.claude.json` global config | Always read | Relocate with `CLAUDE_CONFIG_DIR` in `env` |

88| Auto memory at `~/.claude/projects/<project>/memory/` | Loaded by default into the system prompt | Set `autoMemoryEnabled: false` in settings, or `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env` |

77 89 

78<Warning>90<Warning>

79 The `cwd` option determines where the SDK looks for project settings. If neither `cwd` nor any of its parent directories contains a `.claude/` folder, project-level features won't load. Auto memory (the `~/.claude/projects/<project>/memory/` directory that Claude Code uses to persist notes across interactive sessions) is a CLI-only feature and is never loaded by the SDK.91 Do not rely on default `query()` options for multi-tenant isolation. Because the inputs above are read regardless of `settingSources`, an SDK process can pick up host-level configuration and per-directory memory. For multi-tenant deployments, run each tenant in its own filesystem and set `settingSources: []` plus `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` in `env`. See [Secure deployment](/en/agent-sdk/secure-deployment).

80</Warning>92</Warning>

81 93 

82## Project instructions (CLAUDE.md and rules)94## Project instructions (CLAUDE.md and rules)


107 119 

108Skills are markdown files that give your agent specialized knowledge and invocable workflows. Unlike `CLAUDE.md` (which loads every session), skills load on demand. The agent receives skill descriptions at startup and loads the full content when relevant.120Skills are markdown files that give your agent specialized knowledge and invocable workflows. Unlike `CLAUDE.md` (which loads every session), skills load on demand. The agent receives skill descriptions at startup and loads the full content when relevant.

109 121 

110To use skills in the SDK, set `settingSources` so the agent discovers skill files from the filesystem. The `Skill` tool is enabled by default when you don't specify `allowedTools`. If you are using an `allowedTools` allowlist, include `"Skill"` explicitly.122Skills are discovered from the filesystem through `settingSources`. When the `skills` option on `query()` is omitted, discovered user and project skills are enabled and the Skill tool is available, matching CLI behavior. To control which skills are enabled, pass `skills` as `"all"`, a list of skill names, or `[]` to disable all. The SDK enables the Skill tool automatically when `skills` is set, so you do not need to add it to `allowedTools`.

111 123 

112<CodeGroup>124<CodeGroup>

113 ```python Python theme={null}125 ```python Python theme={null}


119 prompt="Review this PR using our code review checklist",131 prompt="Review this PR using our code review checklist",

120 options=ClaudeAgentOptions(132 options=ClaudeAgentOptions(

121 setting_sources=["user", "project"],133 setting_sources=["user", "project"],

122 allowed_tools=["Skill", "Read", "Grep", "Glob"],134 skills="all",

135 allowed_tools=["Read", "Grep", "Glob"],

123 ),136 ),

124 ):137 ):

125 if isinstance(message, ResultMessage) and message.subtype == "success":138 if isinstance(message, ResultMessage) and message.subtype == "success":


135 prompt: "Review this PR using our code review checklist",148 prompt: "Review this PR using our code review checklist",

136 options: {149 options: {

137 settingSources: ["user", "project"],150 settingSources: ["user", "project"],

138 allowedTools: ["Skill", "Read", "Grep", "Glob"]151 skills: "all",

152 allowedTools: ["Read", "Grep", "Glob"]

139 }153 }

140 })) {154 })) {

141 if (message.type === "result" && message.subtype === "success") {155 if (message.type === "result" && message.subtype === "success") {


231### When to use which hook type245### When to use which hook type

232 246 

233| Hook type | Best for |247| Hook type | Best for |

234| :---------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |248| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

235| **Filesystem** (`settings.json`) | Sharing hooks between CLI and SDK sessions. Supports `"command"` (shell scripts), `"http"` (POST to an endpoint), `"prompt"` (LLM evaluates a prompt), and `"agent"` (spawns a verifier agent). These fire in the main agent and any subagents it spawns. |249| **Filesystem** (`settings.json`) | Sharing hooks between CLI and SDK sessions. Supports `"command"` (shell scripts), `"http"` (POST to an endpoint), `"mcp_tool"` (call a connected MCP server's tool), `"prompt"` (LLM evaluates a prompt), and `"agent"` (spawns a verifier agent). These fire in the main agent and any subagents it spawns. |

236| **Programmatic** (callbacks in `query()`) | Application-specific logic; returning structured decisions; in-process integration. Scoped to the main session only. |250| **Programmatic** (callbacks in `query()`) | Application-specific logic; returning structured decisions; in-process integration. Scoped to the main session only. |

237 251 

238<Note>252<Note>


248| You want to... | Use | SDK surface |262| You want to... | Use | SDK surface |

249| :------------------------------------------------------------------------------------------------ | :-------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |263| :------------------------------------------------------------------------------------------------ | :-------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |

250| Set project conventions your agent always follows | [CLAUDE.md](/en/memory) | `settingSources: ["project"]` loads it automatically |264| Set project conventions your agent always follows | [CLAUDE.md](/en/memory) | `settingSources: ["project"]` loads it automatically |

251| Give the agent reference material it loads when relevant | [Skills](/en/agent-sdk/skills) | `settingSources` + `allowedTools: ["Skill"]` |265| Give the agent reference material it loads when relevant | [Skills](/en/agent-sdk/skills) | `settingSources` + `skills` option |

252| Run a reusable workflow (deploy, review, release) | [User-invocable skills](/en/agent-sdk/skills) | `settingSources` + `allowedTools: ["Skill"]` |266| Run a reusable workflow (deploy, review, release) | [User-invocable skills](/en/agent-sdk/skills) | `settingSources` + `skills` option |

253| Delegate an isolated subtask to a fresh context (research, review) | [Subagents](/en/agent-sdk/subagents) | `agents` parameter + `allowedTools: ["Agent"]` |267| Delegate an isolated subtask to a fresh context (research, review) | [Subagents](/en/agent-sdk/subagents) | `agents` parameter + `allowedTools: ["Agent"]` |

254| Coordinate multiple Claude Code instances with shared task lists and direct inter-agent messaging | [Agent teams](/en/agent-teams) | Not directly configured via SDK options. Agent teams are a CLI feature where one session acts as the team lead, coordinating work across independent teammates |268| Coordinate multiple Claude Code instances with shared task lists and direct inter-agent messaging | [Agent teams](/en/agent-teams) | Not directly configured via SDK options. Agent teams are a CLI feature where one session acts as the team lead, coordinating work across independent teammates |

255| Run deterministic logic on tool calls (audit, block, transform) | [Hooks](/en/agent-sdk/hooks) | `hooks` parameter with callbacks, or shell scripts loaded via `settingSources` |269| Run deterministic logic on tool calls (audit, block, transform) | [Hooks](/en/agent-sdk/hooks) | `hooks` parameter with callbacks, or shell scripts loaded via `settingSources` |

Details

4 4 

5# Track cost and usage5# Track cost and usage

6 6 

7> Learn how to track token usage, deduplicate parallel tool calls, and calculate costs with the Claude Agent SDK.7> Learn how to track token usage, estimate costs, and configure prompt caching with the Claude Agent SDK.

8 8 

9The Claude Agent SDK provides detailed token usage information for each interaction with Claude. This guide explains how to properly track costs and understand usage reporting, especially when dealing with parallel tool uses and multi-step conversations.9The Claude Agent SDK provides detailed token usage information for each interaction with Claude. This guide explains how to properly track usage and understand cost reporting, especially when dealing with parallel tool uses and multi-step conversations.

10 10 

11For complete API documentation, see the [TypeScript SDK reference](/en/agent-sdk/typescript) and [Python SDK reference](/en/agent-sdk/python).11For complete API documentation, see the [TypeScript SDK reference](/en/agent-sdk/typescript) and [Python SDK reference](/en/agent-sdk/python).

12 12 

13<Warning>

14 The `total_cost_usd` and `costUSD` fields are client-side estimates, not authoritative billing data. The SDK computes them locally from a price table bundled at build time, so they can drift from what you are actually billed when:

15 

16 * pricing changes

17 * the installed SDK version does not recognize a model

18 * billing rules apply that the client cannot model

19 

20 Use these fields for development insight and approximate budgeting. For authoritative billing, use the [Usage and Cost API](https://platform.claude.com/docs/en/build-with-claude/usage-cost-api) or the Usage page in the [Claude Console](https://platform.claude.com/usage). Do not bill end users or trigger financial decisions from these fields.

21</Warning>

22 

13## Understand token usage23## Understand token usage

14 24 

15The TypeScript and Python SDKs expose the same usage data with different field names:25The TypeScript and Python SDKs expose the same usage data with different field names:


21 31 

22Cost tracking depends on understanding how the SDK scopes usage data:32Cost tracking depends on understanding how the SDK scopes usage data:

23 33 

24* **`query()` call:** one invocation of the SDK's `query()` function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces one [`result`](/en/agent-sdk/typescript#sdk-result-message) message at the end.34* **`query()` call:** one invocation of the SDK's `query()` function. A single call can involve multiple steps (Claude responds, uses tools, gets results, responds again). Each call produces one [`result`](/en/agent-sdk/typescript#sdkresultmessage) message at the end.

25* **Step:** a single request/response cycle within a `query()` call. Each step produces assistant messages with token usage.35* **Step:** a single request/response cycle within a `query()` call. Each step produces assistant messages with token usage.

26* **Session:** a series of `query()` calls linked by a session ID (using the `resume` option). Each `query()` call within a session reports its own cost independently.36* **Session:** a series of `query()` calls linked by a session ID (using the `resume` option). Each `query()` call within a session reports its own cost independently.

27 37 

28The following diagram shows the message stream from a single `query()` call, with token usage reported at each step and the authoritative total at the end:38The following diagram shows the message stream from a single `query()` call, with token usage reported at each step and the cumulative estimate at the end:

29 39 

30<img src="https://mintcdn.com/claude-code/gvy2DIUELtNA8qD3/images/agent-sdk/message-usage-flow.svg?fit=max&auto=format&n=gvy2DIUELtNA8qD3&q=85&s=88cba82134f8f7994d780c3f153b83fc" alt="Diagram showing a query producing two steps of messages. Step 1 has four assistant messages sharing the same ID and usage (count once), Step 2 has one assistant message with a new ID, and the final result message shows total_cost_usd for billing." width="760" height="520" data-path="images/agent-sdk/message-usage-flow.svg" />40<img src="https://mintcdn.com/claude-code/Dujg43sxTkuhSELI/images/agent-sdk/message-usage-flow.svg?fit=max&auto=format&n=Dujg43sxTkuhSELI&q=85&s=c542f51ff58547ef9c0e57b16d03f33c" alt="Diagram showing a query producing two steps of messages. Step 1 has four assistant messages sharing the same ID and usage (count once), Step 2 has one assistant message with a new ID, and the final result message shows the estimated total_cost_usd." width="760" height="520" data-path="images/agent-sdk/message-usage-flow.svg" />

31 41 

32<Steps>42<Steps>

33 <Step title="Each step produces assistant messages">43 <Step title="Each step produces assistant messages">

34 When Claude responds, it sends one or more assistant messages. In TypeScript, each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and a [`usage`](https://platform.claude.com/docs/en/api/messages) object with token counts (`input_tokens`, `output_tokens`). In Python, the `AssistantMessage` dataclass exposes the same data directly via `message.usage` and `message.message_id`. When Claude uses multiple tools in one turn, all messages in that turn share the same ID, so deduplicate by ID to avoid double-counting.44 When Claude responds, it sends one or more assistant messages. In TypeScript, each assistant message contains a nested `BetaMessage` (accessed via `message.message`) with an `id` and a [`usage`](https://platform.claude.com/docs/en/api/messages) object with token counts (`input_tokens`, `output_tokens`). In Python, the `AssistantMessage` dataclass exposes the same data directly via `message.usage` and `message.message_id`. When Claude uses multiple tools in one turn, all messages in that turn share the same ID, so deduplicate by ID to avoid double-counting.

35 </Step>45 </Step>

36 46 

37 <Step title="The result message provides the authoritative total">47 <Step title="The result message provides the cumulative estimate">

38 When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`. This is available in both TypeScript ([`SDKResultMessage`](/en/agent-sdk/typescript#sdk-result-message)) and Python ([`ResultMessage`](/en/agent-sdk/python#result-message)). If you make multiple `query()` calls (for example, in a multi-turn session), each result only reflects the cost of that individual call. If you only need the total cost, you can ignore the per-step usage and read this single value.48 When the `query()` call completes, the SDK emits a result message with `total_cost_usd` and cumulative `usage`. This is available in both TypeScript ([`SDKResultMessage`](/en/agent-sdk/typescript#sdkresultmessage)) and Python ([`ResultMessage`](/en/agent-sdk/python#resultmessage)). If you make multiple `query()` calls (for example, in a multi-turn session), each result only reflects the cost of that individual call. If you only need the estimated total, you can ignore the per-step usage and read this single value.

39 </Step>49 </Step>

40</Steps>50</Steps>

41 51 

42## Get the total cost of a query52## Get the total cost of a query

43 53 

44The result message ([TypeScript](/en/agent-sdk/typescript#sdk-result-message), [Python](/en/agent-sdk/python#result-message)) is the last message in every `query()` call. It includes `total_cost_usd`, the cumulative cost across all steps in that call. This works for both success and error results. If you use sessions to make multiple `query()` calls, each result only reflects the cost of that individual call.54The result message ([TypeScript](/en/agent-sdk/typescript#sdkresultmessage), [Python](/en/agent-sdk/python#resultmessage)) marks the end of the agent loop for a `query()` call. It includes `total_cost_usd`, the cumulative estimated cost across all steps in that call. This works for both success and error results. If you use sessions to make multiple `query()` calls, each result only reflects the cost of that individual call.

45 55 

46The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives:56The following examples iterate over the message stream from a `query()` call and print the total cost when the `result` message arrives:

47 57 


73 83 

74## Track per-step and per-model usage84## Track per-step and per-model usage

75 85 

76The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](/en/agent-sdk/python#assistant-message) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](/en/agent-sdk/python#result-message) for per-model breakdowns.86The examples in this section use TypeScript field names. In Python, the equivalent fields are [`AssistantMessage.usage`](/en/agent-sdk/python#assistantmessage) and `AssistantMessage.message_id` for per-step usage, and [`ResultMessage.model_usage`](/en/agent-sdk/python#resultmessage) for per-model breakdowns.

77 87 

78### Track per-step usage88### Track per-step usage

79 89 


112 122 

113### Break down usage per model123### Break down usage per model

114 124 

115The result message includes [`modelUsage`](/en/agent-sdk/typescript#model-usage), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going.125The result message includes [`modelUsage`](/en/agent-sdk/typescript#modelusage), a map of model name to per-model token counts and cost. This is useful when you run multiple models (for example, Haiku for subagents and Opus for the main agent) and want to see where tokens are going.

116 126 

117The following example runs a query and prints the cost and token breakdown for each model used:127The following example runs a query and prints the cost and token breakdown for each model used:

118 128 


199In rare cases, you might observe different `output_tokens` values for messages with the same ID. When this occurs:209In rare cases, you might observe different `output_tokens` values for messages with the same ID. When this occurs:

200 210 

2011. **Use the highest value:** the final message in a group typically contains the accurate total.2111. **Use the highest value:** the final message in a group typically contains the accurate total.

2022. **Verify against total cost:** the `total_cost_usd` in the result message is authoritative.2122. **Prefer the result message:** the `total_cost_usd` in the result message reflects the SDK's accumulated estimate across all steps, so it is more reliable than summing per-step values yourself. It is still an estimate and may differ from your actual bill.

2033. **Report inconsistencies:** file issues at the [Claude Code GitHub repository](https://github.com/anthropics/claude-code/issues).2133. **Report inconsistencies:** file issues at the [Claude Code GitHub repository](https://github.com/anthropics/claude-code/issues).

204 214 

205### Track costs on failed conversations215### Track costs on failed conversations


213* `cache_creation_input_tokens`: tokens used to create new cache entries (charged at a higher rate than standard input tokens).223* `cache_creation_input_tokens`: tokens used to create new cache entries (charged at a higher rate than standard input tokens).

214* `cache_read_input_tokens`: tokens read from existing cache entries (charged at a reduced rate).224* `cache_read_input_tokens`: tokens read from existing cache entries (charged at a reduced rate).

215 225 

216Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](/en/agent-sdk/typescript#usage) object. In Python, they appear as keys in the [`ResultMessage.usage`](/en/agent-sdk/python#result-message) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`).226Track these separately from `input_tokens` to understand caching savings. In TypeScript, these fields are typed on the [`Usage`](/en/agent-sdk/typescript#usage) object. In Python, they appear as keys in the [`ResultMessage.usage`](/en/agent-sdk/python#resultmessage) dict (for example, `message.usage.get("cache_read_input_tokens", 0)`).

227 

228### Extend the prompt cache TTL to one hour

229 

230Cache entries written by the SDK use a 5-minute TTL by default when you authenticate with an API key or run on Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. If your workload runs many short sessions against the same system prompt and context with gaps longer than 5 minutes between them, the cache expires between sessions and each new session pays full input price.

231 

232To request a 1-hour TTL on cache writes, set the [`ENABLE_PROMPT_CACHING_1H`](/en/env-vars) environment variable. You can export it in your shell or container environment, or pass it through `options.env`.

233 

234The following example enables 1-hour TTL for an agent running on Bedrock:

235 

236<CodeGroup>

237 ```python Python theme={null}

238 options = ClaudeAgentOptions(

239 env={

240 "CLAUDE_CODE_USE_BEDROCK": "1",

241 "ENABLE_PROMPT_CACHING_1H": "1",

242 },

243 )

244 ```

245 

246 ```typescript TypeScript theme={null}

247 const options = {

248 env: {

249 ...process.env,

250 CLAUDE_CODE_USE_BEDROCK: "1",

251 ENABLE_PROMPT_CACHING_1H: "1",

252 },

253 };

254 ```

255</CodeGroup>

256 

257Cache writes with a 1-hour TTL are billed at a higher rate than 5-minute writes, so enabling this trades higher write cost for more cache reads. See [prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for details. Claude subscription users already receive 1-hour TTL automatically and do not need to set this variable.

217 258 

218## Related documentation259## Related documentation

219 260 

Details

21| Let Claude call tools in parallel | Set `readOnlyHint: true` on tools with no side effects. See [Add tool annotations](#add-tool-annotations). |21| Let Claude call tools in parallel | Set `readOnlyHint: true` on tools with no side effects. See [Add tool annotations](#add-tool-annotations). |

22| Handle errors without stopping the loop | Return `isError: true` instead of throwing. See [Handle errors](#handle-errors). |22| Handle errors without stopping the loop | Return `isError: true` instead of throwing. See [Handle errors](#handle-errors). |

23| Return images or files | Use `image` or `resource` blocks in the content array. See [Return images and resources](#return-images-and-resources). |23| Return images or files | Use `image` or `resource` blocks in the content array. See [Return images and resources](#return-images-and-resources). |

24| Return a machine-readable JSON result | Set `structuredContent` on the result. See [Return structured data](#return-structured-data). |

24| Scale to many tools | Use [tool search](/en/agent-sdk/tool-search) to load tools on demand. |25| Scale to many tools | Use [tool search](/en/agent-sdk/tool-search) to load tools on demand. |

25 26 

26## Create a custom tool27## Create a custom tool


32* **Input schema:** the arguments Claude must provide. In TypeScript this is always a [Zod schema](https://zod.dev/), and the handler's `args` are typed from it automatically. In Python this is a dict mapping names to types, like `{"latitude": float}`, which the SDK converts to JSON Schema for you. The Python decorator also accepts a full [JSON Schema](https://json-schema.org/understanding-json-schema/about) dict directly when you need enums, ranges, optional fields, or nested objects.33* **Input schema:** the arguments Claude must provide. In TypeScript this is always a [Zod schema](https://zod.dev/), and the handler's `args` are typed from it automatically. In Python this is a dict mapping names to types, like `{"latitude": float}`, which the SDK converts to JSON Schema for you. The Python decorator also accepts a full [JSON Schema](https://json-schema.org/understanding-json-schema/about) dict directly when you need enums, ranges, optional fields, or nested objects.

33* **Handler:** the async function that runs when Claude calls the tool. It receives the validated arguments and must return an object with:34* **Handler:** the async function that runs when Claude calls the tool. It receives the validated arguments and must return an object with:

34 * `content` (required): an array of result blocks, each with a `type` of `"text"`, `"image"`, or `"resource"`. See [Return images and resources](#return-images-and-resources) for non-text blocks.35 * `content` (required): an array of result blocks, each with a `type` of `"text"`, `"image"`, or `"resource"`. See [Return images and resources](#return-images-and-resources) for non-text blocks.

36 * `structuredContent` (optional): a JSON object holding the result as machine-readable data, returned alongside `content`. See [Return structured data](#return-structured-data).

35 * `isError` (optional): set to `true` to signal a tool failure so Claude can react to it. See [Handle errors](#handle-errors).37 * `isError` (optional): set to `true` to signal a tool failure so Claude can react to it. See [Handle errors](#handle-errors).

36 38 

37After defining a tool, wrap it in a server with [`createSdkMcpServer`](/en/agent-sdk/typescript#create-sdk-mcp-server) (TypeScript) or [`create_sdk_mcp_server`](/en/agent-sdk/python#create-sdk-mcp-server) (Python). The server runs in-process inside your application, not as a separate process.39After defining a tool, wrap it in a server with [`createSdkMcpServer`](/en/agent-sdk/typescript#createsdkmcpserver) (TypeScript) or [`create_sdk_mcp_server`](/en/agent-sdk/python#create_sdk_mcp_server) (Python). The server runs in-process inside your application, not as a separate process.

38 40 

39### Weather tool example41### Weather tool example

40 42 


306 ```308 ```

307</CodeGroup>309</CodeGroup>

308 310 

309See `ToolAnnotations` in the [TypeScript](/en/agent-sdk/typescript#tool-annotations) or [Python](/en/agent-sdk/python#tool-annotations) reference.311See `ToolAnnotations` in the [TypeScript](/en/agent-sdk/typescript#toolannotations) or [Python](/en/agent-sdk/python#toolannotations) reference.

310 312 

311## Control tool access313## Control tool access

312 314 


550 552 

551These block shapes come from the MCP `CallToolResult` type. See the [MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result) for the full definition.553These block shapes come from the MCP `CallToolResult` type. See the [MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result) for the full definition.

552 554 

555## Return structured data

556 

557`structuredContent` is an optional JSON object on the result, separate from the `content` array. Use it to return raw values that Claude can read as exact fields instead of parsing them out of a text string or image.

558 

559When `structuredContent` is set, Claude receives the JSON plus any image or resource blocks from `content`. Text blocks in `content` are not forwarded, since they are assumed to duplicate the structured data. The example below renders a chart as an image block and returns the data points behind it in `structuredContent` from the same handler.

560 

561```typescript TypeScript theme={null}

562return {

563 content: [

564 {

565 type: "image",

566 data: chartPngBuffer.toString("base64"),

567 mimeType: "image/png"

568 }

569 ],

570 structuredContent: {

571 series: "temperature_2m",

572 unit: "fahrenheit",

573 points: [62.1, 63.4, 65.0, 64.2]

574 }

575};

576```

577 

578<Note>

579 The Python `@tool` decorator forwards only `content` and `is_error` from the handler's return dict. To return `structuredContent` from Python, run a [standalone MCP server](/en/agent-sdk/mcp) instead of an in-process SDK server.

580</Note>

581 

553## Example: unit converter582## Example: unit converter

554 583 

555This tool converts values between units of length, temperature, and weight. A user can ask "convert 100 kilometers to miles" or "what is 72°F in Celsius," and Claude picks the right unit type and units from the request.584This tool converts values between units of length, temperature, and weight. A user can ask "convert 100 kilometers to miles" or "what is 72°F in Celsius," and Claude picks the right unit type and units from the request.

agent-sdk/hooks.md +20 −19

Details

24 </Step>24 </Step>

25 25 

26 <Step title="The SDK collects registered hooks">26 <Step title="The SDK collects registered hooks">

27 The SDK checks for hooks registered for that event type. This includes callback hooks you pass in `options.hooks` and shell command hooks from settings files, but only if you explicitly load them with [`settingSources`](/en/agent-sdk/typescript#setting-source) or [`setting_sources`](/en/agent-sdk/python#setting-source).27 The SDK checks for hooks registered for that event type. This includes callback hooks you pass in `options.hooks` and shell command hooks from settings files when the corresponding [`settingSources`](/en/agent-sdk/typescript#settingsource) or [`setting_sources`](/en/agent-sdk/python#settingsource) entry is enabled, which it is for default `query()` options.

28 </Step>28 </Step>

29 29 

30 <Step title="Matchers filter which hooks run">30 <Step title="Matchers filter which hooks run">


145The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only.145The SDK provides hooks for different stages of agent execution. Some hooks are available in both SDKs, while others are TypeScript-only.

146 146 

147| Hook Event | Python SDK | TypeScript SDK | What triggers it | Example use case |147| Hook Event | Python SDK | TypeScript SDK | What triggers it | Example use case |

148| -------------------- | ---------- | -------------- | --------------------------------------- | ----------------------------------------------- |148| -------------------- | ---------- | -------------- | ------------------------------------------------------------------------------ | ----------------------------------------------- |

149| `PreToolUse` | Yes | Yes | Tool call request (can block or modify) | Block dangerous shell commands |149| `PreToolUse` | Yes | Yes | Tool call request (can block or modify) | Block dangerous shell commands |

150| `PostToolUse` | Yes | Yes | Tool execution result | Log all file changes to audit trail |150| `PostToolUse` | Yes | Yes | Tool execution result | Log all file changes to audit trail |

151| `PostToolUseFailure` | Yes | Yes | Tool execution failure | Handle or log tool errors |151| `PostToolUseFailure` | Yes | Yes | Tool execution failure | Handle or log tool errors |

152| `PostToolBatch` | No | Yes | A full batch of tool calls resolves, once per batch before the next model call | Inject conventions once for the whole batch |

152| `UserPromptSubmit` | Yes | Yes | User prompt submission | Inject additional context into prompts |153| `UserPromptSubmit` | Yes | Yes | User prompt submission | Inject additional context into prompts |

153| `Stop` | Yes | Yes | Agent execution stop | Save session state before exit |154| `Stop` | Yes | Yes | Agent execution stop | Save session state before exit |

154| `SubagentStart` | Yes | Yes | Subagent initialization | Track parallel task spawning |155| `SubagentStart` | Yes | Yes | Subagent initialization | Track parallel task spawning |


224 225 

225Every hook callback receives three arguments:226Every hook callback receives three arguments:

226 227 

227* **Input data:** a typed object containing event details. Each hook type has its own input shape (for example, `PreToolUseHookInput` includes `tool_name` and `tool_input`, while `NotificationHookInput` includes `message`). See the full type definitions in the [TypeScript](/en/agent-sdk/typescript#hook-input) and [Python](/en/agent-sdk/python#hook-input) SDK references.228* **Input data:** a typed object containing event details. Each hook type has its own input shape (for example, `PreToolUseHookInput` includes `tool_name` and `tool_input`, while `NotificationHookInput` includes `message`). See the full type definitions in the [TypeScript](/en/agent-sdk/typescript#hookinput) and [Python](/en/agent-sdk/python#hookinput) SDK references.

228 * All hook inputs share `session_id`, `cwd`, and `hook_event_name`.229 * All hook inputs share `session_id`, `cwd`, and `hook_event_name`.

229 * `agent_id` and `agent_type` are populated when the hook fires inside a subagent. In TypeScript, these are on the base hook input and available to all hook types. In Python, they are on `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` only.230 * `agent_id` and `agent_type` are populated when the hook fires inside a subagent. In TypeScript, these are on the base hook input and available to all hook types. In Python, they are on `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` only.

230* **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call.231* **Tool use ID** (`str | None` / `string | undefined`): correlates `PreToolUse` and `PostToolUse` events for the same tool call.


235Your callback returns an object with two categories of fields:236Your callback returns an object with two categories of fields:

236 237 

237* **Top-level fields** control the conversation: `systemMessage` injects a message into the conversation visible to the model, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.238* **Top-level fields** control the conversation: `systemMessage` injects a message into the conversation visible to the model, and `continue` (`continue_` in Python) determines whether the agent keeps running after this hook.

238* **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, or `"ask"`), `permissionDecisionReason`, and `updatedInput`. For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result.239* **`hookSpecificOutput`** controls the current operation. The fields inside depend on the hook event type. For `PreToolUse` hooks, this is where you set `permissionDecision` (`"allow"`, `"deny"`, or `"ask"`), `permissionDecisionReason`, and `updatedInput`. In the TypeScript SDK, `permissionDecision` also accepts `"defer"` to end the query and [resume later](/en/hooks#defer-a-tool-call-for-later); this value is not available in the Python SDK. For `PostToolUse` hooks, you can set `additionalContext` to append information to the tool result, or `updatedToolOutput` to replace the tool's output entirely before Claude sees it.

239 240 

240Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](/en/hooks#json-output), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](/en/agent-sdk/typescript#sync-hook-json-output) and [Python](/en/agent-sdk/python#sync-hook-json-output) SDK references.241Return `{}` to allow the operation without changes. SDK callback hooks use the same JSON output format as [Claude Code shell command hooks](/en/hooks#json-output), which documents every field and event-specific option. For the SDK type definitions, see the [TypeScript](/en/agent-sdk/typescript#synchookjsonoutput) and [Python](/en/agent-sdk/python#synchookjsonoutput) SDK references.

241 242 

242<Note>243<Note>

243 When multiple hooks or permission rules apply, **deny** takes priority over **ask**, which takes priority over **allow**. If any hook returns `deny`, the operation is blocked regardless of other hooks.244 When multiple hooks or permission rules apply, **deny** takes priority over **defer**, which takes priority over **ask**, which takes priority over **allow**. If any hook returns `deny`, the operation is blocked regardless of other hooks.

244</Note>245</Note>

245 246 

246#### Asynchronous output247#### Asynchronous output


416 ```417 ```

417</CodeGroup>418</CodeGroup>

418 419 

419### Chain multiple hooks420### Register multiple hooks

420 421 

421Hooks execute in the order they appear in the array. Keep each hook focused on a single responsibility and chain multiple hooks for complex logic:422When an event fires, all matching hooks run in parallel. For permission decisions, the most restrictive result wins: a single `deny` blocks the tool call regardless of what the other hooks return. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first.

423 

424The example below registers three independent checks for every tool call:

422 425 

423<CodeGroup>426<CodeGroup>

424 ```python Python theme={null}427 ```python Python theme={null}

425 options = ClaudeAgentOptions(428 options = ClaudeAgentOptions(

426 hooks={429 hooks={

427 "PreToolUse": [430 "PreToolUse": [

428 HookMatcher(hooks=[rate_limiter]), # First: check rate limits431 HookMatcher(hooks=[authorization_check]),

429 HookMatcher(hooks=[authorization_check]), # Second: verify permissions432 HookMatcher(hooks=[input_validator]),

430 HookMatcher(hooks=[input_sanitizer]), # Third: sanitize inputs433 HookMatcher(hooks=[audit_logger]),

431 HookMatcher(hooks=[audit_logger]), # Last: log the action

432 ]434 ]

433 }435 }

434 )436 )


438 const options = {440 const options = {

439 hooks: {441 hooks: {

440 PreToolUse: [442 PreToolUse: [

441 { hooks: [rateLimiter] }, // First: check rate limits443 { hooks: [authorizationCheck] },

442 { hooks: [authorizationCheck] }, // Second: verify permissions444 { hooks: [inputValidator] },

443 { hooks: [inputSanitizer] }, // Third: sanitize inputs445 { hooks: [auditLogger] }

444 { hooks: [auditLogger] } // Last: log the action

445 ]446 ]

446 }447 }

447 };448 };


488 489 

489### Track subagent activity490### Track subagent activity

490 491 

491Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](/en/agent-sdk/typescript#hook-input) and [Python](/en/agent-sdk/python#hook-input) SDK references. This example logs a summary each time a subagent completes:492Use `SubagentStop` hooks to monitor when subagents finish their work. See the full input type in the [TypeScript](/en/agent-sdk/typescript#hookinput) and [Python](/en/agent-sdk/python#hookinput) SDK references. This example logs a summary each time a subagent completes:

492 493 

493<CodeGroup>494<CodeGroup>

494 ```python Python theme={null}495 ```python Python theme={null}


726* Check that your matcher pattern matches the tool name exactly727* Check that your matcher pattern matches the tool name exactly

727* Ensure the hook is under the correct event type in `options.hooks`728* Ensure the hook is under the correct event type in `options.hooks`

728* For non-tool hooks like `Stop` and `SubagentStop`, matchers match against different fields (see [matcher patterns](/en/hooks#matcher-patterns))729* For non-tool hooks like `Stop` and `SubagentStop`, matchers match against different fields (see [matcher patterns](/en/hooks#matcher-patterns))

729* Hooks may not fire when the agent hits the [`max_turns`](/en/agent-sdk/python#claude-agent-options) limit because the session ends before hooks can execute730* Hooks may not fire when the agent hits the [`max_turns`](/en/agent-sdk/python#claudeagentoptions) limit because the session ends before hooks can execute

730 731 

731### Matcher not filtering as expected732### Matcher not filtering as expected

732 733 


774 775 

775### Session hooks not available in Python776### Session hooks not available in Python

776 777 

777`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but are not available in the Python SDK (`HookEvent` omits them). In Python, they are only available as [shell command hooks](/en/hooks#hook-events) defined in settings files (for example, `.claude/settings.json`). To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](/en/agent-sdk/python#setting-source) or [`settingSources`](/en/agent-sdk/typescript#setting-source):778`SessionStart` and `SessionEnd` can be registered as SDK callback hooks in TypeScript, but are not available in the Python SDK (`HookEvent` omits them). In Python, they are only available as [shell command hooks](/en/hooks#hook-events) defined in settings files (for example, `.claude/settings.json`). To load shell command hooks from your SDK application, include the appropriate setting source with [`setting_sources`](/en/agent-sdk/python#settingsource) or [`settingSources`](/en/agent-sdk/typescript#settingsource):

778 779 

779<CodeGroup>780<CodeGroup>

780 ```python Python theme={null}781 ```python Python theme={null}

Details

18 18 

19For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems.19For security and isolation, the SDK should run inside a sandboxed container environment. This provides process isolation, resource limits, network control, and ephemeral filesystems.

20 20 

21The SDK also supports [programmatic sandbox configuration](/en/agent-sdk/typescript#sandbox-settings) for command execution.21The SDK also supports [programmatic sandbox configuration](/en/agent-sdk/typescript#sandboxsettings) for command execution.

22 22 

23### System Requirements23### System Requirements

24 24 

25Each SDK instance requires:25Each SDK instance requires:

26 26 

27* **Runtime dependencies**27* **Runtime dependencies**

28 * Python 3.10+ (for Python SDK) or Node.js 18+ (for TypeScript SDK)28 * Python 3.10+ for the Python SDK, or Node.js 18+ for the TypeScript SDK

29 * Node.js (required by the bundled Claude Code CLI that the SDK spawns; both SDK packages include it, so no separate install is needed)29 * Both SDK packages bundle a native Claude Code binary for the host platform, so no separate Claude Code or Node.js install is needed for the spawned CLI

30 30 

31* **Resource allocation**31* **Resource allocation**

32 * Recommended: 1GiB RAM, 5GiB of disk, and 1 CPU (vary this based on your task as needed)32 * Recommended: 1GiB RAM, 5GiB of disk, and 1 CPU (vary this based on your task as needed)


135## Next Steps135## Next Steps

136 136 

137* [Secure Deployment](/en/agent-sdk/secure-deployment) - Network controls, credential management, and isolation hardening137* [Secure Deployment](/en/agent-sdk/secure-deployment) - Network controls, credential management, and isolation hardening

138* [TypeScript SDK - Sandbox Settings](/en/agent-sdk/typescript#sandbox-settings) - Configure sandbox programmatically138* [TypeScript SDK - Sandbox Settings](/en/agent-sdk/typescript#sandboxsettings) - Configure sandbox programmatically

139* [Sessions Guide](/en/agent-sdk/sessions) - Learn about session management139* [Sessions Guide](/en/agent-sdk/sessions) - Learn about session management

140* [Permissions](/en/agent-sdk/permissions) - Configure tool permissions140* [Permissions](/en/agent-sdk/permissions) - Configure tool permissions

141* [Cost Tracking](/en/agent-sdk/cost-tracking) - Monitor API usage141* [Cost Tracking](/en/agent-sdk/cost-tracking) - Monitor API usage

Details

10 10 

11MCP servers can run as local processes, connect over HTTP, or execute directly within your SDK application.11MCP servers can run as local processes, connect over HTTP, or execute directly within your SDK application.

12 12 

13<Note>

14 This page covers MCP configuration for the Agent SDK. To add MCP servers to the Claude Code CLI so they load in every project, see [MCP installation scopes](/en/mcp#mcp-installation-scopes).

15</Note>

16 

13## Quickstart17## Quickstart

14 18 

15This example connects to the [Claude Code documentation](https://code.claude.com/docs) MCP server using [HTTP transport](#httpsse-servers) and uses [`allowedTools`](#allow-mcp-tools) with a wildcard to permit all tools from the server.19This example connects to the [Claude Code documentation](https://code.claude.com/docs) MCP server using [HTTP transport](#httpsse-servers) and uses [`allowedTools`](#allow-mcp-tools) with a wildcard to permit all tools from the server.


127 131 

128### From a config file132### From a config file

129 133 

130Create a `.mcp.json` file at your project root. The SDK does not load filesystem settings by default, so set `settingSources: ["project"]` (Python: `setting_sources=["project"]`) in your options for the file to be picked up:134Create a `.mcp.json` file at your project root. The file is picked up when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` explicitly, include `"project"` for this file to load:

131 135 

132```json theme={null}136```json theme={null}

133{137{


305 </Tab>309 </Tab>

306</Tabs>310</Tabs>

307 311 

308For HTTP (non-streaming), use `"type": "http"` instead.312For the streamable HTTP transport, use `"type": "http"` instead. In `.mcp.json` and other JSON config files, `"streamable-http"` is accepted as an alias for `"http"`. The programmatic `mcpServers` option accepts only `"http"`.

309 313 

310### SDK MCP servers314### SDK MCP servers

311 315 

Details

110# Before110# Before

111from claude_code_sdk import query, ClaudeCodeOptions111from claude_code_sdk import query, ClaudeCodeOptions

112 112 

113options = ClaudeCodeOptions(model="claude-opus-4-6")113options = ClaudeCodeOptions(model="claude-opus-4-7")

114 114 

115# After115# After

116from claude_agent_sdk import query, ClaudeAgentOptions116from claude_agent_sdk import query, ClaudeAgentOptions

117 117 

118options = ClaudeAgentOptions(model="claude-opus-4-6")118options = ClaudeAgentOptions(model="claude-opus-4-7")

119```119```

120 120 

121**5. Review [breaking changes](#breaking-changes)**121**5. Review [breaking changes](#breaking-changes)**


138# BEFORE (claude-code-sdk)138# BEFORE (claude-code-sdk)

139from claude_code_sdk import query, ClaudeCodeOptions139from claude_code_sdk import query, ClaudeCodeOptions

140 140 

141options = ClaudeCodeOptions(model="claude-opus-4-6", permission_mode="acceptEdits")141options = ClaudeCodeOptions(model="claude-opus-4-7", permission_mode="acceptEdits")

142 142 

143# AFTER (claude-agent-sdk)143# AFTER (claude-agent-sdk)

144from claude_agent_sdk import query, ClaudeAgentOptions144from claude_agent_sdk import query, ClaudeAgentOptions

145 145 

146options = ClaudeAgentOptions(model="claude-opus-4-6", permission_mode="acceptEdits")146options = ClaudeAgentOptions(model="claude-opus-4-7", permission_mode="acceptEdits")

147```147```

148 148 

149**Why this changed:** The type name now matches the "Claude Agent SDK" branding and provides consistency across the SDK's naming conventions.149**Why this changed:** The type name now matches the "Claude Agent SDK" branding and provides consistency across the SDK's naming conventions.


205 205 

206**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.206**Why this changed:** Provides better control and isolation for SDK applications. You can now build agents with custom behavior without inheriting Claude Code's CLI-focused instructions.

207 207 

208### Settings Sources No Longer Loaded by Default208### Settings sources default

209 209 

210**What changed:** The SDK no longer reads from filesystem settings (CLAUDE.md, settings.json, slash commands, etc.) by default.210This default was briefly changed in v0.1.0 and then reverted, so no migration action is needed.

211 211 

212**Migration:**212**Current behavior:** Omitting `settingSources` on `query()` loads user, project, and local filesystem settings, matching the CLI. This includes `~/.claude/settings.json`, `.claude/settings.json`, `.claude/settings.local.json`, CLAUDE.md files, and custom commands.

213 

214To run isolated from filesystem settings, pass an empty array:

213 215 

214<CodeGroup>216<CodeGroup>

215 ```typescript TypeScript theme={null}217 ```typescript TypeScript theme={null}

216 // BEFORE (v0.0.x) - Loaded all settings automatically

217 const result = query({ prompt: "Hello" });

218 // Would read from:

219 // - ~/.claude/settings.json (user)

220 // - .claude/settings.json (project)

221 // - .claude/settings.local.json (local)

222 // - CLAUDE.md files

223 // - Custom slash commands

224 

225 // AFTER (v0.1.0) - No settings loaded by default

226 // To get the old behavior:

227 const result = query({218 const result = query({

228 prompt: "Hello",219 prompt: "Hello",

229 options: {220 options: {

230 settingSources: ["user", "project", "local"]221 settingSources: [] // No filesystem settings loaded

231 }222 }

232 });223 });

233 224 


241 ```232 ```

242 233 

243 ```python Python theme={null}234 ```python Python theme={null}

244 # BEFORE (v0.0.x) - Loaded all settings automatically

245 async for message in query(prompt="Hello"):

246 print(message)

247 # Would read from:

248 # - ~/.claude/settings.json (user)

249 # - .claude/settings.json (project)

250 # - .claude/settings.local.json (local)

251 # - CLAUDE.md files

252 # - Custom slash commands

253 

254 # AFTER (v0.1.0) - No settings loaded by default

255 # To get the old behavior:

256 from claude_agent_sdk import query, ClaudeAgentOptions235 from claude_agent_sdk import query, ClaudeAgentOptions

257 236 

258 async for message in query(237 async for message in query(

259 prompt="Hello",238 prompt="Hello",

260 options=ClaudeAgentOptions(setting_sources=["user", "project", "local"]),239 options=ClaudeAgentOptions(setting_sources=[]), # No filesystem settings loaded

261 ):240 ):

262 print(message)241 print(message)

263 242 


272 ```251 ```

273</CodeGroup>252</CodeGroup>

274 253 

275**Why this changed:** Ensures SDK applications have predictable behavior independent of local filesystem configurations. This is especially important for:254Isolation is especially important for CI/CD pipelines, deployed applications, test environments, and multi-tenant systems where local customizations should not leak in.

276 

277* **CI/CD environments** - Consistent behavior without local customizations

278* **Deployed applications** - No dependency on filesystem settings

279* **Testing** - Isolated test environments

280* **Multi-tenant systems** - Prevent settings leakage between users

281 255 

282<Note>256<Note>

283 **Backward compatibility:** If your application relied on filesystem settings (custom slash commands, CLAUDE.md instructions, etc.), add `settingSources: ['user', 'project', 'local']` to your options.257 SDK v0.1.0 briefly defaulted to no settings loaded; this was reverted in subsequent releases. Python SDK 0.1.59 and earlier treated an empty list the same as omitting the option, so upgrade before relying on `setting_sources=[]`. See [What settingSources does not control](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for inputs that are read even when `settingSources` is `[]`.

284</Note>258</Note>

285 259 

286## Why the Rename?260## Why the Rename?

Details

37* **Project-level:** `CLAUDE.md` or `.claude/CLAUDE.md` in your working directory37* **Project-level:** `CLAUDE.md` or `.claude/CLAUDE.md` in your working directory

38* **User-level:** `~/.claude/CLAUDE.md` for global instructions across all projects38* **User-level:** `~/.claude/CLAUDE.md` for global instructions across all projects

39 39 

40**IMPORTANT:** The SDK only reads CLAUDE.md files when you explicitly configure `settingSources` (TypeScript) or `setting_sources` (Python):40CLAUDE.md files are read when the corresponding setting source is enabled: `'project'` for project-level CLAUDE.md and `'user'` for `~/.claude/CLAUDE.md`. With default `query()` options both sources are enabled, so CLAUDE.md loads automatically. If you set `settingSources` (TypeScript) or `setting_sources` (Python) explicitly, include the sources you need. CLAUDE.md loading is controlled by setting sources, not by the `claude_code` preset.

41 

42* Include `'project'` to load project-level CLAUDE.md

43* Include `'user'` to load user-level CLAUDE.md (`~/.claude/CLAUDE.md`)

44 

45The `claude_code` system prompt preset does NOT automatically load CLAUDE.md - you must also specify setting sources.

46 41 

47**Content format:**42**Content format:**

48CLAUDE.md files use plain markdown and can contain:43CLAUDE.md files use plain markdown and can contain:


83 ```typescript TypeScript theme={null}78 ```typescript TypeScript theme={null}

84 import { query } from "@anthropic-ai/claude-agent-sdk";79 import { query } from "@anthropic-ai/claude-agent-sdk";

85 80 

86 // IMPORTANT: You must specify settingSources to load CLAUDE.md

87 // The claude_code preset alone does NOT load CLAUDE.md files

88 const messages = [];81 const messages = [];

89 82 

90 for await (const message of query({83 for await (const message of query({


94 type: "preset",87 type: "preset",

95 preset: "claude_code" // Use Claude Code's system prompt88 preset: "claude_code" // Use Claude Code's system prompt

96 },89 },

97 settingSources: ["project"] // Required to load CLAUDE.md from project90 settingSources: ["project"] // Loads CLAUDE.md from project

98 }91 }

99 })) {92 })) {

100 messages.push(message);93 messages.push(message);


106 ```python Python theme={null}99 ```python Python theme={null}

107 from claude_agent_sdk import query, ClaudeAgentOptions100 from claude_agent_sdk import query, ClaudeAgentOptions

108 101 

109 # IMPORTANT: You must specify setting_sources to load CLAUDE.md

110 # The claude_code preset alone does NOT load CLAUDE.md files

111 messages = []102 messages = []

112 103 

113 async for message in query(104 async for message in query(


117 "type": "preset",108 "type": "preset",

118 "preset": "claude_code", # Use Claude Code's system prompt109 "preset": "claude_code", # Use Claude Code's system prompt

119 },110 },

120 setting_sources=["project"], # Required to load CLAUDE.md from project111 setting_sources=["project"], # Loads CLAUDE.md from project

121 ),112 ),

122 ):113 ):

123 messages.append(message)114 messages.append(message)


141* ✅ Persistent across all sessions in a project132* ✅ Persistent across all sessions in a project

142* ✅ Shared with team via git133* ✅ Shared with team via git

143* ✅ Automatic discovery (no code changes needed)134* ✅ Automatic discovery (no code changes needed)

144* ⚠️ Requires loading settings via `settingSources`135* ⚠️ Not loaded if you pass `settingSources: []`

145 136 

146### Method 2: Output styles (persistent configurations)137### Method 2: Output styles (persistent configurations)

147 138 


283 ```274 ```

284</CodeGroup>275</CodeGroup>

285 276 

277#### Improve prompt caching across users and machines

278 

279By default, two sessions that use the same `claude_code` preset and `append` text still cannot share a prompt cache entry if they run from different working directories. This is because the preset embeds per-session context in the system prompt ahead of your `append` text: the working directory, platform and OS version, current date, git status, and auto-memory paths. Any difference in that context produces a different system prompt and a cache miss.

280 

281To make the system prompt identical across sessions, set `excludeDynamicSections: true` in TypeScript or `"exclude_dynamic_sections": True` in Python. The per-session context moves into the first user message, leaving only the static preset and your `append` text in the system prompt so identical configurations share a cache entry across users and machines.

282 

283<Note>

284 `excludeDynamicSections` requires `@anthropic-ai/claude-agent-sdk` v0.2.98 or later, or `claude-agent-sdk` v0.1.58 or later for Python. It applies only to the preset object form and has no effect when `systemPrompt` is a string.

285</Note>

286 

287The following example pairs a shared `append` block with `excludeDynamicSections` so a fleet of agents running from different directories can reuse the same cached system prompt:

288 

289<CodeGroup>

290 ```typescript TypeScript theme={null}

291 import { query } from "@anthropic-ai/claude-agent-sdk";

292 

293 for await (const message of query({

294 prompt: "Triage the open issues in this repo",

295 options: {

296 systemPrompt: {

297 type: "preset",

298 preset: "claude_code",

299 append: "You operate Acme's internal triage workflow. Label issues by component and severity.",

300 excludeDynamicSections: true

301 }

302 }

303 })) {

304 // ...

305 }

306 ```

307 

308 ```python Python theme={null}

309 from claude_agent_sdk import query, ClaudeAgentOptions

310 

311 async for message in query(

312 prompt="Triage the open issues in this repo",

313 options=ClaudeAgentOptions(

314 system_prompt={

315 "type": "preset",

316 "preset": "claude_code",

317 "append": "You operate Acme's internal triage workflow. Label issues by component and severity.",

318 "exclude_dynamic_sections": True,

319 },

320 ),

321 ):

322 ...

323 ```

324</CodeGroup>

325 

326**Tradeoffs:** the working directory, git status, and memory location still reach Claude, but as part of the first user message rather than the system prompt. Instructions in the user message carry marginally less weight than the same text in the system prompt, so Claude may rely on them less strongly when reasoning about the current directory or auto-memory paths. Enable this option when cross-session cache reuse matters more than maximally authoritative environment context.

327 

328For the equivalent flag in non-interactive CLI mode, see [`--exclude-dynamic-system-prompt-sections`](/en/cli-reference).

329 

286### Method 4: Custom system prompts330### Method 4: Custom system prompts

287 331 

288You can provide a custom string as `systemPrompt` to replace the default entirely with your own instructions.332You can provide a custom string as `systemPrompt` to replace the default entirely with your own instructions.


371* "Run `npm run lint:fix` before committing"415* "Run `npm run lint:fix` before committing"

372* "Database migrations are in the `migrations/` directory"416* "Database migrations are in the `migrations/` directory"

373 417 

374**Important:** To load CLAUDE.md files, you must explicitly set `settingSources: ['project']` (TypeScript) or `setting_sources=["project"]` (Python). The `claude_code` system prompt preset does NOT automatically load CLAUDE.md without this setting.418CLAUDE.md files load when the `project` setting source is enabled, which it is for default `query()` options. If you set `settingSources` (TypeScript) or `setting_sources` (Python) explicitly, include `'project'` to keep loading project-level CLAUDE.md.

375 419 

376### When to use output styles420### When to use output styles

377 421 

Details

113 113 

114### Flush telemetry from short-lived calls114### Flush telemetry from short-lived calls

115 115 

116The CLI batches telemetry and exports on an interval. It flushes any pending data when the process exits cleanly, so a `query()` call that completes normally does not lose spans. However, if your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces that window.116The CLI batches telemetry and exports on an interval. On a clean process exit it attempts to flush pending data, but the flush is bounded by a short timeout, so spans can still be dropped if the collector is slow to respond. If your process is killed before the CLI shuts down, anything still in the batch buffer is lost. Lowering the export intervals reduces both windows.

117 117 

118By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:118By default, metrics export every 60 seconds and traces and logs export every 5 seconds. The following example shortens all three intervals so that data reaches the collector while a short task is still running:

119 119 


144* **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.144* **`claude_code.interaction`:** wraps a single turn of the agent loop, from receiving a prompt to producing a response.

145* **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.145* **`claude_code.llm_request`:** wraps each call to the Claude API, with model name, latency, and token counts as attributes.

146* **`claude_code.tool`:** wraps each tool invocation, with child spans for the permission wait (`claude_code.tool.blocked_on_user`) and the execution itself (`claude_code.tool.execution`).146* **`claude_code.tool`:** wraps each tool invocation, with child spans for the permission wait (`claude_code.tool.blocked_on_user`) and the execution itself (`claude_code.tool.execution`).

147* **`claude_code.hook`:** wraps each [hook](/en/agent-sdk/hooks) execution.147* **`claude_code.hook`:** wraps each [hook](/en/agent-sdk/hooks) execution. Requires detailed beta tracing (`ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT`) in addition to the variables above.

148 148 

149Every span carries a `session.id` attribute. When you make several `query()` calls against the same [session](/en/agent-sdk/sessions), filter on `session.id` in your backend to see them as one timeline.149The `llm_request`, `tool`, and `hook` spans are children of the enclosing `claude_code.interaction` span. When the agent spawns a subagent through the Task tool, the subagent's `llm_request` and `tool` spans nest under the parent agent's `claude_code.tool` span, so the full delegation chain appears as one trace.

150 

151Spans carry a `session.id` attribute by default. When you make several `query()` calls against the same [session](/en/agent-sdk/sessions), filter on `session.id` in your backend to see them as one timeline. The attribute is omitted if `OTEL_METRICS_INCLUDE_SESSION_ID` is set to a falsy value.

150 152 

151<Note>153<Note>

152 Tracing is in beta. Span names and attributes may change between releases. See154 Tracing is in beta. Span names and attributes may change between releases. See


154 for the trace exporter configuration variables.156 for the trace exporter configuration variables.

155</Note>157</Note>

156 158 

159## Link traces to your application

160 

161The SDK automatically propagates W3C trace context into the CLI subprocess. When you call `query()` while an OpenTelemetry span is active in your application, the SDK injects `TRACEPARENT` and `TRACESTATE` into the child process environment, and the CLI reads them so its `claude_code.interaction` span becomes a child of your span. The agent run then appears inside your application's trace instead of as a disconnected root.

162 

163The CLI also forwards `TRACEPARENT` to every Bash and PowerShell command it runs. If a command launched through the Bash tool emits its own OpenTelemetry spans, those spans nest under the `claude_code.tool.execution` span that wraps the command.

164 

165Auto-injection is skipped when you set `TRACEPARENT` explicitly in `options.env`, so you can pin a specific parent context if needed. Interactive CLI sessions ignore inbound `TRACEPARENT` entirely; only Agent SDK and `claude -p` runs honor it. See [Traces (beta)](/en/monitoring-usage#traces-beta) in the Monitoring reference for the full span and attribute reference.

166 

157## Tag telemetry from your agent167## Tag telemetry from your agent

158 168 

159By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend.169By default, the CLI reports `service.name` as `claude-code`. If you run several agents, or run the SDK alongside other services that export to the same collector, override the service name and add resource attributes so you can filter by agent in your backend.


184 ```194 ```

185</CodeGroup>195</CodeGroup>

186 196 

197## Attribute actions to your end users

198 

199The CLI attaches [identity attributes](/en/monitoring-usage#standard-attributes) to every event based on the credential it uses to call Anthropic. When you build an application that serves many end users from one deployment, these attributes identify your service's credential, not the end user on whose behalf the agent acted.

200 

201To make tool calls and MCP activity attributable to your application's end users, inject end-user identity as resource attributes on each `query()` call. Percent-encode values before interpolating them, since `OTEL_RESOURCE_ATTRIBUTES` [reserves commas, spaces, and equals signs](/en/monitoring-usage#multi-team-organization-support). The following example attaches the requesting user and tenant to every span and event from one request:

202 

203<CodeGroup>

204 ```python Python theme={null}

205 from urllib.parse import quote

206 

207 options = ClaudeAgentOptions(

208 env={

209 # ... exporter configuration ...

210 "OTEL_RESOURCE_ATTRIBUTES": f"enduser.id={quote(request.user_id)},tenant.id={quote(request.tenant_id)}",

211 },

212 )

213 ```

214 

215 ```typescript TypeScript theme={null}

216 const options = {

217 env: {

218 ...process.env,

219 // ... exporter configuration ...

220 OTEL_RESOURCE_ATTRIBUTES: `enduser.id=${encodeURIComponent(request.userId)},tenant.id=${encodeURIComponent(request.tenantId)}`,

221 },

222 };

223 ```

224</CodeGroup>

225 

226With end-user identity attached, the `tool_decision`, `tool_result`, `mcp_server_connection`, and `permission_mode_changed` events become a per-user audit trail you can forward to a Security Information and Event Management (SIEM) platform. See [Audit security events](/en/monitoring-usage#audit-security-events) in the Monitoring reference for the full list of security-relevant events and the attributes each one carries.

227 

187## Control sensitive data in exports228## Control sensitive data in exports

188 229 

189Telemetry is structural by default. Token counts, durations, model names, and tool names are always recorded, but the content your agent reads and writes is not. Three opt-in variables add content to the exported data:230Telemetry is structural by default. Durations, model names, and tool names are recorded on every span; token counts are recorded when the underlying API request returns usage data, so spans for failed or aborted requests may omit them. The content your agent reads and writes is not recorded by default. These opt-in variables add content to the exported data:

190 231 

191| Variable | Adds |232| Variable | Adds |

192| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |233| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

193| `OTEL_LOG_USER_PROMPTS=1` | Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span |234| `OTEL_LOG_USER_PROMPTS=1` | Prompt text on `claude_code.user_prompt` events and on the `claude_code.interaction` span |

194| `OTEL_LOG_TOOL_DETAILS=1` | Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events |235| `OTEL_LOG_TOOL_DETAILS=1` | Tool input arguments (file paths, shell commands, search patterns) on `claude_code.tool_result` events |

195| `OTEL_LOG_TOOL_CONTENT=1` | Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB. Requires [tracing](#read-agent-traces) to be enabled |236| `OTEL_LOG_TOOL_CONTENT=1` | Full tool input and output bodies as span events on `claude_code.tool`, truncated at 60 KB. Requires [tracing](#read-agent-traces) to be enabled |

237| `OTEL_LOG_RAW_API_BODIES` | Full Anthropic Messages API request and response JSON as `claude_code.api_request_body` and `claude_code.api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` path in the event. Bodies include the entire conversation history and have extended-thinking content redacted. Enabling this implies consent to everything the three variables above would reveal |

196 238 

197Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](/en/monitoring-usage#security-and-privacy) in the Monitoring reference for the full list of attributes and redaction behavior.239Leave these unset unless your observability pipeline is approved to store the data your agent handles. See [Security and privacy](/en/monitoring-usage#security-and-privacy) in the Monitoring reference for the full list of attributes and redaction behavior.

198 240 

Details

12 12 

13Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.13Build AI agents that autonomously read files, run commands, search the web, edit code, and more. The Agent SDK gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.

14 14 

15<Note>

16 Opus 4.7 (`claude-opus-4-7`) requires Agent SDK v0.2.111 or later. If you see a `thinking.type.enabled` API error, see [Troubleshooting](/en/agent-sdk/quickstart#troubleshooting).

17</Note>

18 

15<CodeGroup>19<CodeGroup>

16 ```python Python theme={null}20 ```python Python theme={null}

17 import asyncio21 import asyncio


70 ```74 ```

71 </Tab>75 </Tab>

72 </Tabs>76 </Tabs>

77 

78 <Note>

79 The TypeScript SDK bundles a native Claude Code binary for your platform as an optional dependency, so you don't need to install Claude Code separately.

80 </Note>

73 </Step>81 </Step>

74 82 

75 <Step title="Set your API key">83 <Step title="Set your API key">


465 473 

466### Claude Code features474### Claude Code features

467 475 

468The SDK also supports Claude Code's filesystem-based configuration. To use these features, set `setting_sources=["project"]` (Python) or `settingSources: ['project']` (TypeScript) in your options.476The SDK also supports Claude Code's filesystem-based configuration. With default options the SDK loads these from `.claude/` in your working directory and `~/.claude/`. To restrict which sources load, set `setting_sources` (Python) or `settingSources` (TypeScript) in your options.

469 477 

470| Feature | Description | Location |478| Feature | Description | Location |

471| ------------------------------------------------ | ---------------------------------------------------- | ---------------------------------- |479| ------------------------------------------------ | ---------------------------------------------------- | ---------------------------------- |


526 534 

527 Many teams use both: CLI for daily development, SDK for production. Workflows translate directly between them.535 Many teams use both: CLI for daily development, SDK for production. Workflows translate directly between them.

528 </Tab>536 </Tab>

537 

538 <Tab title="Agent SDK vs Managed Agents">

539 [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) is a hosted REST API: Anthropic runs the agent and the sandbox, and your application sends events and streams back results. The **Agent SDK** is a library that runs the agent loop inside your own process.

540 

541 | | Agent SDK | Managed Agents |

542 | ------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |

543 | **Runs in** | Your process, your infrastructure | Anthropic-managed infrastructure |

544 | **Interface** | Python or TypeScript library | REST API |

545 | **Agent works on** | Files on your infrastructure | A managed sandbox per session |

546 | **Session state** | JSONL on your filesystem | Anthropic-hosted event log |

547 | **Custom tools** | In-process Python or TypeScript functions | Claude triggers the tool; you execute and return results |

548 | **Best for** | Local prototyping, agents that work directly on your filesystem and services | Production agents without operating sandbox or session infrastructure, long-running and asynchronous sessions |

549 

550 A common path is to prototype with the Agent SDK locally, then move to Managed Agents for production.

551 </Tab>

529</Tabs>552</Tabs>

530 553 

531## Changelog554## Changelog

Details

18 18 

19<Steps>19<Steps>

20 <Step title="Hooks">20 <Step title="Hooks">

21 Run [hooks](/en/agent-sdk/hooks) first, which can allow, deny, or continue to the next step21 Run [hooks](/en/agent-sdk/hooks) first. A hook can deny the call outright or pass it on. A hook that returns `allow` does not skip the deny and ask rules below; those are evaluated regardless of the hook result.

22 </Step>22 </Step>

23 23 

24 <Step title="Deny rules">24 <Step title="Deny rules">


38 </Step>38 </Step>

39</Steps>39</Steps>

40 40 

41<img src="https://mintcdn.com/claude-code/gvy2DIUELtNA8qD3/images/agent-sdk/permissions-flow.svg?fit=max&auto=format&n=gvy2DIUELtNA8qD3&q=85&s=0ccd63043a9ffc2a34d863602e043f72" alt="Permission evaluation flow diagram" width="920" height="260" data-path="images/agent-sdk/permissions-flow.svg" />41<img src="https://mintcdn.com/claude-code/FEspvVUyRuaWjm0s/images/agent-sdk/permissions-flow.svg?fit=max&auto=format&n=FEspvVUyRuaWjm0s&q=85&s=a1759b0cf4541281a9fdd8f5348228e8" alt="Permission evaluation flow diagram" width="920" height="260" data-path="images/agent-sdk/permissions-flow.svg" />

42 42 

43This page focuses on **allow and deny rules** and **permission modes**. For the other steps:43This page focuses on **allow and deny rules** and **permission modes**. For the other steps:

44 44 


67 **`allowed_tools` does not constrain `bypassPermissions`.** `allowed_tools` only pre-approves the tools you list. Unlisted tools are not matched by any allow rule and fall through to the permission mode, where `bypassPermissions` approves them. Setting `allowed_tools=["Read"]` alongside `permission_mode="bypassPermissions"` still approves every tool, including `Bash`, `Write`, and `Edit`. If you need `bypassPermissions` but want specific tools blocked, use `disallowed_tools`.67 **`allowed_tools` does not constrain `bypassPermissions`.** `allowed_tools` only pre-approves the tools you list. Unlisted tools are not matched by any allow rule and fall through to the permission mode, where `bypassPermissions` approves them. Setting `allowed_tools=["Read"]` alongside `permission_mode="bypassPermissions"` still approves every tool, including `Bash`, `Write`, and `Edit`. If you need `bypassPermissions` but want specific tools blocked, use `disallowed_tools`.

68</Warning>68</Warning>

69 69 

70You can also configure allow, deny, and ask rules declaratively in `.claude/settings.json`. The SDK does not load filesystem settings by default, so you must set `setting_sources=["project"]` (TypeScript: `settingSources: ["project"]`) in your options for these rules to apply. See [Permission settings](/en/settings#permission-settings) for the rule syntax.70You can also configure allow, deny, and ask rules declaratively in `.claude/settings.json`. These rules are read when the `project` setting source is enabled, which it is for default `query()` options. If you set `setting_sources` (TypeScript: `settingSources`) explicitly, include `"project"` for them to apply. See [Permission settings](/en/settings#permission-settings) for the rule syntax.

71 71 

72## Permission modes72## Permission modes

73 73 


83| `dontAsk` | Deny instead of prompting | Anything not pre-approved by `allowed_tools` or rules is denied; `canUseTool` is never called |83| `dontAsk` | Deny instead of prompting | Anything not pre-approved by `allowed_tools` or rules is denied; `canUseTool` is never called |

84| `acceptEdits` | Auto-accept file edits | File edits and [filesystem operations](#accept-edits-mode-acceptedits) (`mkdir`, `rm`, `mv`, etc.) are automatically approved |84| `acceptEdits` | Auto-accept file edits | File edits and [filesystem operations](#accept-edits-mode-acceptedits) (`mkdir`, `rm`, `mv`, etc.) are automatically approved |

85| `bypassPermissions` | Bypass all permission checks | All tools run without permission prompts (use with caution) |85| `bypassPermissions` | Bypass all permission checks | All tools run without permission prompts (use with caution) |

86| `plan` | Planning mode | No tool execution; Claude plans without making changes |86| `plan` | Planning mode | Read-only tools run; Claude analyzes and plans without editing your source files |

87| `auto` (TypeScript only) | Model-classified approvals | A model classifier approves or denies each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability |87| `auto` (TypeScript only) | Model-classified approvals | A model classifier approves or denies each tool call. See [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) for availability |

88 88 

89<Warning>89<Warning>

90 **Subagent inheritance:** When using `bypassPermissions`, all subagents inherit this mode and it cannot be overridden. Subagents may have different system prompts and less constrained behavior than your main agent. Enabling `bypassPermissions` grants them full, autonomous system access without any approval prompts.90 **Subagent inheritance:** When the parent uses `bypassPermissions`, `acceptEdits`, or `auto`, all subagents inherit that mode and it cannot be overridden per subagent. Subagents may have different system prompts and less constrained behavior than your main agent, so inheriting `bypassPermissions` grants them full, autonomous system access without any approval prompts.

91</Warning>91</Warning>

92 92 

93### Set permission mode93### Set permission mode


145 <CodeGroup>145 <CodeGroup>

146 ```python Python theme={null}146 ```python Python theme={null}

147 import asyncio147 import asyncio

148 from claude_agent_sdk import query, ClaudeAgentOptions148 from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

149 149 

150 150 

151 async def main():151 async def main():

152 q = query(152 async with ClaudeSDKClient(

153 prompt="Help me refactor this code",

154 options=ClaudeAgentOptions(153 options=ClaudeAgentOptions(

155 permission_mode="default", # Start in default mode154 permission_mode="default", # Start in default mode

156 ),

157 )155 )

156 ) as client:

157 await client.query("Help me refactor this code")

158 158 

159 # Change mode dynamically mid-session159 # Change mode dynamically mid-session

160 await q.set_permission_mode("acceptEdits")160 await client.set_permission_mode("acceptEdits")

161 161 

162 # Process messages with the new permission mode162 # Process messages with the new permission mode

163 async for message in q:163 async for message in client.receive_response():

164 if hasattr(message, "result"):164 if hasattr(message, "result"):

165 print(message.result)165 print(message.result)

166 166 


229 229 

230#### Plan mode (`plan`)230#### Plan mode (`plan`)

231 231 

232Prevents tool execution entirely. Claude can analyze code and create plans but cannot make changes. Claude may use `AskUserQuestion` to clarify requirements before finalizing the plan. See [Handle approvals and user input](/en/agent-sdk/user-input#handle-clarifying-questions) for handling these prompts.232Restricts Claude to read-only tools. Claude can read files and run read-only shell commands to explore the codebase but does not edit your source files. Claude may use `AskUserQuestion` to clarify requirements before finalizing the plan. See [Handle approvals and user input](/en/agent-sdk/user-input#handle-clarifying-questions) for handling these prompts.

233 233 

234**Use when:** you want Claude to propose changes without executing them, such as during code review or when you need to approve changes before they're made.234**Use when:** you want Claude to propose changes without executing them, such as during code review or when you need to approve changes before they're made.

235 235 

Details

25 25 

26## Loading plugins26## Loading plugins

27 27 

28Load plugins by providing their local file system paths in your options configuration. The SDK supports loading multiple plugins from different locations.28Load plugins by providing their local file system paths in your options configuration. The `type` field must be `"local"`, the only value the SDK accepts. To use a plugin distributed through a [marketplace](/en/plugin-marketplaces) or remote repository, download it first and provide the local directory path. The SDK supports loading multiple plugins from different locations.

29 29 

30<CodeGroup>30<CodeGroup>

31 ```typescript TypeScript theme={null}31 ```typescript TypeScript theme={null}

agent-sdk/python.md +157 −73

Details

113#### Parameters113#### Parameters

114 114 

115| Parameter | Type | Description |115| Parameter | Type | Description |

116| :------------- | :----------------------------------------------- | :------------------------------------------------------------------ |116| :------------- | :---------------------------------------------- | :------------------------------------------------------------------ |

117| `name` | `str` | Unique identifier for the tool |117| `name` | `str` | Unique identifier for the tool |

118| `description` | `str` | Human-readable description of what the tool does |118| `description` | `str` | Human-readable description of what the tool does |

119| `input_schema` | `type \| dict[str, Any]` | Schema defining the tool's input parameters (see below) |119| `input_schema` | `type \| dict[str, Any]` | Schema defining the tool's input parameters (see below) |

120| `annotations` | [`ToolAnnotations`](#tool-annotations)` \| None` | Optional MCP tool annotations providing behavioral hints to clients |120| `annotations` | [`ToolAnnotations`](#toolannotations)` \| None` | Optional MCP tool annotations providing behavioral hints to clients |

121 121 

122#### Input schema options122#### Input schema options

123 123 


267| `first_prompt` | `str \| None` | First meaningful user prompt in the session |267| `first_prompt` | `str \| None` | First meaningful user prompt in the session |

268| `git_branch` | `str \| None` | Git branch at the end of the session |268| `git_branch` | `str \| None` | Git branch at the end of the session |

269| `cwd` | `str \| None` | Working directory for the session |269| `cwd` | `str \| None` | Working directory for the session |

270| `tag` | `str \| None` | User-set session tag (see [`tag_session()`](#tag-session)) |270| `tag` | `str \| None` | User-set session tag (see [`tag_session()`](#tag_session)) |

271| `created_at` | `int \| None` | Session creation time in milliseconds since epoch |271| `created_at` | `int \| None` | Session creation time in milliseconds since epoch |

272 272 

273#### Example273#### Example


343| `session_id` | `str` | required | UUID of the session to look up |343| `session_id` | `str` | required | UUID of the session to look up |

344| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |344| `directory` | `str \| None` | `None` | Project directory path. When omitted, searches all project directories |

345 345 

346Returns [`SDKSessionInfo`](#return-type-sdk-session-info), or `None` if the session is not found.346Returns [`SDKSessionInfo`](#return-type-sdksessioninfo), or `None` if the session is not found.

347 347 

348#### Example348#### Example

349 349 


381 381 

382#### Example382#### Example

383 383 

384Rename the most recent session so it's easier to find later. The new title appears in [`SDKSessionInfo.custom_title`](#return-type-sdk-session-info) on subsequent reads.384Rename the most recent session so it's easier to find later. The new title appears in [`SDKSessionInfo.custom_title`](#return-type-sdksessioninfo) on subsequent reads.

385 385 

386```python theme={null}386```python theme={null}

387from claude_agent_sdk import list_sessions, rename_session387from claude_agent_sdk import list_sessions, rename_session


476| `set_permission_mode(mode)` | Change the permission mode for the current session |476| `set_permission_mode(mode)` | Change the permission mode for the current session |

477| `set_model(model)` | Change the model for the current session. Pass `None` to reset to default |477| `set_model(model)` | Change the model for the current session. Pass `None` to reset to default |

478| `rewind_files(user_message_id)` | Restore files to their state at the specified user message. Requires `enable_file_checkpointing=True`. See [File checkpointing](/en/agent-sdk/file-checkpointing) |478| `rewind_files(user_message_id)` | Restore files to their state at the specified user message. Requires `enable_file_checkpointing=True`. See [File checkpointing](/en/agent-sdk/file-checkpointing) |

479| `get_mcp_status()` | Get the status of all configured MCP servers. Returns [`McpStatusResponse`](#mcp-status-response) |479| `get_mcp_status()` | Get the status of all configured MCP servers. Returns [`McpStatusResponse`](#mcpstatusresponse) |

480| `reconnect_mcp_server(server_name)` | Retry connecting to an MCP server that failed or was disconnected |480| `reconnect_mcp_server(server_name)` | Retry connecting to an MCP server that failed or was disconnected |

481| `toggle_mcp_server(server_name, enabled)` | Enable or disable an MCP server mid-session. Disabling removes its tools |481| `toggle_mcp_server(server_name, enabled)` | Enable or disable an MCP server mid-session. Disabling removes its tools |

482| `stop_task(task_id)` | Stop a running background task. A [`TaskNotificationMessage`](#task-notification-message) with status `"stopped"` follows in the message stream |482| `stop_task(task_id)` | Stop a running background task. A [`TaskNotificationMessage`](#tasknotificationmessage) with status `"stopped"` follows in the message stream |

483| `get_server_info()` | Get server information including session ID and capabilities |483| `get_server_info()` | Get server information including session ID and capabilities |

484| `disconnect()` | Disconnect from Claude |484| `disconnect()` | Disconnect from Claude |

485 485 


757 allowed_tools: list[str] = field(default_factory=list)757 allowed_tools: list[str] = field(default_factory=list)

758 system_prompt: str | SystemPromptPreset | None = None758 system_prompt: str | SystemPromptPreset | None = None

759 mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)759 mcp_servers: dict[str, McpServerConfig] | str | Path = field(default_factory=dict)

760 strict_mcp_config: bool = False

760 permission_mode: PermissionMode | None = None761 permission_mode: PermissionMode | None = None

761 continue_conversation: bool = False762 continue_conversation: bool = False

762 resume: str | None = None763 resume: str | None = None


781 hooks: dict[HookEvent, list[HookMatcher]] | None = None782 hooks: dict[HookEvent, list[HookMatcher]] | None = None

782 user: str | None = None783 user: str | None = None

783 include_partial_messages: bool = False784 include_partial_messages: bool = False

785 include_hook_events: bool = False

784 fork_session: bool = False786 fork_session: bool = False

785 agents: dict[str, AgentDefinition] | None = None787 agents: dict[str, AgentDefinition] | None = None

786 setting_sources: list[SettingSource] | None = None788 setting_sources: list[SettingSource] | None = None


788 plugins: list[SdkPluginConfig] = field(default_factory=list)790 plugins: list[SdkPluginConfig] = field(default_factory=list)

789 max_thinking_tokens: int | None = None # Deprecated: use thinking instead791 max_thinking_tokens: int | None = None # Deprecated: use thinking instead

790 thinking: ThinkingConfig | None = None792 thinking: ThinkingConfig | None = None

791 effort: Literal["low", "medium", "high", "max"] | None = None793 effort: Literal["low", "medium", "high", "xhigh", "max"] | None = None

792 enable_file_checkpointing: bool = False794 enable_file_checkpointing: bool = False

795 session_store: SessionStore | None = None

796 session_store_flush: SessionStoreFlushMode = "batched"

793```797```

794 798 

795| Property | Type | Default | Description |799| Property | Type | Default | Description |

796| :---------------------------- | :------------------------------------------------ | :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |800| :---------------------------- | :------------------------------------------------------------------------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

797| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code's default tools |801| `tools` | `list[str] \| ToolsPreset \| None` | `None` | Tools configuration. Use `{"type": "preset", "preset": "claude_code"}` for Claude Code's default tools |

798| `allowed_tools` | `list[str]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permission_mode` and `can_use_tool`. Use `disallowed_tools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |802| `allowed_tools` | `list[str]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permission_mode` and `can_use_tool`. Use `disallowed_tools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |

799| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | System prompt configuration. Pass a string for custom prompt, or use `{"type": "preset", "preset": "claude_code"}` for Claude Code's system prompt. Add `"append"` to extend the preset |803| `system_prompt` | `str \| SystemPromptPreset \| None` | `None` | System prompt configuration. Pass a string for custom prompt, or use `{"type": "preset", "preset": "claude_code"}` for Claude Code's system prompt. Add `"append"` to extend the preset |

800| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP server configurations or path to config file |804| `mcp_servers` | `dict[str, McpServerConfig] \| str \| Path` | `{}` | MCP server configurations or path to config file |

805| `strict_mcp_config` | `bool` | `False` | When `True`, use only the servers passed in `mcp_servers` and ignore project `.mcp.json`, user settings, and plugin-provided MCP servers. Maps to the CLI `--strict-mcp-config` flag |

801| `permission_mode` | `PermissionMode \| None` | `None` | Permission mode for tool usage |806| `permission_mode` | `PermissionMode \| None` | `None` | Permission mode for tool usage |

802| `continue_conversation` | `bool` | `False` | Continue the most recent conversation |807| `continue_conversation` | `bool` | `False` | Continue the most recent conversation |

803| `resume` | `str \| None` | `None` | Session ID to resume |808| `resume` | `str \| None` | `None` | Session ID to resume |

804| `max_turns` | `int \| None` | `None` | Maximum agentic turns (tool-use round trips) |809| `max_turns` | `int \| None` | `None` | Maximum agentic turns (tool-use round trips) |

805| `max_budget_usd` | `float \| None` | `None` | Maximum budget in USD for the session |810| `max_budget_usd` | `float \| None` | `None` | Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](/en/agent-sdk/cost-tracking) for accuracy caveats |

806| `disallowed_tools` | `list[str]` | `[]` | Tools to always deny. Deny rules are checked first and override `allowed_tools` and `permission_mode` (including `bypassPermissions`) |811| `disallowed_tools` | `list[str]` | `[]` | Tools to always deny. Deny rules are checked first and override `allowed_tools` and `permission_mode` (including `bypassPermissions`) |

807| `enable_file_checkpointing` | `bool` | `False` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |812| `enable_file_checkpointing` | `bool` | `False` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |

808| `model` | `str \| None` | `None` | Claude model to use |813| `model` | `str \| None` | `None` | Claude model to use |

809| `fallback_model` | `str \| None` | `None` | Fallback model to use if the primary model fails |814| `fallback_model` | `str \| None` | `None` | Fallback model to use if the primary model fails |

810| `betas` | `list[SdkBeta]` | `[]` | Beta features to enable. See [`SdkBeta`](#sdk-beta) for available options |815| `betas` | `list[SdkBeta]` | `[]` | Beta features to enable. See [`SdkBeta`](#sdkbeta) for available options |

811| `output_format` | `dict[str, Any] \| None` | `None` | Output format for structured responses (e.g., `{"type": "json_schema", "schema": {...}}`). See [Structured outputs](/en/agent-sdk/structured-outputs) for details |816| `output_format` | `dict[str, Any] \| None` | `None` | Output format for structured responses (e.g., `{"type": "json_schema", "schema": {...}}`). See [Structured outputs](/en/agent-sdk/structured-outputs) for details |

812| `permission_prompt_tool_name` | `str \| None` | `None` | MCP tool name for permission prompts |817| `permission_prompt_tool_name` | `str \| None` | `None` | MCP tool name for permission prompts |

813| `cwd` | `str \| Path \| None` | `None` | Current working directory |818| `cwd` | `str \| Path \| None` | `None` | Current working directory |

814| `cli_path` | `str \| Path \| None` | `None` | Custom path to the Claude Code CLI executable |819| `cli_path` | `str \| Path \| None` | `None` | Custom path to the Claude Code CLI executable |

815| `settings` | `str \| None` | `None` | Path to settings file |820| `settings` | `str \| None` | `None` | Path to settings file |

816| `add_dirs` | `list[str \| Path]` | `[]` | Additional directories Claude can access |821| `add_dirs` | `list[str \| Path]` | `[]` | Additional directories Claude can access |

817| `env` | `dict[str, str]` | `{}` | Environment variables |822| `env` | `dict[str, str]` | `{}` | Environment variables merged on top of the inherited process environment. See [Environment variables](/en/env-vars) for variables the underlying CLI reads, and [Handle slow or stalled API responses](#handle-slow-or-stalled-api-responses) for timeout-related variables |

818| `extra_args` | `dict[str, str \| None]` | `{}` | Additional CLI arguments to pass directly to the CLI |823| `extra_args` | `dict[str, str \| None]` | `{}` | Additional CLI arguments to pass directly to the CLI |

819| `max_buffer_size` | `int \| None` | `None` | Maximum bytes when buffering CLI stdout |824| `max_buffer_size` | `int \| None` | `None` | Maximum bytes when buffering CLI stdout |

820| `debug_stderr` | `Any` | `sys.stderr` | *Deprecated* - File-like object for debug output. Use `stderr` callback instead |825| `debug_stderr` | `Any` | `sys.stderr` | *Deprecated* - File-like object for debug output. Use `stderr` callback instead |

821| `stderr` | `Callable[[str], None] \| None` | `None` | Callback function for stderr output from CLI |826| `stderr` | `Callable[[str], None] \| None` | `None` | Callback function for stderr output from CLI |

822| `can_use_tool` | [`CanUseTool`](#can-use-tool) ` \| None` | `None` | Tool permission callback function. See [Permission types](#can-use-tool) for details |827| `can_use_tool` | [`CanUseTool`](#canusetool) ` \| None` | `None` | Tool permission callback function. See [Permission types](#canusetool) for details |

823| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | Hook configurations for intercepting events |828| `hooks` | `dict[HookEvent, list[HookMatcher]] \| None` | `None` | Hook configurations for intercepting events |

824| `user` | `str \| None` | `None` | User identifier |829| `user` | `str \| None` | `None` | User identifier |

825| `include_partial_messages` | `bool` | `False` | Include partial message streaming events. When enabled, [`StreamEvent`](#stream-event) messages are yielded |830| `include_partial_messages` | `bool` | `False` | Include partial message streaming events. When enabled, [`StreamEvent`](#streamevent) messages are yielded |

831| `include_hook_events` | `bool` | `False` | Include hook lifecycle events in the message stream as `HookEventMessage` objects |

826| `fork_session` | `bool` | `False` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |832| `fork_session` | `bool` | `False` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |

827| `agents` | `dict[str, AgentDefinition] \| None` | `None` | Programmatically defined subagents |833| `agents` | `dict[str, AgentDefinition] \| None` | `None` | Programmatically defined subagents |

828| `plugins` | `list[SdkPluginConfig]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |834| `plugins` | `list[SdkPluginConfig]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |

829| `sandbox` | [`SandboxSettings`](#sandbox-settings) ` \| None` | `None` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandbox-settings) for details |835| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |

830| `setting_sources` | `list[SettingSource] \| None` | `None` (no settings) | Control which filesystem settings to load. When omitted, no settings are loaded. **Note:** Must include `"project"` to load CLAUDE.md files |836| `setting_sources` | `list[SettingSource] \| None` | `None` (CLI defaults: all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

837| `skills` | `list[str] \| Literal["all"] \| None` | `None` | Skills available to the session. Pass `"all"` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowed_tools`. See [Skills](/en/agent-sdk/skills) |

831| `max_thinking_tokens` | `int \| None` | `None` | *Deprecated* - Maximum tokens for thinking blocks. Use `thinking` instead |838| `max_thinking_tokens` | `int \| None` | `None` | *Deprecated* - Maximum tokens for thinking blocks. Use `thinking` instead |

832| `thinking` | [`ThinkingConfig`](#thinking-config) ` \| None` | `None` | Controls extended thinking behavior. Takes precedence over `max_thinking_tokens` |839| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | Controls extended thinking behavior. Takes precedence over `max_thinking_tokens` |

833| `effort` | `Literal["low", "medium", "high", "max"] \| None` | `None` | Effort level for thinking depth |840| `effort` | `Literal["low", "medium", "high", "xhigh", "max"] \| None` | `None` | Effort level for thinking depth |

841| `session_store` | [`SessionStore`](/en/agent-sdk/session-storage#the-sessionstore-interface) ` \| None` | `None` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |

842| `session_store_flush` | `Literal["batched", "eager"]` | `"batched"` | When to flush mirrored transcript entries to `session_store`. `"batched"` flushes once per turn or when the buffer fills; `"eager"` triggers a background flush after every frame. Ignored when `session_store` is `None` |

843 

844#### Handle slow or stalled API responses

845 

846The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through `ClaudeAgentOptions.env`:

847 

848```python theme={null}

849options = ClaudeAgentOptions(

850 env={

851 "API_TIMEOUT_MS": "120000",

852 "CLAUDE_CODE_MAX_RETRIES": "2",

853 "CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS": "120000",

854 },

855)

856```

857 

858* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.

859* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff.

860* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.

861* `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. Off by default. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.

834 862 

835### `OutputFormat`863### `OutputFormat`

836 864 


858 type: Literal["preset"]886 type: Literal["preset"]

859 preset: Literal["claude_code"]887 preset: Literal["claude_code"]

860 append: NotRequired[str]888 append: NotRequired[str]

889 exclude_dynamic_sections: NotRequired[bool]

861```890```

862 891 

863| Field | Required | Description |892| Field | Required | Description |

864| :------- | :------- | :------------------------------------------------------------ |893| :------------------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

865| `type` | Yes | Must be `"preset"` to use a preset system prompt |894| `type` | Yes | Must be `"preset"` to use a preset system prompt |

866| `preset` | Yes | Must be `"claude_code"` to use Claude Code's system prompt |895| `preset` | Yes | Must be `"claude_code"` to use Claude Code's system prompt |

867| `append` | No | Additional instructions to append to the preset system prompt |896| `append` | No | Additional instructions to append to the preset system prompt |

897| `exclude_dynamic_sections` | No | Move per-session context such as working directory, git status, and memory paths from the system prompt into the first user message. Improves prompt-cache reuse across users and machines. See [Modify system prompts](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |

868 898 

869### `SettingSource`899### `SettingSource`

870 900 


882 912 

883#### Default behavior913#### Default behavior

884 914 

885When `setting_sources` is **omitted** or **`None`**, the SDK does **not** load any filesystem settings. This provides isolation for SDK applications.915When `setting_sources` is omitted or `None`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. Managed policy settings are loaded in all cases. See [What settingSources does not control](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for inputs that are read regardless of this option, and how to disable them.

886 916 

887#### Why use setting\_sources917#### Why use setting\_sources

888 918 

889**Load all filesystem settings (legacy behavior):**919**Disable filesystem settings:**

890 920 

891```python theme={null}921```python theme={null}

892# Load all settings like SDK v0.0.x did922# Do not load user, project, or local settings from disk

893from claude_agent_sdk import query, ClaudeAgentOptions923from claude_agent_sdk import query, ClaudeAgentOptions

894 924 

895async for message in query(925async for message in query(

896 prompt="Analyze this code",926 prompt="Analyze this code",

897 options=ClaudeAgentOptions(927 options=ClaudeAgentOptions(

898 setting_sources=["user", "project", "local"] # Load all settings928 setting_sources=[]

929 ),

930):

931 print(message)

932```

933 

934<Note>

935 In Python SDK 0.1.59 and earlier, an empty list was treated the same as omitting the option, so `setting_sources=[]` did not disable filesystem settings. Upgrade to a newer release if you need an empty list to take effect. The TypeScript SDK is not affected.

936</Note>

937 

938**Load all filesystem settings explicitly:**

939 

940```python theme={null}

941from claude_agent_sdk import query, ClaudeAgentOptions

942 

943async for message in query(

944 prompt="Analyze this code",

945 options=ClaudeAgentOptions(

946 setting_sources=["user", "project", "local"]

899 ),947 ),

900):948):

901 print(message)949 print(message)


931**SDK-only applications:**979**SDK-only applications:**

932 980 

933```python theme={null}981```python theme={null}

934# Define everything programmatically (default behavior)982# Define everything programmatically.

935# No filesystem dependencies - setting_sources defaults to None983# Pass [] to opt out of filesystem setting sources.

936async for message in query(984async for message in query(

937 prompt="Review this PR",985 prompt="Review this PR",

938 options=ClaudeAgentOptions(986 options=ClaudeAgentOptions(

939 # setting_sources=None is the default, no need to specify987 setting_sources=[],

940 agents={...},988 agents={...},

941 mcp_servers={...},989 mcp_servers={...},

942 allowed_tools=["Read", "Grep", "Glob"],990 allowed_tools=["Read", "Grep", "Glob"],


956 "type": "preset",1004 "type": "preset",

957 "preset": "claude_code", # Use Claude Code's system prompt1005 "preset": "claude_code", # Use Claude Code's system prompt

958 },1006 },

959 setting_sources=["project"], # Required to load CLAUDE.md from project1007 setting_sources=["project"], # Loads CLAUDE.md from project

960 allowed_tools=["Read", "Write", "Edit"],1008 allowed_tools=["Read", "Write", "Edit"],

961 ),1009 ),

962):1010):


9712. Project settings (`.claude/settings.json`)10192. Project settings (`.claude/settings.json`)

9723. User settings (`~/.claude/settings.json`)10203. User settings (`~/.claude/settings.json`)

973 1021 

974Programmatic options (like `agents`, `allowed_tools`) always override filesystem settings.1022Programmatic options such as `agents` and `allowed_tools` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.

975 1023 

976### `AgentDefinition`1024### `AgentDefinition`

977 1025 


983 description: str1031 description: str

984 prompt: str1032 prompt: str

985 tools: list[str] | None = None1033 tools: list[str] | None = None

986 model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None1034 disallowedTools: list[str] | None = None

1035 model: str | None = None

987 skills: list[str] | None = None1036 skills: list[str] | None = None

988 memory: Literal["user", "project", "local"] | None = None1037 memory: Literal["user", "project", "local"] | None = None

989 mcpServers: list[str | dict[str, Any]] | None = None1038 mcpServers: list[str | dict[str, Any]] | None = None

1039 initialPrompt: str | None = None

1040 maxTurns: int | None = None

1041 background: bool | None = None

1042 effort: Literal["low", "medium", "high", "xhigh", "max"] | int | None = None

1043 permissionMode: PermissionMode | None = None

990```1044```

991 1045 

992| Field | Required | Description |1046| Field | Required | Description |

993| :------------ | :------- | :-------------------------------------------------------------------------------------------------- |1047| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- |

994| `description` | Yes | Natural language description of when to use this agent |1048| `description` | Yes | Natural language description of when to use this agent |

995| `prompt` | Yes | The agent's system prompt |1049| `prompt` | Yes | The agent's system prompt |

996| `tools` | No | Array of allowed tool names. If omitted, inherits all tools |1050| `tools` | No | Array of allowed tool names. If omitted, inherits all tools |

997| `model` | No | Model override for this agent. If omitted, uses the main model |1051| `disallowedTools` | No | Array of tool names to remove from the agent's tool set |

998| `skills` | No | List of skill names available to this agent |1052| `model` | No | Model override for this agent. Accepts an alias such as `"sonnet"`, `"opus"`, `"haiku"`, or `"inherit"`, or a full model ID. If omitted, uses the main model |

1053| `skills` | No | List of skill names to preload into the agent's context at startup. Unlisted skills remain invocable through the Skill tool |

999| `memory` | No | Memory source for this agent: `"user"`, `"project"`, or `"local"` |1054| `memory` | No | Memory source for this agent: `"user"`, `"project"`, or `"local"` |

1000| `mcpServers` | No | MCP servers available to this agent. Each entry is a server name or an inline `{name: config}` dict |1055| `mcpServers` | No | MCP servers available to this agent. Each entry is a server name or an inline `{name: config}` dict |

1056| `initialPrompt` | No | Auto-submitted as the first user turn when this agent runs as the main thread agent |

1057| `maxTurns` | No | Maximum number of agentic turns before the agent stops |

1058| `background` | No | Run this agent as a non-blocking background task when invoked |

1059| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer |

1060| `permissionMode` | No | Permission mode for tool execution within this agent. See [`PermissionMode`](#permissionmode) |

1061 

1062<Note>

1063 `AgentDefinition` field names use camelCase, such as `disallowedTools`, `permissionMode`, and `maxTurns`. These names map directly to the wire format shared with the TypeScript SDK. This differs from `ClaudeAgentOptions`, which uses Python snake\_case for the equivalent top-level fields such as `disallowed_tools` and `permission_mode`. Because `AgentDefinition` is a dataclass, passing a snake\_case keyword raises a `TypeError` at construction time.

1064</Note>

1001 1065 

1002### `PermissionMode`1066### `PermissionMode`

1003 1067 


1007PermissionMode = Literal[1071PermissionMode = Literal[

1008 "default", # Standard permission behavior1072 "default", # Standard permission behavior

1009 "acceptEdits", # Auto-accept file edits1073 "acceptEdits", # Auto-accept file edits

1010 "plan", # Planning mode - no execution1074 "plan", # Planning mode - read-only tools only

1011 "dontAsk", # Deny anything not pre-approved instead of prompting1075 "dontAsk", # Deny anything not pre-approved instead of prompting

1012 "bypassPermissions", # Bypass all permission checks (use with caution)1076 "bypassPermissions", # Bypass all permission checks (use with caution)

1013]1077]


1040class ToolPermissionContext:1104class ToolPermissionContext:

1041 signal: Any | None = None # Future: abort signal support1105 signal: Any | None = None # Future: abort signal support

1042 suggestions: list[PermissionUpdate] = field(default_factory=list)1106 suggestions: list[PermissionUpdate] = field(default_factory=list)

1107 blocked_path: str | None = None

1108 decision_reason: str | None = None

1109 title: str | None = None

1110 display_name: str | None = None

1111 description: str | None = None

1043```1112```

1044 1113 

1045| Field | Type | Description |1114| Field | Type | Description |

1046| :------------ | :----------------------- | :----------------------------------------- |1115| :---------------- | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1047| `signal` | `Any \| None` | Reserved for future abort signal support |1116| `signal` | `Any \| None` | Reserved for future abort signal support |

1048| `suggestions` | `list[PermissionUpdate]` | Permission update suggestions from the CLI |1117| `suggestions` | `list[PermissionUpdate]` | Permission update suggestions from the CLI. Bash prompts include a suggestion with the `localSettings` destination, so returning it in `updated_permissions` writes the rule to `.claude/settings.local.json` and persists across sessions. |

1118| `blocked_path` | `str \| None` | File path that triggered the permission request, when applicable. For example, when a Bash command tries to access a path outside allowed directories |

1119| `decision_reason` | `str \| None` | Reason this permission request was triggered. Forwarded from a PreToolUse hook's `permissionDecisionReason` when the hook returned `"ask"` |

1120| `title` | `str \| None` | Full permission prompt sentence, such as `Claude wants to read foo.txt`. Use as the primary prompt text when present |

1121| `display_name` | `str \| None` | Short noun phrase for the tool action, such as `Read file`, suitable for button labels |

1122| `description` | `str \| None` | Human-readable subtitle for the permission UI |

1049 1123 

1050### `PermissionResult`1124### `PermissionResult`

1051 1125 


1197Use with the `betas` field in `ClaudeAgentOptions` to enable beta features.1271Use with the `betas` field in `ClaudeAgentOptions` to enable beta features.

1198 1272 

1199<Warning>1273<Warning>

1200 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this header with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 4.6 or Claude Opus 4.6](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.1274 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this header with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 4.6, Claude Opus 4.6, or Claude Opus 4.7](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.

1201</Warning>1275</Warning>

1202 1276 

1203### `McpSdkServerConfig`1277### `McpSdkServerConfig`


1251 1325 

1252### `McpServerStatusConfig`1326### `McpServerStatusConfig`

1253 1327 

1254The configuration of an MCP server as reported by [`get_mcp_status()`](#methods). This is the union of all [`McpServerConfig`](#mcp-server-config) transport variants plus an output-only `claudeai-proxy` variant for servers proxied through claude.ai.1328The configuration of an MCP server as reported by [`get_mcp_status()`](#methods). This is the union of all [`McpServerConfig`](#mcpserverconfig) transport variants plus an output-only `claudeai-proxy` variant for servers proxied through claude.ai.

1255 1329 

1256```python theme={null}1330```python theme={null}

1257McpServerStatusConfig = (1331McpServerStatusConfig = (


1263)1337)

1264```1338```

1265 1339 

1266`McpSdkServerConfigStatus` is the serializable form of [`McpSdkServerConfig`](#mcp-sdk-server-config) with only `type` (`"sdk"`) and `name` (`str`) fields; the in-process `instance` is omitted. `McpClaudeAIProxyServerConfig` has `type` (`"claudeai-proxy"`), `url` (`str`), and `id` (`str`) fields.1340`McpSdkServerConfigStatus` is the serializable form of [`McpSdkServerConfig`](#mcpsdkserverconfig) with only `type` (`"sdk"`) and `name` (`str`) fields; the in-process `instance` is omitted. `McpClaudeAIProxyServerConfig` has `type` (`"claudeai-proxy"`), `url` (`str`), and `id` (`str`) fields.

1267 1341 

1268### `McpStatusResponse`1342### `McpStatusResponse`

1269 1343 


1276 1350 

1277### `McpServerStatus`1351### `McpServerStatus`

1278 1352 

1279Status of a connected MCP server, contained in [`McpStatusResponse`](#mcp-status-response).1353Status of a connected MCP server, contained in [`McpStatusResponse`](#mcpstatusresponse).

1280 1354 

1281```python theme={null}1355```python theme={null}

1282class McpServerStatus(TypedDict):1356class McpServerStatus(TypedDict):


1290```1364```

1291 1365 

1292| Field | Type | Description |1366| Field | Type | Description |

1293| :----------- | :-------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |1367| :----------- | :----------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1294| `name` | `str` | Server name |1368| `name` | `str` | Server name |

1295| `status` | `str` | One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"` |1369| `status` | `str` | One of `"connected"`, `"failed"`, `"needs-auth"`, `"pending"`, or `"disabled"` |

1296| `serverInfo` | `dict` (optional) | Server name and version (`{"name": str, "version": str}`) |1370| `serverInfo` | `dict` (optional) | Server name and version (`{"name": str, "version": str}`) |

1297| `error` | `str` (optional) | Error message if the server failed to connect |1371| `error` | `str` (optional) | Error message if the server failed to connect |

1298| `config` | [`McpServerStatusConfig`](#mcp-server-status-config) (optional) | Server configuration. Same shape as [`McpServerConfig`](#mcp-server-config) (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai |1372| `config` | [`McpServerStatusConfig`](#mcpserverstatusconfig) (optional) | Server configuration. Same shape as [`McpServerConfig`](#mcpserverconfig) (stdio, SSE, HTTP, or SDK), plus a `claudeai-proxy` variant for servers connected through claude.ai |

1299| `scope` | `str` (optional) | Configuration scope |1373| `scope` | `str` (optional) | Configuration scope |

1300| `tools` | `list` (optional) | Tools provided by this server, each with `name`, `description`, and `annotations` fields |1374| `tools` | `list` (optional) | Tools provided by this server, each with `name`, `description`, and `annotations` fields |

1301 1375 


1378```1452```

1379 1453 

1380| Field | Type | Description |1454| Field | Type | Description |

1381| :------------------- | :------------------------------------------------------------- | :------------------------------------------------------------------------------ |1455| :------------------- | :----------------------------------------------------------- | :----------------------------------------------------------------------------- |

1382| `content` | `list[ContentBlock]` | List of content blocks in the response |1456| `content` | `list[ContentBlock]` | List of content blocks in the response |

1383| `model` | `str` | Model that generated the response |1457| `model` | `str` | Model that generated the response |

1384| `parent_tool_use_id` | `str \| None` | Tool use ID if this is a nested response |1458| `parent_tool_use_id` | `str \| None` | Tool use ID if this is a nested response |

1385| `error` | [`AssistantMessageError`](#assistant-message-error) ` \| None` | Error type if the response encountered an error |1459| `error` | [`AssistantMessageError`](#assistantmessageerror) ` \| None` | Error type if the response encountered an error |

1386| `usage` | `dict[str, Any] \| None` | Per-message token usage (same keys as [`ResultMessage.usage`](#result-message)) |1460| `usage` | `dict[str, Any] \| None` | Per-message token usage (same keys as [`ResultMessage.usage`](#resultmessage)) |

1387| `message_id` | `str \| None` | API message ID. Multiple messages from one turn share the same ID |1461| `message_id` | `str \| None` | API message ID. Multiple messages from one turn share the same ID |

1388 1462 

1389### `AssistantMessageError`1463### `AssistantMessageError`


1426 is_error: bool1500 is_error: bool

1427 num_turns: int1501 num_turns: int

1428 session_id: str1502 session_id: str

1503 stop_reason: str | None = None

1429 total_cost_usd: float | None = None1504 total_cost_usd: float | None = None

1430 usage: dict[str, Any] | None = None1505 usage: dict[str, Any] | None = None

1431 result: str | None = None1506 result: str | None = None

1432 stop_reason: str | None = None

1433 structured_output: Any = None1507 structured_output: Any = None

1434 model_usage: dict[str, Any] | None = None1508 model_usage: dict[str, Any] | None = None

1509 permission_denials: list[Any] | None = None

1510 deferred_tool_use: DeferredToolUse | None = None

1511 errors: list[str] | None = None

1512 api_error_status: int | None = None

1513 uuid: str | None = None

1435```1514```

1436 1515 

1437The `usage` dict contains the following keys when present:1516The `usage` dict contains the following keys when present:


1443| `cache_creation_input_tokens` | `int` | Tokens used to create new cache entries. |1522| `cache_creation_input_tokens` | `int` | Tokens used to create new cache entries. |

1444| `cache_read_input_tokens` | `int` | Tokens read from existing cache entries. |1523| `cache_read_input_tokens` | `int` | Tokens read from existing cache entries. |

1445 1524 

1446The `model_usage` dict maps model names to per-model usage. The inner dict keys use camelCase because the value is passed through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](/en/agent-sdk/typescript#model-usage) type:1525The `model_usage` dict maps model names to per-model usage. The inner dict keys use camelCase because the value is passed through unmodified from the underlying CLI process, matching the TypeScript [`ModelUsage`](/en/agent-sdk/typescript#modelusage) type:

1447 1526 

1448| Key | Type | Description |1527| Key | Type | Description |

1449| -------------------------- | ------- | ------------------------------------------ |1528| -------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |

1450| `inputTokens` | `int` | Input tokens for this model. |1529| `inputTokens` | `int` | Input tokens for this model. |

1451| `outputTokens` | `int` | Output tokens for this model. |1530| `outputTokens` | `int` | Output tokens for this model. |

1452| `cacheReadInputTokens` | `int` | Cache read tokens for this model. |1531| `cacheReadInputTokens` | `int` | Cache read tokens for this model. |

1453| `cacheCreationInputTokens` | `int` | Cache creation tokens for this model. |1532| `cacheCreationInputTokens` | `int` | Cache creation tokens for this model. |

1454| `webSearchRequests` | `int` | Web search requests made by this model. |1533| `webSearchRequests` | `int` | Web search requests made by this model. |

1455| `costUSD` | `float` | Cost in USD for this model. |1534| `costUSD` | `float` | Estimated cost in USD for this model, computed client-side. See [Track cost and usage](/en/agent-sdk/cost-tracking) for billing caveats. |

1456| `contextWindow` | `int` | Context window size for this model. |1535| `contextWindow` | `int` | Context window size for this model. |

1457| `maxOutputTokens` | `int` | Maximum output token limit for this model. |1536| `maxOutputTokens` | `int` | Maximum output token limit for this model. |

1458 1537 


1489```1568```

1490 1569 

1491| Field | Type | Description |1570| Field | Type | Description |

1492| :---------------- | :---------------------------------- | :----------------------- |1571| :---------------- | :-------------------------------- | :----------------------- |

1493| `rate_limit_info` | [`RateLimitInfo`](#rate-limit-info) | Current rate limit state |1572| `rate_limit_info` | [`RateLimitInfo`](#ratelimitinfo) | Current rate limit state |

1494| `uuid` | `str` | Unique event identifier |1573| `uuid` | `str` | Unique event identifier |

1495| `session_id` | `str` | Session identifier |1574| `session_id` | `str` | Session identifier |

1496 1575 

1497### `RateLimitInfo`1576### `RateLimitInfo`

1498 1577 

1499Rate limit state carried by [`RateLimitEvent`](#rate-limit-event).1578Rate limit state carried by [`RateLimitEvent`](#ratelimitevent).

1500 1579 

1501```python theme={null}1580```python theme={null}

1502RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]1581RateLimitStatus = Literal["allowed", "allowed_warning", "rejected"]


1761```1840```

1762 1841 

1763<Note>1842<Note>

1764 The TypeScript SDK supports additional hook events not yet available in Python: `SessionStart`, `SessionEnd`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, and `WorktreeRemove`.1843 The TypeScript SDK supports additional hook events not yet available in Python: `SessionStart`, `SessionEnd`, `Setup`, `TeammateIdle`, `TaskCompleted`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, and `PostToolBatch`.

1765</Note>1844</Note>

1766 1845 

1767### `HookCallback`1846### `HookCallback`


1774 1853 

1775Parameters:1854Parameters:

1776 1855 

1777* `input`: Strongly-typed hook input with discriminated unions based on `hook_event_name` (see [`HookInput`](#hook-input))1856* `input`: Strongly-typed hook input with discriminated unions based on `hook_event_name` (see [`HookInput`](#hookinput))

1778* `tool_use_id`: Optional tool use identifier (for tool-related hooks)1857* `tool_use_id`: Optional tool use identifier (for tool-related hooks)

1779* `context`: Hook context with additional information1858* `context`: Hook context with additional information

1780 1859 

1781Returns a [`HookJSONOutput`](#hook-json-output) that may contain:1860Returns a [`HookJSONOutput`](#hookjsonoutput) that may contain:

1782 1861 

1783* `decision`: `"block"` to block the action1862* `decision`: `"block"` to block the action

1784* `systemMessage`: System message to add to the transcript1863* `systemMessage`: System message to add to the transcript


2088```python theme={null}2167```python theme={null}

2089class PreToolUseHookSpecificOutput(TypedDict):2168class PreToolUseHookSpecificOutput(TypedDict):

2090 hookEventName: Literal["PreToolUse"]2169 hookEventName: Literal["PreToolUse"]

2091 permissionDecision: NotRequired[Literal["allow", "deny", "ask"]]2170 permissionDecision: NotRequired[Literal["allow", "deny", "ask", "defer"]]

2092 permissionDecisionReason: NotRequired[str]2171 permissionDecisionReason: NotRequired[str]

2093 updatedInput: NotRequired[dict[str, Any]]2172 updatedInput: NotRequired[dict[str, Any]]

2094 additionalContext: NotRequired[str]2173 additionalContext: NotRequired[str]


2097class PostToolUseHookSpecificOutput(TypedDict):2176class PostToolUseHookSpecificOutput(TypedDict):

2098 hookEventName: Literal["PostToolUse"]2177 hookEventName: Literal["PostToolUse"]

2099 additionalContext: NotRequired[str]2178 additionalContext: NotRequired[str]

2179 updatedToolOutput: NotRequired[Any]

2100 updatedMCPToolOutput: NotRequired[Any]2180 updatedMCPToolOutput: NotRequired[Any]

2101 2181 

2102 2182 


2226{2306{

2227 "result": str, # Final result from the subagent2307 "result": str, # Final result from the subagent

2228 "usage": dict | None, # Token usage statistics2308 "usage": dict | None, # Token usage statistics

2229 "total_cost_usd": float | None, # Total cost in USD2309 "total_cost_usd": float | None, # Estimated total cost in USD

2230 "duration_ms": int | None, # Execution duration in milliseconds2310 "duration_ms": int | None, # Execution duration in milliseconds

2231}2311}

2232```2312```


2254 "multiSelect": bool, # Set to true to allow multiple selections2334 "multiSelect": bool, # Set to true to allow multiple selections

2255 }2335 }

2256 ],2336 ],

2257 "answers": dict | None, # User answers populated by the permission system2337 "answers": dict[str, str | list[str]] | None,

2338 # User answers populated by the permission system. Multi-select

2339 # answers may be a list of labels or a comma-joined string

2258}2340}

2259```2341```

2260 2342 


3071```3153```

3072 3154 

3073| Property | Type | Default | Description |3155| Property | Type | Default | Description |

3074| :-------------------------- | :------------------------------------------------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |3156| :-------------------------- | :---------------------------------------------------- | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

3075| `enabled` | `bool` | `False` | Enable sandbox mode for command execution |3157| `enabled` | `bool` | `False` | Enable sandbox mode for command execution |

3076| `autoAllowBashIfSandboxed` | `bool` | `True` | Auto-approve bash commands when sandbox is enabled |3158| `autoAllowBashIfSandboxed` | `bool` | `True` | Auto-approve bash commands when sandbox is enabled |

3077| `excludedCommands` | `list[str]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `["docker"]`). These run unsandboxed automatically without model involvement |3159| `excludedCommands` | `list[str]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `["docker"]`). These run unsandboxed automatically without model involvement |

3078| `allowUnsandboxedCommands` | `bool` | `True` | Allow the model to request running commands outside the sandbox. When `True`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |3160| `allowUnsandboxedCommands` | `bool` | `True` | Allow the model to request running commands outside the sandbox. When `True`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |

3079| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `None` | Network-specific sandbox configuration |3161| `network` | [`SandboxNetworkConfig`](#sandboxnetworkconfig) | `None` | Network-specific sandbox configuration |

3080| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandbox-ignore-violations) | `None` | Configure which sandbox violations to ignore |3162| `ignoreViolations` | [`SandboxIgnoreViolations`](#sandboxignoreviolations) | `None` | Configure which sandbox violations to ignore |

3081| `enableWeakerNestedSandbox` | `bool` | `False` | Enable a weaker nested sandbox for compatibility |3163| `enableWeakerNestedSandbox` | `bool` | `False` | Enable a weaker nested sandbox for compatibility |

3082 3164 

3083<Note>

3084 **Filesystem and network access restrictions** are NOT configured via sandbox settings. Instead, they are derived from [permission rules](/en/settings#permission-settings):

3085 

3086 * **Filesystem read restrictions**: Read deny rules

3087 * **Filesystem write restrictions**: Edit allow/deny rules

3088 * **Network restrictions**: WebFetch allow/deny rules

3089 

3090 Use sandbox settings for command execution sandboxing, and permission rules for filesystem and network access control.

3091</Note>

3092 

3093#### Example usage3165#### Example usage

3094 3166 

3095```python theme={null}3167```python theme={null}


3118 3190 

3119```python theme={null}3191```python theme={null}

3120class SandboxNetworkConfig(TypedDict, total=False):3192class SandboxNetworkConfig(TypedDict, total=False):

3121 allowLocalBinding: bool3193 allowedDomains: list[str]

3194 deniedDomains: list[str]

3195 allowManagedDomainsOnly: bool

3122 allowUnixSockets: list[str]3196 allowUnixSockets: list[str]

3123 allowAllUnixSockets: bool3197 allowAllUnixSockets: bool

3198 allowLocalBinding: bool

3199 allowMachLookup: list[str]

3124 httpProxyPort: int3200 httpProxyPort: int

3125 socksProxyPort: int3201 socksProxyPort: int

3126```3202```

3127 3203 

3128| Property | Type | Default | Description |3204| Property | Type | Default | Description |

3129| :-------------------- | :---------- | :------ | :---------------------------------------------------------------- |3205| :------------------------ | :---------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

3130| `allowLocalBinding` | `bool` | `False` | Allow processes to bind to local ports (e.g., for dev servers) |3206| `allowedDomains` | `list[str]` | `[]` | Domain names that sandboxed processes can access |

3207| `deniedDomains` | `list[str]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |

3208| `allowManagedDomainsOnly` | `bool` | `False` | Managed-settings only: when set in managed settings, ignore `allowedDomains` from non-managed settings sources. Has no effect when set via SDK options |

3131| `allowUnixSockets` | `list[str]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |3209| `allowUnixSockets` | `list[str]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |

3132| `allowAllUnixSockets` | `bool` | `False` | Allow access to all Unix sockets |3210| `allowAllUnixSockets` | `bool` | `False` | Allow access to all Unix sockets |

3211| `allowLocalBinding` | `bool` | `False` | Allow processes to bind to local ports (e.g., for dev servers) |

3212| `allowMachLookup` | `list[str]` | `[]` | macOS only: XPC/Mach service names to allow. Supports a trailing wildcard |

3133| `httpProxyPort` | `int` | `None` | HTTP proxy port for network requests |3213| `httpProxyPort` | `int` | `None` | HTTP proxy port for network requests |

3134| `socksProxyPort` | `int` | `None` | SOCKS proxy port for network requests |3214| `socksProxyPort` | `int` | `None` | SOCKS proxy port for network requests |

3135 3215 

3216<Note>

3217 The built-in sandbox proxy enforces the network allowlist based on the requested hostname and does not terminate or inspect TLS traffic, so techniques such as [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting) can potentially bypass it. See [Sandboxing security limitations](/en/sandboxing#security-limitations) for details and [Secure deployment](/en/agent-sdk/secure-deployment#traffic-forwarding) for configuring a TLS-terminating proxy.

3218</Note>

3219 

3136### `SandboxIgnoreViolations`3220### `SandboxIgnoreViolations`

3137 3221 

3138Configuration for ignoring specific sandbox violations.3222Configuration for ignoring specific sandbox violations.

Details

59 ```59 ```

60 </Tab>60 </Tab>

61 </Tabs>61 </Tabs>

62 

63 <Note>

64 The TypeScript SDK bundles a native Claude Code binary for your platform as an optional dependency, so you don't need to install Claude Code separately.

65 </Note>

62 </Step>66 </Step>

63 67 

64 <Step title="Set your API key">68 <Step title="Set your API key">


169 173 

1702. **`prompt`**: what you want Claude to do. Claude figures out which tools to use based on the task.1742. **`prompt`**: what you want Claude to do. Claude figures out which tools to use based on the task.

171 175 

1723. **`options`**: configuration for the agent. This example uses `allowedTools` to pre-approve `Read`, `Edit`, and `Glob`, and `permissionMode: "acceptEdits"` to auto-approve file changes. Other options include `systemPrompt`, `mcpServers`, and more. See all options for [Python](/en/agent-sdk/python#claude-agent-options) or [TypeScript](/en/agent-sdk/typescript#options).1763. **`options`**: configuration for the agent. This example uses `allowedTools` to pre-approve `Read`, `Edit`, and `Glob`, and `permissionMode: "acceptEdits"` to auto-approve file changes. Other options include `systemPrompt`, `mcpServers`, and more. See all options for [Python](/en/agent-sdk/python#claudeagentoptions) or [TypeScript](/en/agent-sdk/typescript#options).

173 177 

174The `async for` loop keeps running as Claude thinks, calls tools, observes results, and decides what to do next. Each iteration yields a message: Claude's reasoning, a tool call, a tool result, or the final outcome. The SDK handles the orchestration (tool execution, context management, retries) so you just consume the stream. The loop ends when Claude finishes the task or hits an error.178The `async for` loop keeps running as Claude thinks, calls tools, observes results, and decides what to do next. Each iteration yields a message: Claude's reasoning, a tool call, a tool result, or the final outcome. The SDK handles the orchestration (tool execution, context management, retries) so you just consume the stream. The loop ends when Claude finishes the task or hits an error.

175 179 


305 309 

306The example above uses `acceptEdits` mode, which auto-approves file operations so the agent can run without interactive prompts. If you want to prompt users for approval, use `default` mode and provide a [`canUseTool` callback](/en/agent-sdk/user-input) that collects user input. For more control, see [Permissions](/en/agent-sdk/permissions).310The example above uses `acceptEdits` mode, which auto-approves file operations so the agent can run without interactive prompts. If you want to prompt users for approval, use `default` mode and provide a [`canUseTool` callback](/en/agent-sdk/user-input) that collects user input. For more control, see [Permissions](/en/agent-sdk/permissions).

307 311 

312## Troubleshooting

313 

314### API error `thinking.type.enabled` is not supported for this model

315 

316Claude Opus 4.7 replaces `thinking.type.enabled` with `thinking.type.adaptive`. Older Agent SDK versions fail with the following API error when you select `claude-opus-4-7`:

317 

318```text theme={null}

319API Error: 400 {"type":"invalid_request_error","message":"\"thinking.type.enabled\" is not supported for this model. Use \"thinking.type.adaptive\" and \"output_config.effort\" to control thinking behavior."}

320```

321 

322Upgrade to Agent SDK v0.2.111 or later to use Opus 4.7.

323 

308## Next steps324## Next steps

309 325 

310Now that you've created your first agent, learn how to extend its capabilities and tailor it to your use case:326Now that you've created your first agent, learn how to extend its capabilities and tailor it to your use case:

Details

16 16 

17## Threat model17## Threat model

18 18 

19Agents can take unintended actions due to prompt injection (instructions embedded in content they process) or model error. Claude models are designed to resist this, and as analyzed in the [model card](https://www.anthropic.com/claude-opus-4-6-system-card), Claude Opus 4.6 is the most robust frontier model available.19Agents can take unintended actions due to prompt injection (instructions embedded in content they process) or model error. Claude models are designed to resist this; see the [model overview](https://platform.claude.com/docs/en/about-claude/models/overview) and the system card for the model you deploy for evaluation details.

20 20 

21Defense in depth is still good practice though. For example, if an agent processes a malicious file that instructs it to send customer data to an external server, network controls can block that request entirely.21Defense in depth is still good practice though. For example, if an agent processes a malicious file that instructs it to send customer data to an external server, network controls can block that request entirely.

22 22 


25Claude Code includes several security features that address common concerns. See the [security documentation](/en/security) for full details.25Claude Code includes several security features that address common concerns. See the [security documentation](/en/security) for full details.

26 26 

27* **Permissions system**: Every tool and bash command can be configured to allow, block, or prompt the user for approval. Use glob patterns to create rules like "allow all npm commands" or "block any command with sudo". Organizations can set policies that apply across all users. See [permissions](/en/permissions).27* **Permissions system**: Every tool and bash command can be configured to allow, block, or prompt the user for approval. Use glob patterns to create rules like "allow all npm commands" or "block any command with sudo". Organizations can set policies that apply across all users. See [permissions](/en/permissions).

28* **Static analysis**: Before executing bash commands, Claude Code runs static analysis to identify potentially risky operations. Commands that modify system files or access sensitive directories are flagged and require explicit user approval.28* **Command parsing for permissions**: Before executing bash commands, Claude Code parses them into an AST and matches the result against your permission rules. Commands that cannot be parsed cleanly, or that do not match an allow rule, require explicit approval. A small set of constructs such as `eval` always require approval regardless of allow rules. This is a permission gate, not a sandbox; it does not infer whether a command is dangerous from its target path or effects.

29* **Web search summarization**: Search results are summarized rather than passing raw content directly into the context, reducing the risk of prompt injection from malicious web content.29* **Web search summarization**: Search results are summarized rather than passing raw content directly into the context, reducing the risk of prompt injection from malicious web content.

30* **Sandbox mode**: Bash commands can run in a sandboxed environment that restricts filesystem and network access. See the [sandboxing documentation](/en/sandboxing) for details.30* **Sandbox mode**: Bash commands can run in a sandboxed environment that restricts filesystem and network access. See the [sandboxing documentation](/en/sandboxing) for details.

31 31 


100 100 

1011. **Same-host kernel**: Unlike VMs, sandboxed processes share the host kernel. A kernel vulnerability could theoretically enable escape. For some threat models this is acceptable, but if you need kernel-level isolation, use gVisor or a separate VM.1011. **Same-host kernel**: Unlike VMs, sandboxed processes share the host kernel. A kernel vulnerability could theoretically enable escape. For some threat models this is acceptable, but if you need kernel-level isolation, use gVisor or a separate VM.

102 102 

1032. **No TLS inspection**: The proxy allowlists domains but doesn't inspect encrypted traffic. If the agent has permissive credentials for an allowed domain, ensure it isn't possible to use that domain to trigger other network requests or to exfiltrate data.1032. **No TLS inspection**: The proxy allowlists domains based on the client-supplied hostname and does not terminate or inspect encrypted traffic. Code running inside the sandbox can potentially use [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting) or similar techniques to reach hosts outside the allowlist. If your threat model requires stronger guarantees, configure a [TLS-terminating proxy](#traffic-forwarding). See the [sandboxing security limitations](/en/sandboxing#security-limitations) for more detail. Separately, if the agent has permissive credentials for an allowed domain, ensure it cannot use that domain to trigger other network requests or to exfiltrate data.

104 104 

105For many single-developer and CI/CD use cases, sandbox-runtime raises the bar significantly with minimal setup. The sections below cover containers and VMs for deployments requiring stronger isolation.105For many single-developer and CI/CD use cases, sandbox-runtime raises the bar significantly with minimal setup. The sections below cover containers and VMs for deployments requiring stronger isolation.

106 106 

Details

31 31 

32### Continue, resume, and fork32### Continue, resume, and fork

33 33 

34Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options) in Python, [`Options`](/en/agent-sdk/typescript#options) in TypeScript).34Continue, resume, and fork are option fields you set on `query()` ([`ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions) in Python, [`Options`](/en/agent-sdk/typescript#options) in TypeScript).

35 35 

36**Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session:36**Continue** and **resume** both pick up an existing session and add to it. The difference is how they find that session:

37 37 


46 46 

47### Python: `ClaudeSDKClient`47### Python: `ClaudeSDKClient`

48 48 

49[`ClaudeSDKClient`](/en/agent-sdk/python#claude-sdk-client) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](/en/agent-sdk/python#claude-sdk-client) to iterate over the messages for the current query. The client must be used as an async context manager.49[`ClaudeSDKClient`](/en/agent-sdk/python#claudesdkclient) handles session IDs internally. Each call to `client.query()` automatically continues the same session. Call [`client.receive_response()`](/en/agent-sdk/python#claudesdkclient) to iterate over the messages for the current query. The client must be used as an async context manager.

50 50 

51This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID:51This example runs two queries against the same `client`. The first asks the agent to analyze a module; the second asks it to refactor that module. Because both calls go through the same client instance, the second query has full context from the first without any explicit `resume` or session ID:

52 52 


96asyncio.run(main())96asyncio.run(main())

97```97```

98 98 

99See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claude-sdk-client) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.99See the [Python SDK reference](/en/agent-sdk/python#choosing-between-query-and-claudesdkclient) for details on when to use `ClaudeSDKClient` vs the standalone `query()` function.

100 100 

101### TypeScript: `continue: true`101### TypeScript: `continue: true`

102 102 


132```132```

133 133 

134<Note>134<Note>

135 There's also a [V2 preview](/en/agent-sdk/typescript-v2-preview) of the TypeScript SDK that provides `createSession()` with a `send` / `stream` pattern, closer to Python's `ClaudeSDKClient` in feel. V2 is unstable and its APIs may change; the rest of this documentation uses the stable V1 `query()` function.135 The experimental [V2 session API](/en/agent-sdk/typescript-v2-preview), which provided `createSession()` with a `send` / `stream` pattern, is deprecated. Use the V1 `query()` function and the session options described on this page instead.

136</Note>136</Note>

137 137 

138## Use session options with `query()`138## Use session options with `query()`

139 139 

140### Capture the session ID140### Capture the session ID

141 141 

142Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](/en/agent-sdk/python#result-message) in Python, [`SDKResultMessage`](/en/agent-sdk/typescript#sdk-result-message) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it's nested inside `SystemMessage.data`.142Resume and fork require a session ID. Read it from the `session_id` field on the result message ([`ResultMessage`](/en/agent-sdk/python#resultmessage) in Python, [`SDKResultMessage`](/en/agent-sdk/typescript#sdkresultmessage) in TypeScript), which is present on every result regardless of success or error. In TypeScript the ID is also available earlier as a direct field on the init `SystemMessage`; in Python it's nested inside `SystemMessage.data`.

143 143 

144<CodeGroup>144<CodeGroup>

145 ```python Python theme={null}145 ```python Python theme={null}


233 If a `resume` call returns a fresh session instead of the expected history, the most common cause is a mismatched `cwd`. Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, where `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-` (so `/Users/me/proj` becomes `-Users-me-proj`). If your resume call runs from a different directory, the SDK looks in the wrong place. The session file also needs to exist on the current machine.233 If a `resume` call returns a fresh session instead of the expected history, the most common cause is a mismatched `cwd`. Sessions are stored under `~/.claude/projects/<encoded-cwd>/*.jsonl`, where `<encoded-cwd>` is the absolute working directory with every non-alphanumeric character replaced by `-` (so `/Users/me/proj` becomes `-Users-me-proj`). If your resume call runs from a different directory, the SDK looks in the wrong place. The session file also needs to exist on the current machine.

234</Tip>234</Tip>

235 235 

236To resume sessions across machines or in serverless environments, mirror transcripts to shared storage with a [`SessionStore` adapter](/en/agent-sdk/session-storage).

237 

236### Fork to explore alternatives238### Fork to explore alternatives

237 239 

238Forking creates a new session that starts with a copy of the original's history but diverges from that point. The fork gets its own session ID; the original's ID and history stay unchanged. You end up with two independent sessions you can resume separately.240Forking creates a new session that starts with a copy of the original's history but diverges from that point. The fork gets its own session ID; the original's ID and history stay unchanged. You end up with two independent sessions you can resume separately.


310* **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match.312* **Move the session file.** Persist `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl` from the first run and restore it to the same path on the new host before calling `resume`. The `cwd` must match.

311* **Don't rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session's prompt. This is often more robust than shipping transcript files around.313* **Don't rely on session resume.** Capture the results you need (analysis output, decisions, file diffs) as application state and pass them into a fresh session's prompt. This is often more robust than shipping transcript files around.

312 314 

313Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](/en/agent-sdk/typescript#list-sessions) and [`getSessionMessages()`](/en/agent-sdk/typescript#get-session-messages) in TypeScript, [`list_sessions()`](/en/agent-sdk/python#list-sessions) and [`get_session_messages()`](/en/agent-sdk/python#get-session-messages) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers.315Both SDKs expose functions for enumerating sessions on disk and reading their messages: [`listSessions()`](/en/agent-sdk/typescript#listsessions) and [`getSessionMessages()`](/en/agent-sdk/typescript#getsessionmessages) in TypeScript, [`list_sessions()`](/en/agent-sdk/python#list_sessions) and [`get_session_messages()`](/en/agent-sdk/python#get_session_messages) in Python. Use them to build custom session pickers, cleanup logic, or transcript viewers.

314 316 

315Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](/en/agent-sdk/python#get-session-info), [`rename_session()`](/en/agent-sdk/python#rename-session), and [`tag_session()`](/en/agent-sdk/python#tag-session) in Python, and [`getSessionInfo()`](/en/agent-sdk/typescript#get-session-info), [`renameSession()`](/en/agent-sdk/typescript#rename-session), and [`tagSession()`](/en/agent-sdk/typescript#tag-session) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.317Both SDKs also expose functions for looking up and mutating individual sessions: [`get_session_info()`](/en/agent-sdk/python#get_session_info), [`rename_session()`](/en/agent-sdk/python#rename_session), and [`tag_session()`](/en/agent-sdk/python#tag_session) in Python, and [`getSessionInfo()`](/en/agent-sdk/typescript#getsessioninfo), [`renameSession()`](/en/agent-sdk/typescript#renamesession), and [`tagSession()`](/en/agent-sdk/typescript#tagsession) in TypeScript. Use them to organize sessions by tag or give them human-readable titles.

316 318 

317## Related resources319## Related resources

318 320 

319* [How the agent loop works](/en/agent-sdk/agent-loop): Understand turns, messages, and context accumulation within a session321* [How the agent loop works](/en/agent-sdk/agent-loop): Understand turns, messages, and context accumulation within a session

320* [File checkpointing](/en/agent-sdk/file-checkpointing): Track and revert file changes across sessions322* [File checkpointing](/en/agent-sdk/file-checkpointing): Track and revert file changes across sessions

321* [Python `ClaudeAgentOptions`](/en/agent-sdk/python#claude-agent-options): Full session option reference for Python323* [Python `ClaudeAgentOptions`](/en/agent-sdk/python#claudeagentoptions): Full session option reference for Python

322* [TypeScript `Options`](/en/agent-sdk/typescript#options): Full session option reference for TypeScript324* [TypeScript `Options`](/en/agent-sdk/typescript#options): Full session option reference for TypeScript

Details

17When using the Claude Agent SDK, Skills are:17When using the Claude Agent SDK, Skills are:

18 18 

191. **Defined as filesystem artifacts**: Created as `SKILL.md` files in specific directories (`.claude/skills/`)191. **Defined as filesystem artifacts**: Created as `SKILL.md` files in specific directories (`.claude/skills/`)

202. **Loaded from filesystem**: Skills are loaded from configured filesystem locations. You must specify `settingSources` (TypeScript) or `setting_sources` (Python) to load Skills from the filesystem202. **Loaded from filesystem**: Skills are loaded from filesystem locations governed by `settingSources` (TypeScript) or `setting_sources` (Python)

213. **Automatically discovered**: Once filesystem settings are loaded, Skill metadata is discovered at startup from user and project directories; full content loaded when triggered213. **Automatically discovered**: Once filesystem settings are loaded, Skill metadata is discovered at startup from user and project directories; full content loaded when triggered

224. **Model-invoked**: Claude autonomously chooses when to use them based on context224. **Model-invoked**: Claude autonomously chooses when to use them based on context

235. **Enabled via allowed\_tools**: Add `"Skill"` to your `allowed_tools` to enable Skills235. **Filtered via the `skills` option**: Discovered skills are enabled by default. Pass a list of skill names, `"all"`, or `[]` to control which are available in the session

24 24 

25Unlike subagents (which can be defined programmatically), Skills must be created as filesystem artifacts. The SDK does not provide a programmatic API for registering Skills.25Unlike subagents (which can be defined programmatically), Skills must be created as filesystem artifacts. The SDK does not provide a programmatic API for registering Skills.

26 26 

27<Note>27<Note>

28 **Default behavior**: By default, the SDK does not load any filesystem settings. To use Skills, you must explicitly configure `settingSources: ['user', 'project']` (TypeScript) or `setting_sources=["user", "project"]` (Python) in your options.28 Skills are discovered through the filesystem setting sources. With default `query()` options, the SDK loads user and project sources, so skills in `~/.claude/skills/` and `<cwd>/.claude/skills/` are available. If you set `settingSources` explicitly, include `'user'` or `'project'` to keep skill discovery, or use the [`plugins` option](/en/agent-sdk/plugins) to load skills from a specific path.

29</Note>29</Note>

30 30 

31## Using Skills with the SDK31## Using Skills with the SDK

32 32 

33To use Skills with the SDK, you need to:33Set the `skills` option on `query()` to control which Skills are available to the session. When omitted, discovered Skills are enabled and the Skill tool is available, matching CLI behavior. Pass `"all"` to enable every discovered Skill, a list of Skill names to enable only those, or `[]` to disable all. When you set `skills`, the SDK enables the Skill tool automatically, so you do not need to list it in `allowedTools`.

34 34 

351. Include `"Skill"` in your `allowed_tools` configuration35Once configured, Claude automatically discovers Skills from the filesystem and invokes them when relevant to the user's request.

362. Configure `settingSources`/`setting_sources` to load Skills from the filesystem

37 

38Once configured, Claude automatically discovers Skills from the specified directories and invokes them when relevant to the user's request.

39 36 

40<CodeGroup>37<CodeGroup>

41 ```python Python theme={null}38 ```python Python theme={null}


47 options = ClaudeAgentOptions(44 options = ClaudeAgentOptions(

48 cwd="/path/to/project", # Project with .claude/skills/45 cwd="/path/to/project", # Project with .claude/skills/

49 setting_sources=["user", "project"], # Load Skills from filesystem46 setting_sources=["user", "project"], # Load Skills from filesystem

50 allowed_tools=["Skill", "Read", "Write", "Bash"], # Enable Skill tool47 skills="all", # Enable every discovered Skill

48 allowed_tools=["Read", "Write", "Bash"],

51 )49 )

52 50 

53 async for message in query(51 async for message in query(


67 options: {65 options: {

68 cwd: "/path/to/project", // Project with .claude/skills/66 cwd: "/path/to/project", // Project with .claude/skills/

69 settingSources: ["user", "project"], // Load Skills from filesystem67 settingSources: ["user", "project"], // Load Skills from filesystem

70 allowedTools: ["Skill", "Read", "Write", "Bash"] // Enable Skill tool68 skills: "all", // Enable every discovered Skill

69 allowedTools: ["Read", "Write", "Bash"]

71 }70 }

72 })) {71 })) {

73 console.log(message);72 console.log(message);


75 ```74 ```

76</CodeGroup>75</CodeGroup>

77 76 

77To enable only specific Skills, pass their names. Names match the `name` field in `SKILL.md` or the Skill's directory name. Use `plugin:skill` for plugin-provided Skills.

78 

79<CodeGroup>

80 ```python Python theme={null}

81 options = ClaudeAgentOptions(skills=["pdf", "docx"])

82 ```

83 

84 ```typescript TypeScript theme={null}

85 const options = { skills: ["pdf", "docx"] };

86 ```

87</CodeGroup>

88 

89The `skills` option is a context filter, not a sandbox. Unlisted Skills are hidden from the model and rejected by the Skill tool, but their files remain on disk and are reachable through Read and Bash.

90 

78## Skill Locations91## Skill Locations

79 92 

80Skills are loaded from filesystem directories based on your `settingSources`/`setting_sources` configuration:93Skills are loaded from filesystem directories based on your `settingSources`/`setting_sources` configuration:


117 ```python Python theme={null}130 ```python Python theme={null}

118 options = ClaudeAgentOptions(131 options = ClaudeAgentOptions(

119 setting_sources=["user", "project"], # Load Skills from filesystem132 setting_sources=["user", "project"], # Load Skills from filesystem

120 allowed_tools=["Skill", "Read", "Grep", "Glob"],133 skills="all",

134 allowed_tools=["Read", "Grep", "Glob"],

121 )135 )

122 136 

123 async for message in query(prompt="Analyze the codebase structure", options=options):137 async for message in query(prompt="Analyze the codebase structure", options=options):


129 prompt: "Analyze the codebase structure",143 prompt: "Analyze the codebase structure",

130 options: {144 options: {

131 settingSources: ["user", "project"], // Load Skills from filesystem145 settingSources: ["user", "project"], // Load Skills from filesystem

132 allowedTools: ["Skill", "Read", "Grep", "Glob"],146 skills: "all",

147 allowedTools: ["Read", "Grep", "Glob"],

133 permissionMode: "dontAsk" // Deny anything not in allowedTools148 permissionMode: "dontAsk" // Deny anything not in allowedTools

134 }149 }

135 })) {150 })) {


146 ```python Python theme={null}161 ```python Python theme={null}

147 options = ClaudeAgentOptions(162 options = ClaudeAgentOptions(

148 setting_sources=["user", "project"], # Load Skills from filesystem163 setting_sources=["user", "project"], # Load Skills from filesystem

149 allowed_tools=["Skill"],164 skills="all",

150 )165 )

151 166 

152 async for message in query(prompt="What Skills are available?", options=options):167 async for message in query(prompt="What Skills are available?", options=options):


158 prompt: "What Skills are available?",173 prompt: "What Skills are available?",

159 options: {174 options: {

160 settingSources: ["user", "project"], // Load Skills from filesystem175 settingSources: ["user", "project"], // Load Skills from filesystem

161 allowedTools: ["Skill"]176 skills: "all"

162 }177 }

163 })) {178 })) {

164 console.log(message);179 console.log(message);


177 options = ClaudeAgentOptions(192 options = ClaudeAgentOptions(

178 cwd="/path/to/project",193 cwd="/path/to/project",

179 setting_sources=["user", "project"], # Load Skills from filesystem194 setting_sources=["user", "project"], # Load Skills from filesystem

180 allowed_tools=["Skill", "Read", "Bash"],195 skills="all",

196 allowed_tools=["Read", "Bash"],

181 )197 )

182 198 

183 async for message in query(prompt="Extract text from invoice.pdf", options=options):199 async for message in query(prompt="Extract text from invoice.pdf", options=options):


190 options: {206 options: {

191 cwd: "/path/to/project",207 cwd: "/path/to/project",

192 settingSources: ["user", "project"], // Load Skills from filesystem208 settingSources: ["user", "project"], // Load Skills from filesystem

193 allowedTools: ["Skill", "Read", "Bash"]209 skills: "all",

210 allowedTools: ["Read", "Bash"]

194 }211 }

195 })) {212 })) {

196 console.log(message);213 console.log(message);


204 221 

205### Skills Not Found222### Skills Not Found

206 223 

207**Check settingSources configuration**: Skills are only loaded when you explicitly configure `settingSources`/`setting_sources`. This is the most common issue:224**Check settingSources configuration**: Skills are discovered through the `user` and `project` setting sources. If you set `settingSources`/`setting_sources` explicitly and omit those sources, skills are not loaded:

208 225 

209<CodeGroup>226<CodeGroup>

210 ```python Python theme={null}227 ```python Python theme={null}

211 # Wrong - Skills won't be loaded228 # Skills not loaded: setting_sources excludes user and project

212 options = ClaudeAgentOptions(allowed_tools=["Skill"])229 options = ClaudeAgentOptions(setting_sources=[], skills="all")

213 230 

214 # Correct - Skills will be loaded231 # Skills loaded: user and project sources included

215 options = ClaudeAgentOptions(232 options = ClaudeAgentOptions(

216 setting_sources=["user", "project"], # Required to load Skills233 setting_sources=["user", "project"],

217 allowed_tools=["Skill"],234 skills="all",

218 )235 )

219 ```236 ```

220 237 

221 ```typescript TypeScript theme={null}238 ```typescript TypeScript theme={null}

222 // Wrong - Skills won't be loaded239 // Skills not loaded: settingSources excludes user and project

223 const options = {240 const options = {

224 allowedTools: ["Skill"]241 settingSources: [],

242 skills: "all"

225 };243 };

226 244 

227 // Correct - Skills will be loaded245 // Skills loaded: user and project sources included

228 const options = {246 const options = {

229 settingSources: ["user", "project"], // Required to load Skills247 settingSources: ["user", "project"],

230 allowedTools: ["Skill"]248 skills: "all"

231 };249 };

232 ```250 ```

233</CodeGroup>251</CodeGroup>

234 252 

235For more details on `settingSources`/`setting_sources`, see the [TypeScript SDK reference](/en/agent-sdk/typescript#setting-source) or [Python SDK reference](/en/agent-sdk/python#setting-source).253For more details on `settingSources`/`setting_sources`, see the [TypeScript SDK reference](/en/agent-sdk/typescript#settingsource) or [Python SDK reference](/en/agent-sdk/python#settingsource).

236 254 

237**Check working directory**: The SDK loads Skills relative to the `cwd` option. Ensure it points to a directory containing `.claude/skills/`:255**Check working directory**: The SDK loads Skills relative to the `cwd` option. Ensure it points to a directory containing `.claude/skills/`:

238 256 


241 # Ensure your cwd points to the directory containing .claude/skills/259 # Ensure your cwd points to the directory containing .claude/skills/

242 options = ClaudeAgentOptions(260 options = ClaudeAgentOptions(

243 cwd="/path/to/project", # Must contain .claude/skills/261 cwd="/path/to/project", # Must contain .claude/skills/

244 setting_sources=["user", "project"], # Required to load Skills262 setting_sources=["user", "project"], # Loads skills from these sources

245 allowed_tools=["Skill"],263 skills="all",

246 )264 )

247 ```265 ```

248 266 


250 // Ensure your cwd points to the directory containing .claude/skills/268 // Ensure your cwd points to the directory containing .claude/skills/

251 const options = {269 const options = {

252 cwd: "/path/to/project", // Must contain .claude/skills/270 cwd: "/path/to/project", // Must contain .claude/skills/

253 settingSources: ["user", "project"], // Required to load Skills271 settingSources: ["user", "project"], // Loads skills from these sources

254 allowedTools: ["Skill"]272 skills: "all"

255 };273 };

256 ```274 ```

257</CodeGroup>275</CodeGroup>


270 288 

271### Skill Not Being Used289### Skill Not Being Used

272 290 

273**Check the Skill tool is enabled**: Confirm `"Skill"` is in your `allowedTools`.291**Check the `skills` option**: If you passed a `skills` list, confirm the skill's name is included. Passing `[]` disables all skills.

274 292 

275**Check the description**: Ensure it's specific and includes relevant keywords. See [Agent Skills Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#writing-effective-descriptions) for guidance on writing effective descriptions.293**Check the description**: Ensure it's specific and includes relevant keywords. See [Agent Skills Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#writing-effective-descriptions) for guidance on writing effective descriptions.

276 294 

Details

6 6 

7> Learn how to use slash commands to control Claude Code sessions through the SDK7> Learn how to use slash commands to control Claude Code sessions through the SDK

8 8 

9Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like clearing conversation history, compacting messages, or getting help.9Slash commands provide a way to control Claude Code sessions with special commands that start with `/`. These commands can be sent through the SDK to perform actions like compacting context, listing context usage, or invoking custom commands. Only commands that work without an interactive terminal are dispatchable through the SDK; the `system/init` message lists the ones available in your session.

10 10 

11## Discovering Available Slash Commands11## Discovering Available Slash Commands

12 12 


22 })) {22 })) {

23 if (message.type === "system" && message.subtype === "init") {23 if (message.type === "system" && message.subtype === "init") {

24 console.log("Available slash commands:", message.slash_commands);24 console.log("Available slash commands:", message.slash_commands);

25 // Example output: ["/compact", "/clear", "/help"]25 // Example output: ["/compact", "/context", "/usage"]

26 }26 }

27 }27 }

28 ```28 ```


36 async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):36 async for message in query(prompt="Hello Claude", options=ClaudeAgentOptions(max_turns=1)):

37 if isinstance(message, SystemMessage) and message.subtype == "init":37 if isinstance(message, SystemMessage) and message.subtype == "init":

38 print("Available slash commands:", message.data["slash_commands"])38 print("Available slash commands:", message.data["slash_commands"])

39 # Example output: ["/compact", "/clear", "/help"]39 # Example output: ["/compact", "/context", "/usage"]

40 40 

41 41 

42 asyncio.run(main())42 asyncio.run(main())


117 ```117 ```

118</CodeGroup>118</CodeGroup>

119 119 

120### `/clear` - Clear Conversation120### Clearing the conversation

121 121 

122The `/clear` command starts a fresh conversation by clearing all previous history:122The interactive `/clear` command is not available in the SDK. Each `query()` call already starts a fresh conversation, so to clear context, end the current `query()` and start a new one. The previous conversation stays on disk and can be returned to by passing its session ID to the [`resume` option](/en/agent-sdk/sessions#resume-by-id).

123 

124<CodeGroup>

125 ```typescript TypeScript theme={null}

126 import { query } from "@anthropic-ai/claude-agent-sdk";

127 

128 // Clear conversation and start fresh

129 for await (const message of query({

130 prompt: "/clear",

131 options: { maxTurns: 1 }

132 })) {

133 if (message.type === "system" && message.subtype === "init") {

134 console.log("Conversation cleared, new session started");

135 console.log("Session ID:", message.session_id);

136 }

137 }

138 ```

139 

140 ```python Python theme={null}

141 import asyncio

142 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage

143 

144 

145 async def main():

146 # Clear conversation and start fresh

147 async for message in query(prompt="/clear", options=ClaudeAgentOptions(max_turns=1)):

148 if isinstance(message, SystemMessage) and message.subtype == "init":

149 print("Conversation cleared, new session started")

150 print("Session ID:", message.data["session_id"])

151 

152 

153 asyncio.run(main())

154 ```

155</CodeGroup>

156 123 

157## Creating Custom Slash Commands124## Creating Custom Slash Commands

158 125 


196---163---

197allowed-tools: Read, Grep, Glob164allowed-tools: Read, Grep, Glob

198description: Run security vulnerability scan165description: Run security vulnerability scan

199model: claude-opus-4-6166model: claude-opus-4-7

200---167---

201 168 

202Analyze the codebase for security vulnerabilities including:169Analyze the codebase for security vulnerabilities including:


232 if (message.type === "system" && message.subtype === "init") {199 if (message.type === "system" && message.subtype === "init") {

233 // Will include both built-in and custom commands200 // Will include both built-in and custom commands

234 console.log("Available commands:", message.slash_commands);201 console.log("Available commands:", message.slash_commands);

235 // Example: ["/compact", "/clear", "/help", "/refactor", "/security-check"]202 // Example: ["/compact", "/context", "/usage", "/refactor", "/security-check"]

236 }203 }

237 }204 }

238 ```205 ```


257 if isinstance(message, SystemMessage) and message.subtype == "init":224 if isinstance(message, SystemMessage) and message.subtype == "init":

258 # Will include both built-in and custom commands225 # Will include both built-in and custom commands

259 print("Available commands:", message.data["slash_commands"])226 print("Available commands:", message.data["slash_commands"])

260 # Example: ["/compact", "/clear", "/help", "/refactor", "/security-check"]227 # Example: ["/compact", "/context", "/usage", "/refactor", "/security-check"]

261 228 

262 229 

263 asyncio.run(main())230 asyncio.run(main())


325 292 

326```markdown theme={null}293```markdown theme={null}

327---294---

328allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)295allowed-tools: Bash(git add *), Bash(git status *), Bash(git commit *)

329description: Create a git commit296description: Create a git commit

330---297---

331 298 


383 350 

384```markdown theme={null}351```markdown theme={null}

385---352---

386allowed-tools: Read, Grep, Glob, Bash(git diff:*)353allowed-tools: Read, Grep, Glob, Bash(git diff *)

387description: Comprehensive code review354description: Comprehensive code review

388---355---

389 356 

Details

93 ```typescript TypeScript theme={null}93 ```typescript TypeScript theme={null}

94 type SDKPartialAssistantMessage = {94 type SDKPartialAssistantMessage = {

95 type: "stream_event";95 type: "stream_event";

96 event: RawMessageStreamEvent; // From Anthropic SDK96 event: BetaRawMessageStreamEvent; // From Anthropic SDK

97 parent_tool_use_id: string | null;97 parent_tool_use_id: string | null;

98 uuid: UUID;98 uuid: UUID;

99 session_id: string;99 session_id: string;

Details

6 6 

7> Return validated JSON from agent workflows using JSON Schema, Zod, or Pydantic. Get type-safe, structured data after multi-turn tool use.7> Return validated JSON from agent workflows using JSON Schema, Zod, or Pydantic. Get type-safe, structured data after multi-turn tool use.

8 8 

9Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](https://json-schema.org/understanding-json-schema/about) for the structure you need, and the SDK guarantees the output matches it.9Structured outputs let you define the exact shape of data you want back from an agent. The agent can use any tools it needs to complete the task, and you still get validated JSON matching your schema at the end. Define a [JSON Schema](https://json-schema.org/understanding-json-schema/about) for the structure you need, and the SDK validates the output against it, re-prompting on mismatch. If validation does not succeed within the retry limit, the result is an error instead of structured data; see [Error handling](#error-handling).

10 10 

11For full type safety, use [Zod](#type-safe-schemas-with-zod-and-pydantic) (TypeScript) or [Pydantic](#type-safe-schemas-with-zod-and-pydantic) (Python) to define your schema and get strongly-typed objects back.11For full type safety, use [Zod](#type-safe-schemas-with-zod-and-pydantic) (TypeScript) or [Pydantic](#type-safe-schemas-with-zod-and-pydantic) (Python) to define your schema and get strongly-typed objects back.

12 12 

Details

15 15 

16You can create subagents in three ways:16You can create subagents in three ways:

17 17 

18* **Programmatically**: use the `agents` parameter in your `query()` options ([TypeScript](/en/agent-sdk/typescript#agent-definition), [Python](/en/agent-sdk/python#agent-definition))18* **Programmatically**: use the `agents` parameter in your `query()` options ([TypeScript](/en/agent-sdk/typescript#agentdefinition), [Python](/en/agent-sdk/python#agentdefinition))

19* **Filesystem-based**: define agents as markdown files in `.claude/agents/` directories (see [defining subagents as files](/en/sub-agents))19* **Filesystem-based**: define agents as markdown files in `.claude/agents/` directories (see [defining subagents as files](/en/sub-agents))

20* **Built-in general-purpose**: Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything20* **Built-in general-purpose**: Claude can invoke the built-in `general-purpose` subagent at any time via the Agent tool without you defining anything

21 21 


160### AgentDefinition configuration160### AgentDefinition configuration

161 161 

162| Field | Type | Required | Description |162| Field | Type | Required | Description |

163| :------------ | :------------------------------------------- | :------- | :--------------------------------------------------------------- |163| :---------------- | :---------------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- |

164| `description` | `string` | Yes | Natural language description of when to use this agent |164| `description` | `string` | Yes | Natural language description of when to use this agent |

165| `prompt` | `string` | Yes | The agent's system prompt defining its role and behavior |165| `prompt` | `string` | Yes | The agent's system prompt defining its role and behavior |

166| `tools` | `string[]` | No | Array of allowed tool names. If omitted, inherits all tools |166| `tools` | `string[]` | No | Array of allowed tool names. If omitted, inherits all tools |

167| `model` | `'sonnet' \| 'opus' \| 'haiku' \| 'inherit'` | No | Model override for this agent. Defaults to main model if omitted |167| `disallowedTools` | `string[]` | No | Array of tool names to remove from the agent's tool set |

168| `skills` | `string[]` | No | List of skill names available to this agent |168| `model` | `string` | No | Model override for this agent. Accepts an alias such as `'sonnet'`, `'opus'`, `'haiku'`, `'inherit'`, or a full model ID. Defaults to main model if omitted |

169| `memory` | `'user' \| 'project' \| 'local'` | No | Memory source for this agent (Python only) |169| `skills` | `string[]` | No | List of skill names to preload into the agent's context at startup. Unlisted skills remain invocable through the Skill tool |

170| `memory` | `'user' \| 'project' \| 'local'` | No | Memory source for this agent |

170| `mcpServers` | `(string \| object)[]` | No | MCP servers available to this agent, by name or inline config |171| `mcpServers` | `(string \| object)[]` | No | MCP servers available to this agent, by name or inline config |

172| `maxTurns` | `number` | No | Maximum number of agentic turns before the agent stops |

173| `background` | `boolean` | No | Run this agent as a non-blocking background task when invoked |

174| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| number` | No | Reasoning effort level for this agent |

175| `permissionMode` | `PermissionMode` | No | Permission mode for tool execution within this agent |

176 

177In the Python SDK, these field names use camelCase to match the wire format. See the [`AgentDefinition` reference](/en/agent-sdk/python#agentdefinition) for details.

171 178 

172<Note>179<Note>

173 Subagents cannot spawn their own subagents. Don't include `Agent` in a subagent's `tools` array.180 Subagents cannot spawn their own subagents. Don't include `Agent` in a subagent's `tools` array.


186A subagent's context window starts fresh (no parent conversation) but isn't empty. The only channel from parent to subagent is the Agent tool's prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt.193A subagent's context window starts fresh (no parent conversation) but isn't empty. The only channel from parent to subagent is the Agent tool's prompt string, so include any file paths, error messages, or decisions the subagent needs directly in that prompt.

187 194 

188| The subagent receives | The subagent does not receive |195| The subagent receives | The subagent does not receive |

189| :--------------------------------------------------------------------------- | :------------------------------------------------- |196| :--------------------------------------------------------------------------- | :----------------------------------------------------------------- |

190| Its own system prompt (`AgentDefinition.prompt`) and the Agent tool's prompt | The parent's conversation history or tool results |197| Its own system prompt (`AgentDefinition.prompt`) and the Agent tool's prompt | The parent's conversation history or tool results |

191| Project CLAUDE.md (loaded via `settingSources`) | Skills (unless listed in `AgentDefinition.skills`) |198| Project CLAUDE.md (loaded via `settingSources`) | Preloaded skill content, unless listed in `AgentDefinition.skills` |

192| Tool definitions (inherited from parent, or the subset in `tools`) | The parent's system prompt |199| Tool definitions (inherited from parent, or the subset in `tools`) | The parent's system prompt |

193 200 

194<Note>201<Note>

Details

57 ```57 ```

58 58 

59 ```python Python theme={null}59 ```python Python theme={null}

60 from claude_agent_sdk import query, AssistantMessage, ToolUseBlock60 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock

61 61 

62 async for message in query(62 async for message in query(

63 prompt="Optimize my React app performance and track progress with todos",63 prompt="Optimize my React app performance and track progress with todos",

64 options={"max_turns": 15},64 options=ClaudeAgentOptions(max_turns=15),

65 ):65 ):

66 # Todo updates are reflected in the message stream66 # Todo updates are reflected in the message stream

67 if isinstance(message, AssistantMessage):67 if isinstance(message, AssistantMessage):


132 ```132 ```

133 133 

134 ```python Python theme={null}134 ```python Python theme={null}

135 from claude_agent_sdk import query, AssistantMessage, ToolUseBlock135 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ToolUseBlock

136 from typing import List, Dict136 from typing import List, Dict

137 137 

138 138 


167 print(f"{i + 1}. {icon} {text}")167 print(f"{i + 1}. {icon} {text}")

168 168 

169 async def track_query(self, prompt: str):169 async def track_query(self, prompt: str):

170 async for message in query(prompt=prompt, options={"max_turns": 20}):170 async for message in query(prompt=prompt, options=ClaudeAgentOptions(max_turns=20)):

171 if isinstance(message, AssistantMessage):171 if isinstance(message, AssistantMessage):

172 for block in message.content:172 for block in message.content:

173 if isinstance(block, ToolUseBlock) and block.name == "TodoWrite":173 if isinstance(block, ToolUseBlock) and block.name == "TodoWrite":

Details

8 8 

9<script src="/components/typescript-sdk-type-links.js" defer />9<script src="/components/typescript-sdk-type-links.js" defer />

10 10 

11<Note>

12 **Try the new V2 interface (preview):** A simplified interface with `send()` and `stream()` patterns is now available, making multi-turn conversations easier. [Learn more about the TypeScript V2 preview](/en/agent-sdk/typescript-v2-preview)

13</Note>

14 

15## Installation11## Installation

16 12 

17```bash theme={null}13```bash theme={null}

18npm install @anthropic-ai/claude-agent-sdk14npm install @anthropic-ai/claude-agent-sdk

19```15```

20 16 

17<Note>

18 The SDK bundles a native Claude Code binary for your platform as an optional dependency such as `@anthropic-ai/claude-agent-sdk-darwin-arm64`. You don't need to install Claude Code separately. If your package manager skips optional dependencies, the SDK throws `Native CLI binary for <platform> not found`; set [`pathToClaudeCodeExecutable`](#options) to a separately installed `claude` binary instead.

19</Note>

20 

21## Functions21## Functions

22 22 

23### `query()`23### `query()`


37#### Parameters37#### Parameters

38 38 

39| Parameter | Type | Description |39| Parameter | Type | Description |

40| :-------- | :---------------------------------------------------------------- | :---------------------------------------------------------------- |40| :-------- | :--------------------------------------------------------------- | :---------------------------------------------------------------- |

41| `prompt` | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkuser-message)`>` | The input prompt as a string or async iterable for streaming mode |41| `prompt` | `string \| AsyncIterable<`[`SDKUserMessage`](#sdkusermessage)`>` | The input prompt as a string or async iterable for streaming mode |

42| `options` | [`Options`](#options) | Optional configuration object (see Options type below) |42| `options` | [`Options`](#options) | Optional configuration object (see Options type below) |

43 43 

44#### Returns44#### Returns

45 45 

46Returns a [`Query`](#query-object) object that extends `AsyncGenerator<`[`SDKMessage`](#sdk-message)`, void>` with additional methods.46Returns a [`Query`](#query-object) object that extends `AsyncGenerator<`[`SDKMessage`](#sdkmessage)`, void>` with additional methods.

47 

48### `startup()`

49 

50Pre-warms the CLI subprocess by spawning it and completing the initialize handshake before a prompt is available. The returned [`WarmQuery`](#warmquery) handle accepts a prompt later and writes it to an already-ready process, so the first `query()` call resolves without paying subprocess spawn and initialization cost inline.

51 

52```typescript theme={null}

53function startup(params?: {

54 options?: Options;

55 initializeTimeoutMs?: number;

56}): Promise<WarmQuery>;

57```

58 

59#### Parameters

60 

61| Parameter | Type | Description |

62| :-------------------- | :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

63| `options` | [`Options`](#options) | Optional configuration object. Same as the `options` parameter to `query()` |

64| `initializeTimeoutMs` | `number` | Maximum time in milliseconds to wait for subprocess initialization. Defaults to `60000`. If initialization does not complete in time, the promise rejects with a timeout error |

65 

66#### Returns

67 

68Returns a `Promise<`[`WarmQuery`](#warmquery)`>` that resolves once the subprocess has spawned and completed its initialize handshake.

69 

70#### Example

71 

72Call `startup()` early, for example on application boot, then call `.query()` on the returned handle once a prompt is ready. This moves subprocess spawn and initialization out of the critical path.

73 

74```typescript theme={null}

75import { startup } from "@anthropic-ai/claude-agent-sdk";

76 

77// Pay startup cost upfront

78const warm = await startup({ options: { maxTurns: 3 } });

79 

80// Later, when a prompt is ready, this is immediate

81for await (const message of warm.query("What files are here?")) {

82 console.log(message);

83}

84```

47 85 

48### `tool()`86### `tool()`

49 87 


62#### Parameters100#### Parameters

63 101 

64| Parameter | Type | Description |102| Parameter | Type | Description |

65| :------------ | :------------------------------------------------------------------ | :------------------------------------------------------------------------------ |103| :------------ | :---------------------------------------------------------------- | :------------------------------------------------------------------------------ |

66| `name` | `string` | The name of the tool |104| `name` | `string` | The name of the tool |

67| `description` | `string` | A description of what the tool does |105| `description` | `string` | A description of what the tool does |

68| `inputSchema` | `Schema extends AnyZodRawShape` | Zod schema defining the tool's input parameters (supports both Zod 3 and Zod 4) |106| `inputSchema` | `Schema extends AnyZodRawShape` | Zod schema defining the tool's input parameters (supports both Zod 3 and Zod 4) |

69| `handler` | `(args, extra) => Promise<`[`CallToolResult`](#call-tool-result)`>` | Async function that executes the tool logic |107| `handler` | `(args, extra) => Promise<`[`CallToolResult`](#calltoolresult)`>` | Async function that executes the tool logic |

70| `extras` | `{ annotations?: `[`ToolAnnotations`](#tool-annotations)` }` | Optional MCP tool annotations providing behavioral hints to clients |108| `extras` | `{ annotations?: `[`ToolAnnotations`](#toolannotations)` }` | Optional MCP tool annotations providing behavioral hints to clients |

71 109 

72#### `ToolAnnotations`110#### `ToolAnnotations`

73 111 


144| `firstPrompt` | `string \| undefined` | First meaningful user prompt in the session |182| `firstPrompt` | `string \| undefined` | First meaningful user prompt in the session |

145| `gitBranch` | `string \| undefined` | Git branch at the end of the session |183| `gitBranch` | `string \| undefined` | Git branch at the end of the session |

146| `cwd` | `string \| undefined` | Working directory for the session |184| `cwd` | `string \| undefined` | Working directory for the session |

147| `tag` | `string \| undefined` | User-set session tag (see [`tagSession()`](#tag-session)) |185| `tag` | `string \| undefined` | User-set session tag (see [`tagSession()`](#tagsession)) |

148| `createdAt` | `number \| undefined` | Creation time in milliseconds since epoch, from the first entry's timestamp |186| `createdAt` | `number \| undefined` | Creation time in milliseconds since epoch, from the first entry's timestamp |

149 187 

150#### Example188#### Example


228| `sessionId` | `string` | required | UUID of the session to look up |266| `sessionId` | `string` | required | UUID of the session to look up |

229| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |267| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |

230 268 

231Returns [`SDKSessionInfo`](#return-type-sdk-session-info), or `undefined` if the session is not found.269Returns [`SDKSessionInfo`](#return-type-sdksessioninfo), or `undefined` if the session is not found.

232 270 

233### `renameSession()`271### `renameSession()`

234 272 


270| `tag` | `string \| null` | required | Tag string, or `null` to clear |308| `tag` | `string \| null` | required | Tag string, or `null` to clear |

271| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |309| `options.dir` | `string` | `undefined` | Project directory path. When omitted, searches all project directories |

272 310 

311### `resolveSettings()`

312 

313Resolves the effective Claude Code settings for a given directory using the same merge engine as the CLI, without spawning the Claude CLI. Use it to inspect what configuration a `query()` call would see before invoking one.

314 

315<Note>

316 This function is alpha and its API may change before stabilization. It reads MDM sources, including macOS plist and Windows HKLM/HKCU, for parity with CLI startup, but does not execute the admin-configured `policyHelper` subprocess. The `permissions.defaultMode` field is returned as-is from all tiers including project settings. The trust filter the CLI applies before honoring escalating permission modes is not applied.

317</Note>

318 

319```typescript theme={null}

320function resolveSettings(

321 options?: ResolveSettingsOptions

322): Promise<ResolvedSettings>;

323```

324 

325#### Parameters

326 

327`resolveSettings()` accepts a single options object. All fields are optional.

328 

329| Parameter | Type | Default | Description |

330| :------------------------------ | :------------------------------------ | :-------------- | :---------------------------------------------------------------------------------------------------------------------------------------- |

331| `options.cwd` | `string` | `process.cwd()` | Directory to resolve project and local settings relative to |

332| `options.settingSources` | [`SettingSource`](#settingsource)`[]` | All sources | Which filesystem sources to load. Pass `[]` to skip user, project, and local settings. Managed policy settings load in all cases |

333| `options.managedSettings` | `Settings` | `undefined` | Restrictive policy-tier settings merged at the managed-policy precedence level. Non-restrictive keys such as `model` are silently dropped |

334| `options.serverManagedSettings` | `Settings` | `undefined` | Server-managed settings payload from `/api/claude_code/settings`. Non-restrictive keys pass through unfiltered |

335 

336#### Return type: `ResolvedSettings`

337 

338`resolveSettings()` returns an object describing the merged settings and the source that contributed each key.

339 

340| Property | Type | Description |

341| :----------- | :-------------------------------------------------- | :--------------------------------------------------------------------- |

342| `effective` | `Settings` | Merged settings after applying all enabled sources in precedence order |

343| `provenance` | `Partial<Record<keyof Settings, ProvenanceEntry>>` | For each top-level key in `effective`, which source supplied the value |

344| `sources` | `Array<{ source, settings, path?, policyOrigin? }>` | Per-source raw settings, ordered from lowest to highest precedence |

345 

346#### Example

347 

348The example below resolves settings for a project directory and prints the source that controls the cleanup period.

349 

350```typescript theme={null}

351import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";

352 

353const { effective, provenance } = await resolveSettings({

354 cwd: "/path/to/project",

355 settingSources: ["user", "project", "local"],

356});

357 

358console.log(`Cleanup period: ${effective.cleanupPeriodDays} days`);

359console.log(`Set by: ${provenance.cleanupPeriodDays?.source}`);

360```

361 

273## Types362## Types

274 363 

275### `Options`364### `Options`


277Configuration object for the `query()` function.366Configuration object for the `query()` function.

278 367 

279| Property | Type | Default | Description |368| Property | Type | Default | Description |

280| :-------------------------------- | :--------------------------------------------------------------------------------------------------- | :------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |369| :-------------------------------- | :------------------------------------------------------------------------------------------------------- | :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

281| `abortController` | `AbortController` | `new AbortController()` | Controller for cancelling operations |370| `abortController` | `AbortController` | `new AbortController()` | Controller for cancelling operations |

282| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |371| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |

283| `agent` | `string` | `undefined` | Agent name for the main thread. The agent must be defined in the `agents` option or in settings |372| `agent` | `string` | `undefined` | Agent name for the main thread. The agent must be defined in the `agents` option or in settings |

284| `agents` | `Record<string, [`AgentDefinition`](#agent-definition)>` | `undefined` | Programmatically define subagents |373| `agents` | `Record<string, [`AgentDefinition`](#agentdefinition)>` | `undefined` | Programmatically define subagents |

285| `allowDangerouslySkipPermissions` | `boolean` | `false` | Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'` |374| `allowDangerouslySkipPermissions` | `boolean` | `false` | Enable bypassing permissions. Required when using `permissionMode: 'bypassPermissions'` |

286| `allowedTools` | `string[]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |375| `allowedTools` | `string[]` | `[]` | Tools to auto-approve without prompting. This does not restrict Claude to only these tools; unlisted tools fall through to `permissionMode` and `canUseTool`. Use `disallowedTools` to block tools. See [Permissions](/en/agent-sdk/permissions#allow-and-deny-rules) |

287| `betas` | [`SdkBeta`](#sdk-beta)`[]` | `[]` | Enable beta features |376| `betas` | [`SdkBeta`](#sdkbeta)`[]` | `[]` | Enable beta features |

288| `canUseTool` | [`CanUseTool`](#can-use-tool) | `undefined` | Custom permission function for tool usage |377| `canUseTool` | [`CanUseTool`](#canusetool) | `undefined` | Custom permission function for tool usage |

289| `continue` | `boolean` | `false` | Continue the most recent conversation |378| `continue` | `boolean` | `false` | Continue the most recent conversation |

290| `cwd` | `string` | `process.cwd()` | Current working directory |379| `cwd` | `string` | `process.cwd()` | Current working directory |

291| `debug` | `boolean` | `false` | Enable debug mode for the Claude Code process |380| `debug` | `boolean` | `false` | Enable debug mode for the Claude Code process |

292| `debugFile` | `string` | `undefined` | Write debug logs to a specific file path. Implicitly enables debug mode |381| `debugFile` | `string` | `undefined` | Write debug logs to a specific file path. Implicitly enables debug mode |

293| `disallowedTools` | `string[]` | `[]` | Tools to always deny. Deny rules are checked first and override `allowedTools` and `permissionMode` (including `bypassPermissions`) |382| `disallowedTools` | `string[]` | `[]` | Tools to always deny. Deny rules are checked first and override `allowedTools` and `permissionMode` (including `bypassPermissions`) |

294| `effort` | `'low' \| 'medium' \| 'high' \| 'max'` | `'high'` | Controls how much effort Claude puts into its response. Works with adaptive thinking to guide thinking depth |383| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | `'high'` | Controls how much effort Claude puts into its response. Works with adaptive thinking to guide thinking depth |

295| `enableFileCheckpointing` | `boolean` | `false` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |384| `enableFileCheckpointing` | `boolean` | `false` | Enable file change tracking for rewinding. See [File checkpointing](/en/agent-sdk/file-checkpointing) |

296| `env` | `Record<string, string \| undefined>` | `process.env` | Environment variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header |385| `env` | `Record<string, string \| undefined>` | `process.env` | Environment variables. See [Environment variables](/en/env-vars) for variables the underlying CLI reads, and [Handle slow or stalled API responses](#handle-slow-or-stalled-api-responses) for timeout-related variables. Set `CLAUDE_AGENT_SDK_CLIENT_APP` to identify your app in the User-Agent header |

297| `executable` | `'bun' \| 'deno' \| 'node'` | Auto-detected | JavaScript runtime to use |386| `executable` | `'bun' \| 'deno' \| 'node'` | Auto-detected | JavaScript runtime to use |

298| `executableArgs` | `string[]` | `[]` | Arguments to pass to the executable |387| `executableArgs` | `string[]` | `[]` | Arguments to pass to the executable |

299| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |388| `extraArgs` | `Record<string, string \| null>` | `{}` | Additional arguments |

300| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |389| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |

301| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |390| `forkSession` | `boolean` | `false` | When resuming with `resume`, fork to a new session ID instead of continuing the original session |

302| `hooks` | `Partial<Record<`[`HookEvent`](#hook-event)`, `[`HookCallbackMatcher`](#hook-callback-matcher)`[]>>` | `{}` | Hook callbacks for events |391| `hooks` | `Partial<Record<`[`HookEvent`](#hookevent)`, `[`HookCallbackMatcher`](#hookcallbackmatcher)`[]>>` | `{}` | Hook callbacks for events |

303| `includePartialMessages` | `boolean` | `false` | Include partial message events |392| `includePartialMessages` | `boolean` | `false` | Include partial message events |

304| `maxBudgetUsd` | `number` | `undefined` | Maximum budget in USD for the query |393| `maxBudgetUsd` | `number` | `undefined` | Stop the query when the client-side cost estimate reaches this USD value. Compared against the same estimate as `total_cost_usd`; see [Track cost and usage](/en/agent-sdk/cost-tracking) for accuracy caveats |

305| `maxThinkingTokens` | `number` | `undefined` | *Deprecated:* Use `thinking` instead. Maximum tokens for thinking process |394| `maxThinkingTokens` | `number` | `undefined` | *Deprecated:* Use `thinking` instead. Maximum tokens for thinking process |

306| `maxTurns` | `number` | `undefined` | Maximum agentic turns (tool-use round trips) |395| `maxTurns` | `number` | `undefined` | Maximum agentic turns (tool-use round trips) |

307| `mcpServers` | `Record<string, [`McpServerConfig`](#mcp-server-config)>` | `{}` | MCP server configurations |396| `mcpServers` | `Record<string, [`McpServerConfig`](#mcpserverconfig)>` | `{}` | MCP server configurations |

308| `model` | `string` | Default from CLI | Claude model to use |397| `model` | `string` | Default from CLI | Claude model to use |

309| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Define output format for agent results. See [Structured outputs](/en/agent-sdk/structured-outputs) for details |398| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Define output format for agent results. See [Structured outputs](/en/agent-sdk/structured-outputs) for details |

310| `pathToClaudeCodeExecutable` | `string` | Uses built-in executable | Path to Claude Code executable |399| `pathToClaudeCodeExecutable` | `string` | Auto-resolved from bundled native binary | Path to Claude Code executable. Only needed if optional dependencies were skipped during install or your platform isn't in the supported set |

311| `permissionMode` | [`PermissionMode`](#permission-mode) | `'default'` | Permission mode for the session |400| `permissionMode` | [`PermissionMode`](#permissionmode) | `'default'` | Permission mode for the session |

312| `permissionPromptToolName` | `string` | `undefined` | MCP tool name for permission prompts |401| `permissionPromptToolName` | `string` | `undefined` | MCP tool name for permission prompts |

313| `persistSession` | `boolean` | `true` | When `false`, disables session persistence to disk. Sessions cannot be resumed later |402| `persistSession` | `boolean` | `true` | When `false`, disables session persistence to disk. Sessions cannot be resumed later |

314| `plugins` | [`SdkPluginConfig`](#sdk-plugin-config)`[]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |403| `plugins` | [`SdkPluginConfig`](#sdkpluginconfig)`[]` | `[]` | Load custom plugins from local paths. See [Plugins](/en/agent-sdk/plugins) for details |

315| `promptSuggestions` | `boolean` | `false` | Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt |404| `promptSuggestions` | `boolean` | `false` | Enable prompt suggestions. Emits a `prompt_suggestion` message after each turn with a predicted next user prompt |

316| `resume` | `string` | `undefined` | Session ID to resume |405| `resume` | `string` | `undefined` | Session ID to resume |

317| `resumeSessionAt` | `string` | `undefined` | Resume session at a specific message UUID |406| `resumeSessionAt` | `string` | `undefined` | Resume session at a specific message UUID |

318| `sandbox` | [`SandboxSettings`](#sandbox-settings) | `undefined` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandbox-settings) for details |407| `sandbox` | [`SandboxSettings`](#sandboxsettings) | `undefined` | Configure sandbox behavior programmatically. See [Sandbox settings](#sandboxsettings) for details |

319| `sessionId` | `string` | Auto-generated | Use a specific UUID for the session instead of auto-generating one |408| `sessionId` | `string` | Auto-generated | Use a specific UUID for the session instead of auto-generating one |

320| `settingSources` | [`SettingSource`](#setting-source)`[]` | `[]` (no settings) | Control which filesystem settings to load. When omitted, no settings are loaded. **Note:** Must include `'project'` to load CLAUDE.md files |409| `sessionStore` | [`SessionStore`](/en/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | Mirror session transcripts to an external backend so any host can resume them. See [Persist sessions to external storage](/en/agent-sdk/session-storage) |

410| `settings` | `string \| Settings` | `undefined` | Inline [settings](/en/settings) object or path to a settings file. Populates the flag-settings layer in the [precedence order](/en/settings#settings-precedence). Change at runtime with [`applyFlagSettings()`](#applyflagsettings) |

411| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI defaults (all sources) | Control which filesystem settings to load. Pass `[]` to disable user, project, and local settings. Managed policy settings load regardless. See [Use Claude Code features](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

412| `skills` | `string[] \| 'all'` | `undefined` | Skills available to the session. Pass `'all'` to enable every discovered skill, or a list of skill names. When set, the SDK enables the Skill tool automatically without listing it in `allowedTools`. See [Skills](/en/agent-sdk/skills) |

321| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | Custom function to spawn the Claude Code process. Use to run Claude Code in VMs, containers, or remote environments |413| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | Custom function to spawn the Claude Code process. Use to run Claude Code in VMs, containers, or remote environments |

322| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |414| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |

323| `strictMcpConfig` | `boolean` | `false` | Enforce strict MCP validation |415| `strictMcpConfig` | `boolean` | `false` | Enforce strict MCP validation |

324| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string }` | `undefined` (minimal prompt) | System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code's system prompt. When using the preset object form, add `append` to extend the system prompt with additional instructions |416| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string; excludeDynamicSections?: boolean }` | `undefined` (minimal prompt) | System prompt configuration. Pass a string for custom prompt, or `{ type: 'preset', preset: 'claude_code' }` to use Claude Code's system prompt. When using the preset object form, add `append` to extend it with additional instructions, and set `excludeDynamicSections: true` to move per-session context into the first user message for [better prompt-cache reuse across machines](/en/agent-sdk/modifying-system-prompts#improve-prompt-caching-across-users-and-machines) |

325| `thinking` | [`ThinkingConfig`](#thinking-config) | `{ type: 'adaptive' }` for supported models | Controls Claude's thinking/reasoning behavior. See [`ThinkingConfig`](#thinking-config) for options |417| `thinking` | [`ThinkingConfig`](#thinkingconfig) | `{ type: 'adaptive' }` for supported models | Controls Claude's thinking/reasoning behavior. See [`ThinkingConfig`](#thinkingconfig) for options |

326| `toolConfig` | [`ToolConfig`](#tool-config) | `undefined` | Configuration for built-in tool behavior. See [`ToolConfig`](#tool-config) for details |418| `toolConfig` | [`ToolConfig`](#toolconfig) | `undefined` | Configuration for built-in tool behavior. See [`ToolConfig`](#toolconfig) for details |

327| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |419| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration. Pass an array of tool names or use the preset to get Claude Code's default tools |

328 420 

421#### Handle slow or stalled API responses

422 

423The CLI subprocess reads several environment variables that control API timeouts and stall detection. Pass them through the `env` option:

424 

425```typescript theme={null}

426const result = query({

427 prompt: "Analyze this code",

428 options: {

429 env: {

430 ...process.env,

431 API_TIMEOUT_MS: "120000",

432 CLAUDE_CODE_MAX_RETRIES: "2",

433 CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS: "120000",

434 },

435 },

436});

437```

438 

439* `API_TIMEOUT_MS`: per-request timeout on the Anthropic client, in milliseconds. Default `600000`. Applies to the main loop and all subagents.

440* `CLAUDE_CODE_MAX_RETRIES`: maximum API retries. Default `10`. Each retry gets its own `API_TIMEOUT_MS` window, so worst-case wall time is roughly `API_TIMEOUT_MS × (CLAUDE_CODE_MAX_RETRIES + 1)` plus backoff.

441* `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS`: stall watchdog for subagents launched with `run_in_background`. Default `600000`. Resets on each stream event; on stall it aborts the subagent, marks the task failed, and surfaces the error to the parent with any partial result. Does not apply to synchronous subagents.

442* `CLAUDE_ENABLE_STREAM_WATCHDOG=1` with `CLAUDE_STREAM_IDLE_TIMEOUT_MS`: aborts the request when headers have arrived but the response body stops streaming. Off by default. `CLAUDE_STREAM_IDLE_TIMEOUT_MS` defaults to `300000` and is clamped to that minimum. The aborted request goes through the normal retry path.

443 

329### `Query` object444### `Query` object

330 445 

331Interface returned by the `query()` function.446Interface returned by the `query()` function.


340 setPermissionMode(mode: PermissionMode): Promise<void>;455 setPermissionMode(mode: PermissionMode): Promise<void>;

341 setModel(model?: string): Promise<void>;456 setModel(model?: string): Promise<void>;

342 setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;457 setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;

458 applyFlagSettings(settings: { [K in keyof Settings]?: Settings[K] | null }): Promise<void>;

343 initializationResult(): Promise<SDKControlInitializeResponse>;459 initializationResult(): Promise<SDKControlInitializeResponse>;

344 supportedCommands(): Promise<SlashCommand[]>;460 supportedCommands(): Promise<SlashCommand[]>;

345 supportedModels(): Promise<ModelInfo[]>;461 supportedModels(): Promise<ModelInfo[]>;


364| `setPermissionMode()` | Changes the permission mode (only available in streaming input mode) |480| `setPermissionMode()` | Changes the permission mode (only available in streaming input mode) |

365| `setModel()` | Changes the model (only available in streaming input mode) |481| `setModel()` | Changes the model (only available in streaming input mode) |

366| `setMaxThinkingTokens()` | *Deprecated:* Use the `thinking` option instead. Changes the maximum thinking tokens |482| `setMaxThinkingTokens()` | *Deprecated:* Use the `thinking` option instead. Changes the maximum thinking tokens |

483| `applyFlagSettings(settings)` | Merges settings into the session's flag settings layer at runtime (only available in streaming input mode). See [`applyFlagSettings()`](#applyflagsettings) |

367| `initializationResult()` | Returns the full initialization result including supported commands, models, account info, and output style configuration |484| `initializationResult()` | Returns the full initialization result including supported commands, models, account info, and output style configuration |

368| `supportedCommands()` | Returns available slash commands |485| `supportedCommands()` | Returns available slash commands |

369| `supportedModels()` | Returns available models with display info |486| `supportedModels()` | Returns available models with display info |

370| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agent-info)`[]` |487| `supportedAgents()` | Returns available subagents as [`AgentInfo`](#agentinfo)`[]` |

371| `mcpServerStatus()` | Returns status of connected MCP servers |488| `mcpServerStatus()` | Returns status of connected MCP servers |

372| `accountInfo()` | Returns account information |489| `accountInfo()` | Returns account information |

373| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |490| `reconnectMcpServer(serverName)` | Reconnect an MCP server by name |


377| `stopTask(taskId)` | Stop a running background task by ID |494| `stopTask(taskId)` | Stop a running background task by ID |

378| `close()` | Close the query and terminate the underlying process. Forcefully ends the query and cleans up all resources |495| `close()` | Close the query and terminate the underlying process. Forcefully ends the query and cleans up all resources |

379 496 

497#### `applyFlagSettings()`

498 

499Changes any [setting](/en/settings) on a running session without restarting the query. Use it when a setting that has no dedicated setter needs to change mid-session, such as tightening `permissions` after the agent reads untrusted input. `setModel()` and `setPermissionMode()` are dedicated setters for those two keys; `applyFlagSettings()` is the general form that accepts any subset of the settings keys, and passing `model` here behaves the same as `setModel()`.

500 

501The values are written to the flag-settings layer, the same layer the inline `settings` option of `query()` populates at startup. Flag settings sit near the top of the [settings precedence order](/en/settings#settings-precedence): they override user, project, and local settings, and only managed policy settings can override them. This is the same tier the [on-page precedence section](#settings-precedence) calls programmatic options.

502 

503Successive calls shallow-merge top-level keys. A second call with `{ permissions: {...} }` replaces the entire `permissions` object from the prior call rather than deep-merging into it. To clear a key from the flag layer and fall back to lower-precedence sources, pass `null` for that key. Passing `undefined` has no effect because JSON serialization drops it.

504 

505Only available in streaming input mode, the same constraint as `setModel()` and `setPermissionMode()`.

506 

507The example below switches the active model mid-session, then clears the override so the model falls back to whatever the user or project settings specify.

508 

509```typescript theme={null}

510const q = query({ prompt: messageStream });

511 

512// Override the model for the rest of the session

513await q.applyFlagSettings({ model: "claude-opus-4-6" });

514 

515// Later: clear the override and fall back to lower-precedence settings

516await q.applyFlagSettings({ model: null });

517```

518 

519<Note>

520 `applyFlagSettings()` is TypeScript-only. The Python SDK does not expose an equivalent method.

521</Note>

522 

523### `WarmQuery`

524 

525Handle returned by [`startup()`](#startup). The subprocess is already spawned and initialized, so calling `query()` on this handle writes the prompt directly to a ready process with no startup latency.

526 

527```typescript theme={null}

528interface WarmQuery extends AsyncDisposable {

529 query(prompt: string | AsyncIterable<SDKUserMessage>): Query;

530 close(): void;

531}

532```

533 

534#### Methods

535 

536| Method | Description |

537| :-------------- | :------------------------------------------------------------------------------------------------------------------------ |

538| `query(prompt)` | Send a prompt to the pre-warmed subprocess and return a [`Query`](#query-object). Can only be called once per `WarmQuery` |

539| `close()` | Close the subprocess without sending a prompt. Use this to discard a warm query that is no longer needed |

540 

541`WarmQuery` implements `AsyncDisposable`, so it can be used with `await using` for automatic cleanup.

542 

380### `SDKControlInitializeResponse`543### `SDKControlInitializeResponse`

381 544 

382Return type of `initializationResult()`. Contains session initialization data.545Return type of `initializationResult()`. Contains session initialization data.


403 tools?: string[];566 tools?: string[];

404 disallowedTools?: string[];567 disallowedTools?: string[];

405 prompt: string;568 prompt: string;

406 model?: "sonnet" | "opus" | "haiku" | "inherit";569 model?: string;

407 mcpServers?: AgentMcpServerSpec[];570 mcpServers?: AgentMcpServerSpec[];

408 skills?: string[];571 skills?: string[];

572 initialPrompt?: string;

409 maxTurns?: number;573 maxTurns?: number;

574 background?: boolean;

575 memory?: "user" | "project" | "local";

576 effort?: "low" | "medium" | "high" | "xhigh" | "max" | number;

577 permissionMode?: PermissionMode;

410 criticalSystemReminder_EXPERIMENTAL?: string;578 criticalSystemReminder_EXPERIMENTAL?: string;

411};579};

412```580```

413 581 

414| Field | Required | Description |582| Field | Required | Description |

415| :------------------------------------ | :------- | :---------------------------------------------------------------------------- |583| :------------------------------------ | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

416| `description` | Yes | Natural language description of when to use this agent |584| `description` | Yes | Natural language description of when to use this agent |

417| `tools` | No | Array of allowed tool names. If omitted, inherits all tools from parent |585| `tools` | No | Array of allowed tool names. If omitted, inherits all tools from parent. To preload Skills into the agent's context, use the `skills` field rather than listing `'Skill'` here |

418| `disallowedTools` | No | Array of tool names to explicitly disallow for this agent |586| `disallowedTools` | No | Array of tool names to explicitly disallow for this agent |

419| `prompt` | Yes | The agent's system prompt |587| `prompt` | Yes | The agent's system prompt |

420| `model` | No | Model override for this agent. If omitted or `'inherit'`, uses the main model |588| `model` | No | Model override for this agent. Accepts an alias such as `'sonnet'`, `'opus'`, `'haiku'`, `'inherit'`, or a full model ID. If omitted or `'inherit'`, uses the main model |

421| `mcpServers` | No | MCP server specifications for this agent |589| `mcpServers` | No | MCP server specifications for this agent |

422| `skills` | No | Array of skill names to preload into the agent context |590| `skills` | No | Array of skill names to preload into the agent context |

591| `initialPrompt` | No | Auto-submitted as the first user turn when this agent runs as the main thread agent |

423| `maxTurns` | No | Maximum number of agentic turns (API round-trips) before stopping |592| `maxTurns` | No | Maximum number of agentic turns (API round-trips) before stopping |

593| `background` | No | Run this agent as a non-blocking background task when invoked |

594| `memory` | No | Memory source for this agent: `'user'`, `'project'`, or `'local'` |

595| `effort` | No | Reasoning effort level for this agent. Accepts a named level or an integer |

596| `permissionMode` | No | Permission mode for tool execution within this agent. See [`PermissionMode`](#permissionmode) |

424| `criticalSystemReminder_EXPERIMENTAL` | No | Experimental: Critical reminder added to the system prompt |597| `criticalSystemReminder_EXPERIMENTAL` | No | Experimental: Critical reminder added to the system prompt |

425 598 

426### `AgentMcpServerSpec`599### `AgentMcpServerSpec`


449 622 

450#### Default behavior623#### Default behavior

451 624 

452When `settingSources` is **omitted** or **undefined**, the SDK does **not** load any filesystem settings. This provides isolation for SDK applications.625When `settingSources` is omitted or `undefined`, `query()` loads the same filesystem settings as the Claude Code CLI: user, project, and local. Managed policy settings are loaded in all cases. See [What settingSources does not control](/en/agent-sdk/claude-code-features#what-settingsources-does-not-control) for inputs that are read regardless of this option, and how to disable them.

453 626 

454#### Why use settingSources627#### Why use settingSources

455 628 

456**Load all filesystem settings (legacy behavior):**629**Disable filesystem settings:**

630 

631```typescript theme={null}

632// Do not load user, project, or local settings from disk

633const result = query({

634 prompt: "Analyze this code",

635 options: { settingSources: [] }

636});

637```

638 

639**Load all filesystem settings explicitly:**

457 640 

458```typescript theme={null}641```typescript theme={null}

459// Load all settings like SDK v0.0.x did

460const result = query({642const result = query({

461 prompt: "Analyze this code",643 prompt: "Analyze this code",

462 options: {644 options: {


493**SDK-only applications:**675**SDK-only applications:**

494 676 

495```typescript theme={null}677```typescript theme={null}

496// Define everything programmatically (default behavior)678// Define everything programmatically.

497// No filesystem dependencies - settingSources defaults to []679// Pass [] to opt out of filesystem setting sources.

498const result = query({680const result = query({

499 prompt: "Review this PR",681 prompt: "Review this PR",

500 options: {682 options: {

501 // settingSources: [] is the default, no need to specify683 settingSources: [],

502 agents: {684 agents: {

503 /* ... */685 /* ... */

504 },686 },


519 options: {701 options: {

520 systemPrompt: {702 systemPrompt: {

521 type: "preset",703 type: "preset",

522 preset: "claude_code" // Required to use CLAUDE.md704 preset: "claude_code" // Use Claude Code's system prompt

523 },705 },

524 settingSources: ["project"], // Loads CLAUDE.md from project directory706 settingSources: ["project"], // Loads CLAUDE.md from project directory

525 allowedTools: ["Read", "Write", "Edit"]707 allowedTools: ["Read", "Write", "Edit"]


5352. Project settings (`.claude/settings.json`)7172. Project settings (`.claude/settings.json`)

5363. User settings (`~/.claude/settings.json`)7183. User settings (`~/.claude/settings.json`)

537 719 

538Programmatic options (like `agents`, `allowedTools`) always override filesystem settings.720Programmatic options such as `agents`, `allowedTools`, and `settings` override user, project, and local filesystem settings. Managed policy settings take precedence over programmatic options.

539 721 

540### `PermissionMode`722### `PermissionMode`

541 723 


544 | "default" // Standard permission behavior726 | "default" // Standard permission behavior

545 | "acceptEdits" // Auto-accept file edits727 | "acceptEdits" // Auto-accept file edits

546 | "bypassPermissions" // Bypass all permission checks728 | "bypassPermissions" // Bypass all permission checks

547 | "plan" // Planning mode - no execution729 | "plan" // Planning mode - read-only tools only

548 | "dontAsk" // Don't prompt for permissions, deny if not pre-approved730 | "dontAsk" // Don't prompt for permissions, deny if not pre-approved

549 | "auto"; // Use a model classifier to approve or deny each tool call731 | "auto"; // Use a model classifier to approve or deny each tool call

550```732```


569```751```

570 752 

571| Option | Type | Description |753| Option | Type | Description |

572| :--------------- | :------------------------------------------- | :--------------------------------------------------------------------------- |754| :--------------- | :------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

573| `signal` | `AbortSignal` | Signaled if the operation should be aborted |755| `signal` | `AbortSignal` | Signaled if the operation should be aborted |

574| `suggestions` | [`PermissionUpdate`](#permission-update)`[]` | Suggested permission updates so the user is not prompted again for this tool |756| `suggestions` | [`PermissionUpdate`](#permissionupdate)`[]` | Suggested permission updates so the user is not prompted again for this tool. Bash prompts include a suggestion with the `localSettings` [destination](#permissionupdatedestination), so returning it in `updatedPermissions` writes the rule to `.claude/settings.local.json` and persists across sessions. |

575| `blockedPath` | `string` | The file path that triggered the permission request, if applicable |757| `blockedPath` | `string` | The file path that triggered the permission request, if applicable |

576| `decisionReason` | `string` | Explains why this permission request was triggered |758| `decisionReason` | `string` | Explains why this permission request was triggered |

577| `toolUseID` | `string` | Unique identifier for this specific tool call within the assistant message |759| `toolUseID` | `string` | Unique identifier for this specific tool call within the assistant message |


723 | SDKHookStartedMessage905 | SDKHookStartedMessage

724 | SDKHookProgressMessage906 | SDKHookProgressMessage

725 | SDKHookResponseMessage907 | SDKHookResponseMessage

908 | SDKPluginInstallMessage

726 | SDKToolProgressMessage909 | SDKToolProgressMessage

727 | SDKAuthStatusMessage910 | SDKAuthStatusMessage

728 | SDKTaskNotificationMessage911 | SDKTaskNotificationMessage

729 | SDKTaskStartedMessage912 | SDKTaskStartedMessage

730 | SDKTaskProgressMessage913 | SDKTaskProgressMessage

914 | SDKTaskUpdatedMessage

731 | SDKFilesPersistedEvent915 | SDKFilesPersistedEvent

732 | SDKToolUseSummaryMessage916 | SDKToolUseSummaryMessage

733 | SDKRateLimitEvent917 | SDKRateLimitEvent

918 | SDKPermissionDeniedMessage

734 | SDKPromptSuggestionMessage;919 | SDKPromptSuggestionMessage;

735```920```

736 921 


751 936 

752The `message` field is a [`BetaMessage`](https://platform.claude.com/docs/en/api/messages/create) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`.937The `message` field is a [`BetaMessage`](https://platform.claude.com/docs/en/api/messages/create) from the Anthropic SDK. It includes fields like `id`, `content`, `model`, `stop_reason`, and `usage`.

753 938 

754`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'billing_error'`, `'rate_limit'`, `'invalid_request'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`.939`SDKAssistantMessageError` is one of: `'authentication_failed'`, `'oauth_org_not_allowed'`, `'billing_error'`, `'rate_limit'`, `'invalid_request'`, `'server_error'`, `'max_output_tokens'`, or `'unknown'`.

755 940 

756### `SDKUserMessage`941### `SDKUserMessage`

757 942 


765 message: MessageParam; // From Anthropic SDK950 message: MessageParam; // From Anthropic SDK

766 parent_tool_use_id: string | null;951 parent_tool_use_id: string | null;

767 isSynthetic?: boolean;952 isSynthetic?: boolean;

953 shouldQuery?: boolean;

768 tool_use_result?: unknown;954 tool_use_result?: unknown;

955 origin?: SDKMessageOrigin;

769};956};

770```957```

771 958 

959Set `shouldQuery` to `false` to append the message to the transcript without triggering an assistant turn. The message is held and merged into the next user message that does trigger a turn. Use this to inject context, such as the output of a command you ran out of band, without spending a model call on it.

960 

772### `SDKUserMessageReplay`961### `SDKUserMessageReplay`

773 962 

774Replayed user message with required UUID.963Replayed user message with required UUID.


782 parent_tool_use_id: string | null;971 parent_tool_use_id: string | null;

783 isSynthetic?: boolean;972 isSynthetic?: boolean;

784 tool_use_result?: unknown;973 tool_use_result?: unknown;

974 origin?: SDKMessageOrigin;

785 isReplay: true;975 isReplay: true;

786};976};

787```977```


808 modelUsage: { [modelName: string]: ModelUsage };998 modelUsage: { [modelName: string]: ModelUsage };

809 permission_denials: SDKPermissionDenial[];999 permission_denials: SDKPermissionDenial[];

810 structured_output?: unknown;1000 structured_output?: unknown;

1001 deferred_tool_use?: { id: string; name: string; input: Record<string, unknown> };

1002 origin?: SDKMessageOrigin;

811 }1003 }

812 | {1004 | {

813 type: "result";1005 type: "result";


828 modelUsage: { [modelName: string]: ModelUsage };1020 modelUsage: { [modelName: string]: ModelUsage };

829 permission_denials: SDKPermissionDenial[];1021 permission_denials: SDKPermissionDenial[];

830 errors: string[];1022 errors: string[];

1023 origin?: SDKMessageOrigin;

831 };1024 };

832```1025```

833 1026 

1027The `origin` field forwards the [`SDKMessageOrigin`](#sdkmessageorigin) of the user message that triggered this result. When a background task finishes and the SDK injects a synthetic follow-up turn, the resulting `SDKResultMessage` carries `origin: { kind: "task-notification" }`. Check this field to distinguish results that answer your prompt from results emitted for background-task follow-ups, so you can route or suppress the latter. The field is absent for results emitted before any user turn, such as startup errors.

1028 

1029When a `PreToolUse` hook returns `permissionDecision: "defer"`, the result has `stop_reason: "tool_deferred"` and `deferred_tool_use` carries the pending tool's `id`, `name`, and `input`. Read this field to surface the request in your own UI, then resume with the same `session_id` to continue. See [Defer a tool call for later](/en/hooks#defer-a-tool-call-for-later) for the full round trip.

1030 

834### `SDKSystemMessage`1031### `SDKSystemMessage`

835 1032 

836System initialization message.1033System initialization message.


891};1088};

892```1089```

893 1090 

1091### `SDKPluginInstallMessage`

1092 

1093Plugin installation progress event. Emitted when [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, so your Agent SDK application can track marketplace plugin installation before the first turn. The `started` and `completed` statuses bracket the overall install. The `installed` and `failed` statuses report individual marketplaces and include `name`.

1094 

1095```typescript theme={null}

1096type SDKPluginInstallMessage = {

1097 type: "system";

1098 subtype: "plugin_install";

1099 status: "started" | "installed" | "failed" | "completed";

1100 name?: string;

1101 error?: string;

1102 uuid: UUID;

1103 session_id: string;

1104};

1105```

1106 

1107### `SDKPermissionDeniedMessage`

1108 

1109Stream event emitted when the permission system auto-denies a tool call without an interactive prompt. Use it to render the denial in your UI as it happens, rather than only observing the `is_error` tool result that follows. The interactive ask path reaches your application separately through the [`canUseTool`](#canusetool) callback. Denials issued by a `PreToolUse` hook are not reported through this event.

1110 

1111This event requires Claude Code v2.1.136 or later.

1112 

1113```typescript theme={null}

1114type SDKPermissionDeniedMessage = {

1115 type: "system";

1116 subtype: "permission_denied";

1117 tool_name: string;

1118 tool_use_id: string;

1119 agent_id?: string;

1120 decision_reason_type?: string;

1121 decision_reason?: string;

1122 message: string;

1123 uuid: UUID;

1124 session_id: string;

1125};

1126```

1127 

1128| Field | Type | Description |

1129| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------ |

1130| `tool_name` | `string` | Name of the tool that was denied |

1131| `tool_use_id` | `string` | ID of the `tool_use` block this denial answers |

1132| `agent_id` | `string` | Subagent ID when the denied call originated inside a subagent. Mirrors the field on `can_use_tool` for host-side routing |

1133| `decision_reason_type` | `string` | Discriminator for the component that decided, such as `"rule"`, `"mode"`, `"classifier"`, or `"asyncAgent"` |

1134| `decision_reason` | `string` | Human-readable reason from the deciding component, when available |

1135| `message` | `string` | Rejection message returned to the model in the `tool_result` |

1136 

894### `SDKPermissionDenial`1137### `SDKPermissionDenial`

895 1138 

896Information about a denied tool use.1139Information about a denied tool use.


903};1146};

904```1147```

905 1148 

1149### `SDKMessageOrigin`

1150 

1151Provenance of a user-role message. This appears as `origin` on [`SDKUserMessage`](#sdkusermessage) and is forwarded onto the corresponding [`SDKResultMessage`](#sdkresultmessage) so you can tell what triggered a given turn.

1152 

1153```typescript theme={null}

1154type SDKMessageOrigin =

1155 | { kind: "human" }

1156 | { kind: "channel"; server: string }

1157 | { kind: "peer"; from: string; name?: string }

1158 | { kind: "task-notification" }

1159 | { kind: "coordinator" };

1160```

1161 

1162| `kind` | Meaning |

1163| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |

1164| `human` | Direct input from the end user. On user messages, an absent `origin` also means human input. |

1165| `channel` | Message arriving on a [channel](/en/channels). `server` is the source MCP server name. |

1166| `peer` | Message from another agent session via `SendMessage`. `from` is the sender address; `name` is the sender's display name when available. |

1167| `task-notification` | Synthetic turn injected after a background task finished. See [`SDKTaskNotificationMessage`](#sdktasknotificationmessage). |

1168| `coordinator` | Message from a team coordinator in an [agent team](/en/agent-teams). |

1169 

906## Hook Types1170## Hook Types

907 1171 

908For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](/en/agent-sdk/hooks).1172For a comprehensive guide on using hooks with examples and common patterns, see the [Hooks guide](/en/agent-sdk/hooks).


916 | "PreToolUse"1180 | "PreToolUse"

917 | "PostToolUse"1181 | "PostToolUse"

918 | "PostToolUseFailure"1182 | "PostToolUseFailure"

1183 | "PostToolBatch"

919 | "Notification"1184 | "Notification"

920 | "UserPromptSubmit"1185 | "UserPromptSubmit"

921 | "SessionStart"1186 | "SessionStart"


966 | PreToolUseHookInput1231 | PreToolUseHookInput

967 | PostToolUseHookInput1232 | PostToolUseHookInput

968 | PostToolUseFailureHookInput1233 | PostToolUseFailureHookInput

1234 | PostToolBatchHookInput

969 | NotificationHookInput1235 | NotificationHookInput

970 | UserPromptSubmitHookInput1236 | UserPromptSubmitHookInput

971 | SessionStartHookInput1237 | SessionStartHookInput


993 transcript_path: string;1259 transcript_path: string;

994 cwd: string;1260 cwd: string;

995 permission_mode?: string;1261 permission_mode?: string;

1262 effort?: { level: string };

996 agent_id?: string;1263 agent_id?: string;

997 agent_type?: string;1264 agent_type?: string;

998};1265};


1018 tool_input: unknown;1285 tool_input: unknown;

1019 tool_response: unknown;1286 tool_response: unknown;

1020 tool_use_id: string;1287 tool_use_id: string;

1288 duration_ms?: number;

1021};1289};

1022```1290```

1023 1291 


1031 tool_use_id: string;1299 tool_use_id: string;

1032 error: string;1300 error: string;

1033 is_interrupt?: boolean;1301 is_interrupt?: boolean;

1302 duration_ms?: number;

1303};

1304```

1305 

1306#### `PostToolBatchHookInput`

1307 

1308Fires once after every tool call in a batch has resolved, before the next model request. `tool_response` carries the serialized `tool_result` content the model sees; the shape differs from `PostToolUseHookInput`'s structured `Output` object.

1309 

1310```typescript theme={null}

1311type PostToolBatchHookInput = BaseHookInput & {

1312 hook_event_name: "PostToolBatch";

1313 tool_calls: PostToolBatchToolCall[];

1314};

1315 

1316type PostToolBatchToolCall = {

1317 tool_name: string;

1318 tool_input: unknown;

1319 tool_use_id: string;

1320 tool_response?: unknown;

1034};1321};

1035```1322```

1036 1323 


1223 hookSpecificOutput?:1510 hookSpecificOutput?:

1224 | {1511 | {

1225 hookEventName: "PreToolUse";1512 hookEventName: "PreToolUse";

1226 permissionDecision?: "allow" | "deny" | "ask";1513 permissionDecision?: "allow" | "deny" | "ask" | "defer";

1227 permissionDecisionReason?: string;1514 permissionDecisionReason?: string;

1228 updatedInput?: Record<string, unknown>;1515 updatedInput?: Record<string, unknown>;

1229 additionalContext?: string;1516 additionalContext?: string;


1247 | {1534 | {

1248 hookEventName: "PostToolUse";1535 hookEventName: "PostToolUse";

1249 additionalContext?: string;1536 additionalContext?: string;

1537 updatedToolOutput?: unknown;

1538 /** @deprecated Use `updatedToolOutput`, which works for all tools. */

1250 updatedMCPToolOutput?: unknown;1539 updatedMCPToolOutput?: unknown;

1251 }1540 }

1252 | {1541 | {

1253 hookEventName: "PostToolUseFailure";1542 hookEventName: "PostToolUseFailure";

1254 additionalContext?: string;1543 additionalContext?: string;

1255 }1544 }

1545 | {

1546 hookEventName: "PostToolBatch";

1547 additionalContext?: string;

1548 }

1256 | {1549 | {

1257 hookEventName: "Notification";1550 hookEventName: "Notification";

1258 additionalContext?: string;1551 additionalContext?: string;


1288 | AskUserQuestionInput1581 | AskUserQuestionInput

1289 | BashInput1582 | BashInput

1290 | TaskOutputInput1583 | TaskOutputInput

1291 | ConfigInput

1292 | EnterWorktreeInput1584 | EnterWorktreeInput

1293 | ExitPlanModeInput1585 | ExitPlanModeInput

1294 | FileEditInput1586 | FileEditInput


1588 1880 

1589Reads a specific MCP resource from a server.1881Reads a specific MCP resource from a server.

1590 1882 

1591### Config

1592 

1593**Tool name:** `Config`

1594 

1595```typescript theme={null}

1596type ConfigInput = {

1597 setting: string;

1598 value?: string | boolean | number;

1599};

1600```

1601 

1602Gets or sets a configuration value.

1603 

1604### EnterWorktree1883### EnterWorktree

1605 1884 

1606**Tool name:** `EnterWorktree`1885**Tool name:** `EnterWorktree`


1627 | AgentOutput1906 | AgentOutput

1628 | AskUserQuestionOutput1907 | AskUserQuestionOutput

1629 | BashOutput1908 | BashOutput

1630 | ConfigOutput

1631 | EnterWorktreeOutput1909 | EnterWorktreeOutput

1632 | ExitPlanModeOutput1910 | ExitPlanModeOutput

1633 | FileEditOutput1911 | FileEditOutput


2043 2321 

2044Returns the contents of the requested MCP resource.2322Returns the contents of the requested MCP resource.

2045 2323 

2046### Config

2047 

2048**Tool name:** `Config`

2049 

2050```typescript theme={null}

2051type ConfigOutput = {

2052 success: boolean;

2053 operation?: "get" | "set";

2054 setting?: string;

2055 value?: unknown;

2056 previousValue?: unknown;

2057 newValue?: unknown;

2058 error?: string;

2059};

2060```

2061 

2062Returns the result of a configuration get or set operation.

2063 

2064### EnterWorktree2324### EnterWorktree

2065 2325 

2066**Tool name:** `EnterWorktree`2326**Tool name:** `EnterWorktree`


2161```2421```

2162 2422 

2163<Warning>2423<Warning>

2164 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 4.6 or Claude Opus 4.6](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.2424 The `context-1m-2025-08-07` beta is retired as of April 30, 2026. Passing this value with Claude Sonnet 4.5 or Sonnet 4 has no effect, and requests that exceed the standard 200k-token context window return an error. To use a 1M-token context window, migrate to [Claude Sonnet 4.6, Claude Opus 4.6, or Claude Opus 4.7](https://platform.claude.com/docs/en/about-claude/models/overview), which include 1M context at standard pricing with no beta header required.

2165</Warning>2425</Warning>

2166 2426 

2167### `SlashCommand`2427### `SlashCommand`


2173 name: string;2433 name: string;

2174 description: string;2434 description: string;

2175 argumentHint: string;2435 argumentHint: string;

2436 aliases?: string[];

2176};2437};

2177```2438```

2178 2439 


2186 displayName: string;2447 displayName: string;

2187 description: string;2448 description: string;

2188 supportsEffort?: boolean;2449 supportsEffort?: boolean;

2189 supportedEffortLevels?: ("low" | "medium" | "high" | "max")[];2450 supportedEffortLevels?: ("low" | "medium" | "high" | "xhigh" | "max")[];

2190 supportsAdaptiveThinking?: boolean;2451 supportsAdaptiveThinking?: boolean;

2191 supportsFastMode?: boolean;2452 supportsFastMode?: boolean;

2192};2453};


2250 | McpClaudeAIProxyServerConfig;2511 | McpClaudeAIProxyServerConfig;

2251```2512```

2252 2513 

2253See [`McpServerConfig`](#mcp-server-config) for details on each transport type.2514See [`McpServerConfig`](#mcpserverconfig) for details on each transport type.

2254 2515 

2255### `AccountInfo`2516### `AccountInfo`

2256 2517 


2268 2529 

2269### `ModelUsage`2530### `ModelUsage`

2270 2531 

2271Per-model usage statistics returned in result messages.2532Per-model usage statistics returned in result messages. The `costUSD` value is a client-side estimate. See [Track cost and usage](/en/agent-sdk/cost-tracking) for billing caveats.

2272 2533 

2273```typescript theme={null}2534```typescript theme={null}

2274type ModelUsage = {2535type ModelUsage = {


2314 2575 

2315### `CallToolResult`2576### `CallToolResult`

2316 2577 

2317MCP tool result type (from `@modelcontextprotocol/sdk/types.js`).2578MCP tool result type (from `@modelcontextprotocol/sdk/types.js`). `structuredContent` is a JSON object that can be returned alongside `content`, including image blocks. See [Return structured data](/en/agent-sdk/custom-tools#return-structured-data).

2318 2579 

2319```typescript theme={null}2580```typescript theme={null}

2320type CallToolResult = {2581type CallToolResult = {


2322 type: "text" | "image" | "resource";2583 type: "text" | "image" | "resource";

2323 // Additional fields vary by type2584 // Additional fields vary by type

2324 }>;2585 }>;

2586 structuredContent?: Record<string, unknown>;

2325 isError?: boolean;2587 isError?: boolean;

2326};2588};

2327```2589```


2585};2847};

2586```2848```

2587 2849 

2850### `SDKTaskUpdatedMessage`

2851 

2852Emitted when a background task's state changes, such as when it transitions from `running` to `completed`. Merge `patch` into your local task map keyed by `task_id`. The `end_time` field is a Unix epoch timestamp in milliseconds, comparable with `Date.now()`.

2853 

2854```typescript theme={null}

2855type SDKTaskUpdatedMessage = {

2856 type: "system";

2857 subtype: "task_updated";

2858 task_id: string;

2859 patch: {

2860 status?: "pending" | "running" | "completed" | "failed" | "killed";

2861 description?: string;

2862 end_time?: number;

2863 total_paused_ms?: number;

2864 error?: string;

2865 is_backgrounded?: boolean;

2866 };

2867 uuid: UUID;

2868 session_id: string;

2869};

2870```

2871 

2588### `SDKFilesPersistedEvent`2872### `SDKFilesPersistedEvent`

2589 2873 

2590Emitted when file checkpoints are persisted to disk.2874Emitted when file checkpoints are persisted to disk.


2620 2904 

2621### `SDKLocalCommandOutputMessage`2905### `SDKLocalCommandOutputMessage`

2622 2906 

2623Output from a local slash command (for example, `/voice` or `/cost`). Displayed as assistant-style text in the transcript.2907Output from a local slash command (for example, `/voice` or `/usage`). Displayed as assistant-style text in the transcript.

2624 2908 

2625```typescript theme={null}2909```typescript theme={null}

2626type SDKLocalCommandOutputMessage = {2910type SDKLocalCommandOutputMessage = {


2674```2958```

2675 2959 

2676| Property | Type | Default | Description |2960| Property | Type | Default | Description |

2677| :-------------------------- | :------------------------------------------------------ | :---------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |2961| :-------------------------- | :---------------------------------------------------- | :---------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

2678| `enabled` | `boolean` | `false` | Enable sandbox mode for command execution |2962| `enabled` | `boolean` | `false` | Enable sandbox mode for command execution |

2679| `autoAllowBashIfSandboxed` | `boolean` | `true` | Auto-approve bash commands when sandbox is enabled |2963| `autoAllowBashIfSandboxed` | `boolean` | `true` | Auto-approve bash commands when sandbox is enabled |

2680| `excludedCommands` | `string[]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `['docker']`). These run unsandboxed automatically without model involvement |2964| `excludedCommands` | `string[]` | `[]` | Commands that always bypass sandbox restrictions (e.g., `['docker']`). These run unsandboxed automatically without model involvement |

2681| `allowUnsandboxedCommands` | `boolean` | `true` | Allow the model to request running commands outside the sandbox. When `true`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |2965| `allowUnsandboxedCommands` | `boolean` | `true` | Allow the model to request running commands outside the sandbox. When `true`, the model can set `dangerouslyDisableSandbox` in tool input, which falls back to the [permissions system](#permissions-fallback-for-unsandboxed-commands) |

2682| `network` | [`SandboxNetworkConfig`](#sandbox-network-config) | `undefined` | Network-specific sandbox configuration |2966| `network` | [`SandboxNetworkConfig`](#sandboxnetworkconfig) | `undefined` | Network-specific sandbox configuration |

2683| `filesystem` | [`SandboxFilesystemConfig`](#sandbox-filesystem-config) | `undefined` | Filesystem-specific sandbox configuration for read/write restrictions |2967| `filesystem` | [`SandboxFilesystemConfig`](#sandboxfilesystemconfig) | `undefined` | Filesystem-specific sandbox configuration for read/write restrictions |

2684| `ignoreViolations` | `Record<string, string[]>` | `undefined` | Map of violation categories to patterns to ignore (e.g., `{ file: ['/tmp/*'], network: ['localhost'] }`) |2968| `ignoreViolations` | `Record<string, string[]>` | `undefined` | Map of violation categories to patterns to ignore (e.g., `{ file: ['/tmp/*'], network: ['localhost'] }`) |

2685| `enableWeakerNestedSandbox` | `boolean` | `false` | Enable a weaker nested sandbox for compatibility |2969| `enableWeakerNestedSandbox` | `boolean` | `false` | Enable a weaker nested sandbox for compatibility |

2686| `ripgrep` | `{ command: string; args?: string[] }` | `undefined` | Custom ripgrep binary configuration for sandbox environments |2970| `ripgrep` | `{ command: string; args?: string[] }` | `undefined` | Custom ripgrep binary configuration for sandbox environments |


2717```typescript theme={null}3001```typescript theme={null}

2718type SandboxNetworkConfig = {3002type SandboxNetworkConfig = {

2719 allowedDomains?: string[];3003 allowedDomains?: string[];

3004 deniedDomains?: string[];

2720 allowManagedDomainsOnly?: boolean;3005 allowManagedDomainsOnly?: boolean;

2721 allowLocalBinding?: boolean;3006 allowLocalBinding?: boolean;

2722 allowUnixSockets?: string[];3007 allowUnixSockets?: string[];


2727```3012```

2728 3013 

2729| Property | Type | Default | Description |3014| Property | Type | Default | Description |

2730| :------------------------ | :--------- | :---------- | :---------------------------------------------------------------- |3015| :------------------------ | :--------- | :---------- | :------------------------------------------------------------------------------------------ |

2731| `allowedDomains` | `string[]` | `[]` | Domain names that sandboxed processes can access |3016| `allowedDomains` | `string[]` | `[]` | Domain names that sandboxed processes can access |

3017| `deniedDomains` | `string[]` | `[]` | Domain names that sandboxed processes cannot access. Takes precedence over `allowedDomains` |

2732| `allowManagedDomainsOnly` | `boolean` | `false` | Restrict network access to only the domains in `allowedDomains` |3018| `allowManagedDomainsOnly` | `boolean` | `false` | Restrict network access to only the domains in `allowedDomains` |

2733| `allowLocalBinding` | `boolean` | `false` | Allow processes to bind to local ports (e.g., for dev servers) |3019| `allowLocalBinding` | `boolean` | `false` | Allow processes to bind to local ports (e.g., for dev servers) |

2734| `allowUnixSockets` | `string[]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |3020| `allowUnixSockets` | `string[]` | `[]` | Unix socket paths that processes can access (e.g., Docker socket) |


2736| `httpProxyPort` | `number` | `undefined` | HTTP proxy port for network requests |3022| `httpProxyPort` | `number` | `undefined` | HTTP proxy port for network requests |

2737| `socksProxyPort` | `number` | `undefined` | SOCKS proxy port for network requests |3023| `socksProxyPort` | `number` | `undefined` | SOCKS proxy port for network requests |

2738 3024 

3025<Note>

3026 The built-in sandbox proxy enforces `allowedDomains` based on the requested hostname and does not terminate or inspect TLS traffic, so techniques such as [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting) can potentially bypass it. See [Sandboxing security limitations](/en/sandboxing#security-limitations) for details and [Secure deployment](/en/agent-sdk/secure-deployment#traffic-forwarding) for configuring a TLS-terminating proxy.

3027</Note>

3028 

2739### `SandboxFilesystemConfig`3029### `SandboxFilesystemConfig`

2740 3030 

2741Filesystem-specific configuration for sandbox mode.3031Filesystem-specific configuration for sandbox mode.

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> 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.3> Use this file to discover all available pages before exploring further.

4 4 

5# TypeScript SDK V2 interface (preview)5# TypeScript SDK V2 session API (deprecated)

6 6 

7> Preview of the simplified V2 TypeScript Agent SDK, with session-based send/stream patterns for multi-turn conversations.7> Reference for the deprecated V2 TypeScript Agent SDK session API, with session-based send/stream patterns for multi-turn conversations.

8 8 

9<Warning>9<Warning>

10 The V2 interface is an **unstable preview**. APIs may change based on feedback before becoming stable. Some features like session forking are only available in the [V1 SDK](/en/agent-sdk/typescript).10 The V2 session API functions `unstable_v2_createSession`, `unstable_v2_resumeSession`, and `unstable_v2_prompt` are deprecated and will be removed in a future release. Use the [V1 `query()` API](/en/agent-sdk/typescript) instead.

11</Warning>11</Warning>

12 12 

13The V2 Claude Agent TypeScript SDK removes the need for async generators and yield coordination. This makes multi-turn conversations simpler, instead of managing generator state across turns, each turn is a separate `send()`/`stream()` cycle. The API surface reduces to three concepts:13V2 was an experimental session API that removed the need for async generators and yield coordination. Instead of managing generator state across turns, each turn was a separate `send()`/`stream()` cycle. The API surface reduced to three concepts:

14 14 

15* `createSession()` / `resumeSession()`: Start or continue a conversation15* `createSession()` / `resumeSession()`: Start or continue a conversation

16* `session.send()`: Send a message16* `session.send()`: Send a message


24npm install @anthropic-ai/claude-agent-sdk24npm install @anthropic-ai/claude-agent-sdk

25```25```

26 26 

27<Note>

28 The SDK bundles a native Claude Code binary for your platform as an optional dependency, so you don't need to install Claude Code separately.

29</Note>

30 

27## Quick start31## Quick start

28 32 

29### One-shot prompt33### One-shot prompt


34import { unstable_v2_prompt } from "@anthropic-ai/claude-agent-sdk";38import { unstable_v2_prompt } from "@anthropic-ai/claude-agent-sdk";

35 39 

36const result = await unstable_v2_prompt("What is 2 + 2?", {40const result = await unstable_v2_prompt("What is 2 + 2?", {

37 model: "claude-opus-4-6"41 model: "claude-opus-4-7"

38});42});

39if (result.subtype === "success") {43if (result.subtype === "success") {

40 console.log(result.result);44 console.log(result.result);


49 53 

50 const q = query({54 const q = query({

51 prompt: "What is 2 + 2?",55 prompt: "What is 2 + 2?",

52 options: { model: "claude-opus-4-6" }56 options: { model: "claude-opus-4-7" }

53 });57 });

54 58 

55 for await (const msg of q) {59 for await (const msg of q) {


75import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";79import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

76 80 

77await using session = unstable_v2_createSession({81await using session = unstable_v2_createSession({

78 model: "claude-opus-4-6"82 model: "claude-opus-4-7"

79});83});

80 84 

81await session.send("Hello!");85await session.send("Hello!");


101 105 

102 const q = query({106 const q = query({

103 prompt: "Hello!",107 prompt: "Hello!",

104 options: { model: "claude-opus-4-6" }108 options: { model: "claude-opus-4-7" }

105 });109 });

106 110 

107 for await (const msg of q) {111 for await (const msg of q) {


126import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";130import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

127 131 

128await using session = unstable_v2_createSession({132await using session = unstable_v2_createSession({

129 model: "claude-opus-4-6"133 model: "claude-opus-4-7"

130});134});

131 135 

132// Turn 1136// Turn 1


180 184 

181 const q = query({185 const q = query({

182 prompt: createInputStream(),186 prompt: createInputStream(),

183 options: { model: "claude-opus-4-6" }187 options: { model: "claude-opus-4-7" }

184 });188 });

185 189 

186 for await (const msg of q) {190 for await (const msg of q) {


219 223 

220// Create initial session and have a conversation224// Create initial session and have a conversation

221const session = unstable_v2_createSession({225const session = unstable_v2_createSession({

222 model: "claude-opus-4-6"226 model: "claude-opus-4-7"

223});227});

224 228 

225await session.send("Remember this number: 42");229await session.send("Remember this number: 42");


237 241 

238// Later: resume the session using the stored ID242// Later: resume the session using the stored ID

239await using resumedSession = unstable_v2_resumeSession(sessionId!, {243await using resumedSession = unstable_v2_resumeSession(sessionId!, {

240 model: "claude-opus-4-6"244 model: "claude-opus-4-7"

241});245});

242 246 

243await resumedSession.send("What number did I ask you to remember?");247await resumedSession.send("What number did I ask you to remember?");


256 // Create initial session260 // Create initial session

257 const initialQuery = query({261 const initialQuery = query({

258 prompt: "Remember this number: 42",262 prompt: "Remember this number: 42",

259 options: { model: "claude-opus-4-6" }263 options: { model: "claude-opus-4-7" }

260 });264 });

261 265 

262 // Get session ID from any message266 // Get session ID from any message


278 const resumedQuery = query({282 const resumedQuery = query({

279 prompt: "What number did I ask you to remember?",283 prompt: "What number did I ask you to remember?",

280 options: {284 options: {

281 model: "claude-opus-4-6",285 model: "claude-opus-4-7",

282 resume: sessionId286 resume: sessionId

283 }287 }

284 });288 });


305import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";309import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

306 310 

307await using session = unstable_v2_createSession({311await using session = unstable_v2_createSession({

308 model: "claude-opus-4-6"312 model: "claude-opus-4-7"

309});313});

310// Session closes automatically when the block exits314// Session closes automatically when the block exits

311```315```


316import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";320import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";

317 321 

318const session = unstable_v2_createSession({322const session = unstable_v2_createSession({

319 model: "claude-opus-4-6"323 model: "claude-opus-4-7"

320});324});

321// ... use the session ...325// ... use the session ...

322session.close();326session.close();


376 380 

377## Feature availability381## Feature availability

378 382 

379Not all V1 features are available in V2 yet. The following require using the [V1 SDK](/en/agent-sdk/typescript):383The V2 session API does not support every V1 feature. The following require the [V1 SDK](/en/agent-sdk/typescript):

380 384 

381* Session forking (`forkSession` option)385* Session forking (`forkSession` option)

382* Some advanced streaming input patterns386* Some advanced streaming input patterns

383 387 

384## Feedback

385 

386Share your feedback on the V2 interface before it becomes stable. Report issues and suggestions through [GitHub Issues](https://github.com/anthropics/claude-code/issues).

387 

388## See also388## See also

389 389 

390* [TypeScript SDK reference (V1)](/en/agent-sdk/typescript) - Full V1 SDK documentation390* [TypeScript SDK reference (V1)](/en/agent-sdk/typescript) - Full V1 SDK documentation

Details

12 12 

13For clarifying questions, Claude generates the questions and options. Your role is to present them to users and return their selections. You can't add your own questions to this flow; if you need to ask users something yourself, do that separately in your application logic.13For clarifying questions, Claude generates the questions and options. Your role is to present them to users and return their selections. You can't add your own questions to this flow; if you need to ask users something yourself, do that separately in your application logic.

14 14 

15The callback can stay pending indefinitely. Execution remains paused until your callback returns, and the SDK only cancels the wait when the query itself is cancelled. If a user might take longer to respond than your process can reasonably stay running, the TypeScript SDK supports the [`defer` hook decision](/en/hooks#defer-a-tool-call-for-later), which lets the process exit and resume later from the persisted session; this option is not available in the Python SDK.

16 

15This guide shows you how to detect each type of request and respond appropriately.17This guide shows you how to detect each type of request and respond appropriately.

16 18 

17## Detect when Claude needs input19## Detect when Claude needs input


52Once you've passed a `canUseTool` callback in your query options, it fires when Claude wants to use a tool that isn't auto-approved. Your callback receives three arguments:54Once you've passed a `canUseTool` callback in your query options, it fires when Claude wants to use a tool that isn't auto-approved. Your callback receives three arguments:

53 55 

54| Argument | Description |56| Argument | Description |

55| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |57| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

56| `toolName` | The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`) |58| `toolName` | The name of the tool Claude wants to use (e.g., `"Bash"`, `"Write"`, `"Edit"`) |

57| `input` | The parameters Claude is passing to the tool. Contents vary by tool. |59| `input` | The parameters Claude is passing to the tool. Contents vary by tool. |

58| `options` (TS) / `context` (Python) | Additional context including optional `suggestions` (proposed `PermissionUpdate` entries to avoid re-prompting) and a cancellation signal. In TypeScript, `signal` is an `AbortSignal`; in Python, the signal field is reserved for future use. See [`ToolPermissionContext`](/en/agent-sdk/python#tool-permission-context) for Python. |60| `options` (TS) / `context` (Python) | Additional context including optional `suggestions` (proposed `PermissionUpdate` entries to avoid re-prompting) and a cancellation signal. In TypeScript, `signal` is an `AbortSignal`; in Python, the signal field is reserved for future use. See [`ToolPermissionContext`](/en/agent-sdk/python#toolpermissioncontext) for Python. |

59 61 

60The `input` object contains tool-specific parameters. Common examples:62The `input` object contains tool-specific parameters. Common examples:

61 63 


66| `Edit` | `file_path`, `old_string`, `new_string` |68| `Edit` | `file_path`, `old_string`, `new_string` |

67| `Read` | `file_path`, `offset`, `limit` |69| `Read` | `file_path`, `offset`, `limit` |

68 70 

69See the SDK reference for complete input schemas: [Python](/en/agent-sdk/python#tool-input-output-types) | [TypeScript](/en/agent-sdk/typescript#tool-input-types).71See the SDK reference for complete input schemas: [Python](/en/agent-sdk/python#tool-input%2Foutput-types) | [TypeScript](/en/agent-sdk/typescript#tool-input-types).

70 72 

71You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response.73You can display this information to the user so they can decide whether to allow or reject the action, then return the appropriate response.

72 74 


472 | `question` field (e.g., `"How should I format the output?"`) | Key |474 | `question` field (e.g., `"How should I format the output?"`) | Key |

473 | Selected option's `label` field (e.g., `"Summary"`) | Value |475 | Selected option's `label` field (e.g., `"Summary"`) | Value |

474 476 

475 For multi-select questions, join multiple labels with `", "`. If you [support free-text input](#support-free-text-input), use the user's custom text as the value.477 For multi-select questions, pass an array of labels or join them with `", "`. If you [support free-text input](#support-free-text-input), use the user's custom text as the value.

476 478 

477 <CodeGroup>479 <CodeGroup>

478 ```python Python theme={null}480 ```python Python theme={null}


481 "questions": input_data.get("questions", []),483 "questions": input_data.get("questions", []),

482 "answers": {484 "answers": {

483 "How should I format the output?": "Summary",485 "How should I format the output?": "Summary",

484 "Which sections should I include?": "Introduction, Conclusion",486 "Which sections should I include?": ["Introduction", "Conclusion"],

485 },487 },

486 }488 }

487 )489 )


582| `questions` | Pass through the original questions array (required for tool processing) |584| `questions` | Pass through the original questions array (required for tool processing) |

583| `answers` | Object where keys are question text and values are selected labels |585| `answers` | Object where keys are question text and values are selected labels |

584 586 

585For multi-select questions, join multiple labels with `", "`. For free-text input, use the user's custom text directly.587For multi-select questions, pass an array of labels or join them with `", "`. For free-text input, use the user's custom text directly.

586 588 

587```json theme={null}589```json theme={null}

588{590{


591 ],593 ],

592 "answers": {594 "answers": {

593 "How should I format the output?": "Summary",595 "How should I format the output?": "Summary",

594 "Which sections should I include?": "Introduction, Conclusion"596 "Which sections should I include?": ["Introduction", "Conclusion"]

595 }597 }

596}598}

597```599```


805 807 

806* [Configure permissions](/en/agent-sdk/permissions): set up permission modes and rules808* [Configure permissions](/en/agent-sdk/permissions): set up permission modes and rules

807* [Control execution with hooks](/en/agent-sdk/hooks): run custom code at key points in the agent lifecycle809* [Control execution with hooks](/en/agent-sdk/hooks): run custom code at key points in the agent lifecycle

808* [TypeScript SDK reference](/en/agent-sdk/typescript#can-use-tool): full canUseTool API documentation810* [TypeScript SDK reference](/en/agent-sdk/typescript#canusetool): full canUseTool API documentation

agent-teams.md +4 −8

Details

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

102</Note>102</Note>

103 103 

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

105 105 

106```json theme={null}106```json theme={null}

107{107{


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

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

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

265 265* **Teammate messaging**: send a message to one specific teammate by name. To reach everyone, send one message per recipient.

266**Teammate messaging:**

267 

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

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

270 266 

271The lead assigns every teammate a name when it spawns them, and any teammate can message any other by that name. To get predictable names you can reference in later prompts, tell the lead what to call each teammate in your spawn instruction.267The lead assigns every teammate a name when it spawns them, and any teammate can message any other by that name. To get predictable names you can reference in later prompts, tell the lead what to call each teammate in your spawn instruction.

272 268 


409* **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.405* **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.

410* **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.406* **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.

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

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

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

414* **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.410* **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.

415* **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.411* **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.


424Explore related approaches for parallel work and delegation:420Explore related approaches for parallel work and delegation:

425 421 

426* **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 coordination422* **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

427* **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 coordination423* **Manual parallel sessions**: [Git worktrees](/en/worktrees) let you run multiple Claude Code sessions yourself without automated team coordination

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

amazon-bedrock.md +30 −10

Details

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

8 8 

9 9 

10 10<ContactSalesCard surface="bedrock" />

11<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="bedrock" />} />

12 11 

13## Prerequisites12## Prerequisites

14 13 


160 Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to the latest version, which may not yet be available in your Bedrock account when Anthropic releases an update. Claude Code [falls back](#startup-model-checks) to the previous version at startup when the latest is unavailable, but pinning lets you control when your users move to a new model.159 Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to the latest version, which may not yet be available in your Bedrock account when Anthropic releases an update. Claude Code [falls back](#startup-model-checks) to the previous version at startup when the latest is unavailable, but pinning lets you control when your users move to a new model.

161</Warning>160</Warning>

162 161 

163Set these environment variables to specific Bedrock model IDs:162Set these environment variables to specific Bedrock model IDs.

163 

164Without `ANTHROPIC_DEFAULT_OPUS_MODEL`, the `opus` alias on Bedrock resolves to Opus 4.6. Set it to the Opus 4.7 ID to use the latest model:

164 165 

165```bash theme={null}166```bash theme={null}

166export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'167export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-7'

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

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

169```170```


181 182 

182```bash theme={null}183```bash theme={null}

183# Using inference profile ID184# Using inference profile ID

184export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-6'185export ANTHROPIC_MODEL='us.anthropic.claude-sonnet-4-6'

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

186 187 

187# Using application inference profile ARN188# Using application inference profile ARN


189 190 

190# Optional: Disable prompt caching if needed191# Optional: Disable prompt caching if needed

191export DISABLE_PROMPT_CACHING=1192export DISABLE_PROMPT_CACHING=1

193 

194# Optional: Request 1-hour prompt cache TTL instead of the 5-minute default

195export ENABLE_PROMPT_CACHING_1H=1

192```196```

193 197 

194<Note>[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) may not be available in all regions.</Note>198<Note>[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) may not be available in all regions. Cache writes with a 1-hour TTL are billed at a higher rate than 5-minute writes.</Note>

195 199 

196#### Map each model version to an inference profile200#### Map each model version to an inference profile

197 201 

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

199 203 

200This example maps three Opus versions to distinct ARNs so users can switch between them without bypassing your organization's inference profiles:204This example maps four Opus versions to distinct ARNs so users can switch between them without bypassing your organization's inference profiles:

201 205 

202```json theme={null}206```json theme={null}

203{207{

204 "modelOverrides": {208 "modelOverrides": {

209 "claude-opus-4-7": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-47-prod",

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

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

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


233 "Action": [238 "Action": [

234 "bedrock:InvokeModel",239 "bedrock:InvokeModel",

235 "bedrock:InvokeModelWithResponseStream",240 "bedrock:InvokeModelWithResponseStream",

236 "bedrock:ListInferenceProfiles"241 "bedrock:ListInferenceProfiles",

242 "bedrock:GetInferenceProfile"

237 ],243 ],

238 "Resource": [244 "Resource": [

239 "arn:aws:bedrock:*:*:inference-profile/*",245 "arn:aws:bedrock:*:*:inference-profile/*",


261 267 

262For more restrictive permissions, you can limit the Resource to specific inference profile ARNs.268For more restrictive permissions, you can limit the Resource to specific inference profile ARNs.

263 269 

270`bedrock:GetInferenceProfile` lets Claude Code resolve an [application inference profile ARN](#map-each-model-version-to-an-inference-profile) to its backing foundation model, which is used to select the correct request shape for that model.

271 

272If the token is missing this permission, Claude Code recovers automatically by retrying once with the alternate shape, so requests still succeed but each new model adds an extra round-trip. Granting the permission avoids the retry. This applies most often to `AWS_BEARER_TOKEN_BEDROCK` deployments, where the token's policy is typically narrower than a full IAM role.

273 

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

265 275 

266<Note>276<Note>


269 279 

270## 1M token context window280## 1M token context window

271 281 

272Claude Opus 4.6 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 Amazon Bedrock. Claude Code automatically enables the extended context window when you select a 1M model variant.282Claude Opus 4.7, Opus 4.6, 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 Amazon Bedrock. Claude Code automatically enables the extended context window when you select a 1M model variant.

283 

284The [setup wizard](#sign-in-with-bedrock) offers a 1M context option when it pins models. To enable it for a manually pinned model instead, append `[1m]` to the model ID. See [Pin models for third-party deployments](/en/model-config#pin-models-for-third-party-deployments) for details.

285 

286## Service tiers

287 

288[Amazon Bedrock service tiers](https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html) let you trade off cost against latency. Set `ANTHROPIC_BEDROCK_SERVICE_TIER` to `default`, `flex`, or `priority`:

289 

290```bash theme={null}

291export ANTHROPIC_BEDROCK_SERVICE_TIER=priority

292```

273 293 

274To enable the 1M context window for your pinned model, append `[1m]` to the model ID. See [Pin models for third-party deployments](/en/model-config#pin-models-for-third-party-deployments) for details.294Claude Code sends this as the `X-Amzn-Bedrock-Service-Tier` header on each request. Tier availability varies by model and region. Reserved capacity uses a [provisioned throughput](https://docs.aws.amazon.com/bedrock/latest/userguide/prov-throughput.html) ARN as the model ID instead of this setting.

275 295 

276## AWS Guardrails296## AWS Guardrails

277 297 

analytics.md +2 −0

Details

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

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

26 26 

27For per-user token counts and cost estimates, configure [OpenTelemetry export](/en/monitoring-usage).

28 

27### Enable contribution metrics29### Enable contribution metrics

28 30 

29<Note>31<Note>

Details

14 14 

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

16 16 

17If your browser shows a login code instead of redirecting back after you sign in, paste it into the terminal at the `Paste code here if prompted` prompt.17If your browser shows a login code instead of redirecting back after you sign in, paste it into the terminal at the `Paste code here if prompted` prompt. This happens when the browser can't reach Claude Code's local callback server, which is common in WSL2, SSH sessions, and containers.

18 18 

19You can authenticate with any of these account types:19You can authenticate with any of these account types:

20 20 


25 25 

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

27 27 

28If you're having trouble logging in, see [authentication troubleshooting](/en/troubleshooting#authentication-issues).28If you're having trouble logging in, see [authentication troubleshooting](/en/troubleshoot-install#login-and-authentication).

29 29 

30## Set up team authentication30## Set up team authentication

31 31 


113 113 

114Claude Code securely manages your authentication credentials:114Claude Code securely manages your authentication credentials:

115 115 

116* **Storage location**: on macOS, credentials are stored in the encrypted macOS Keychain. On Linux and Windows, credentials are stored in `~/.claude/.credentials.json`, or under `$CLAUDE_CONFIG_DIR` if that variable is set. On Linux, the file is written with mode `0600`; on Windows, it inherits the access controls of your user profile directory.116* **Storage location**:

117 * On macOS, credentials are stored in the encrypted macOS Keychain.

118 * On Linux, credentials are stored in `~/.claude/.credentials.json` with file mode `0600`.

119 * On Windows, credentials are stored in `%USERPROFILE%\.claude\.credentials.json` and inherit the access controls of your user profile directory, which restricts the file to your user account by default.

120 * If you've set the `CLAUDE_CONFIG_DIR` environment variable on Linux or Windows, the `.credentials.json` file lives under that directory instead.

121 * Claude Code manages `.credentials.json` through `/login` and `/logout`. To route requests through a custom API endpoint, set the [`ANTHROPIC_BASE_URL`](/en/env-vars) environment variable instead.

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

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

119* **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.124* **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.

auto-mode-config.md +183 −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 auto mode

6 

7> Tell the auto mode classifier which repos, buckets, and domains your organization trusts. Set environment context, override the default block and allow rules, and inspect your effective config with the auto-mode CLI subcommands.

8 

9[Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) lets Claude Code run without permission prompts by routing each tool call through a classifier that blocks anything irreversible, destructive, or aimed outside your environment. Use the `autoMode` settings block to tell that classifier which repos, buckets, and domains your organization trusts, so it stops blocking routine internal operations.

10 

11<Note>

12 Auto mode is available on Max, Team, Enterprise, and API plans through the Anthropic API. It is not available on Pro or on Bedrock, Vertex, or Foundry. If Claude Code reports auto mode as unavailable for your account, check the [full requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), which also cover the supported models and admin enablement on Team and Enterprise plans.

13</Note>

14 

15Out of the box, the classifier trusts only the working directory and the current repo's configured remotes. Actions like pushing to your company's source-control org or writing to a team cloud bucket are blocked until you add them to `autoMode.environment`.

16 

17For how to enable auto mode and what it blocks by default, see [Permission modes](/en/permission-modes#eliminate-prompts-with-auto-mode). This page is the configuration reference.

18 

19This page covers how to:

20 

21* [Choose where to set rules](#where-the-classifier-reads-configuration) across CLAUDE.md, user settings, and managed settings

22* [Define trusted infrastructure](#define-trusted-infrastructure) with `autoMode.environment`

23* [Override the block and allow rules](#override-the-block-and-allow-rules) when the defaults don't fit your pipeline

24* [Inspect your effective config](#inspect-the-defaults-and-your-effective-config) with the `claude auto-mode` subcommands

25* [Review denials](#review-denials) so you know what to add next

26 

27## Where the classifier reads configuration

28 

29The classifier reads the same [CLAUDE.md](/en/memory) content Claude itself loads, so an instruction like "never force push" in your project's CLAUDE.md steers both Claude and the classifier at the same time. Start there for project conventions and behavioral rules.

30 

31For rules that apply across projects, such as trusted infrastructure or organization-wide deny rules, use the `autoMode` settings block. The classifier reads `autoMode` from the following scopes:

32 

33| Scope | File | Use for |

34| :----------------------------- | :---------------------------------------------- | :--------------------------------------------------- |

35| One developer | `~/.claude/settings.json` | Personal trusted infrastructure |

36| One project, one developer | `.claude/settings.local.json` | Per-project trusted buckets or services, gitignored |

37| Organization-wide | [Managed settings](/en/server-managed-settings) | Trusted infrastructure distributed to all developers |

38| `--settings` flag or Agent SDK | Inline JSON | Per-invocation overrides for automation |

39 

40The classifier does not read `autoMode` from shared project settings in `.claude/settings.json`, so a checked-in repo cannot inject its own allow rules.

41 

42Entries from each scope are combined. A developer can extend `environment`, `allow`, `soft_deny`, and `hard_deny` with personal entries but cannot remove entries that managed settings provide. Because allow rules act as exceptions to soft block rules inside the classifier, a developer-added `allow` entry can override an organization `soft_deny` entry: the combination is additive, not a hard policy boundary.

43 

44<Note>

45 The classifier is a second gate that runs after the [permissions system](/en/permissions). For actions that must never run regardless of user intent or classifier configuration, use `permissions.deny` in managed settings, which blocks the action before the classifier is consulted and cannot be overridden.

46</Note>

47 

48## Define trusted infrastructure

49 

50For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted: the classifier uses it to decide what "external" means, so any destination not listed is a potential exfiltration target.

51 

52The default environment list trusts the working repo and its configured remotes. To add your own entries alongside that default, include the literal string `"$defaults"` in the array. The default entries are spliced in at that position, so your custom entries can go before or after them.

53 

54```json theme={null}

55{

56 "autoMode": {

57 "environment": [

58 "$defaults",

59 "Source control: github.example.com/acme-corp and all repos under it",

60 "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",

61 "Trusted internal domains: *.corp.example.com, api.internal.example.com",

62 "Key internal services: Jenkins at ci.example.com, Artifactory at artifacts.example.com"

63 ]

64 }

65}

66```

67 

68Entries are prose, not regex or tool patterns. The classifier reads them as natural-language rules. Write them the way you would describe your infrastructure to a new engineer. A thorough environment section covers:

69 

70* **Organization**: your company name and what Claude Code is primarily used for, like software development, infrastructure automation, or data engineering

71* **Source control**: every GitHub, GitLab, or Bitbucket org your developers push to

72* **Cloud providers and trusted buckets**: bucket names or prefixes that Claude should be able to read from and write to

73* **Trusted internal domains**: hostnames for APIs, dashboards, and services inside your network, like `*.internal.example.com`

74* **Key internal services**: CI, artifact registries, internal package indexes, incident tooling

75* **Additional context**: regulated-industry constraints, multi-tenant infrastructure, or compliance requirements that affect what the classifier should treat as risky

76 

77A useful starting template: fill in the bracketed fields and remove any lines that don't apply.

78 

79```json theme={null}

80{

81 "autoMode": {

82 "environment": [

83 "$defaults",

84 "Organization: {COMPANY_NAME}. Primary use: {PRIMARY_USE_CASE, e.g. software development, infrastructure automation}",

85 "Source control: {SOURCE_CONTROL, e.g. GitHub org github.example.com/acme-corp}",

86 "Cloud provider(s): {CLOUD_PROVIDERS, e.g. AWS, GCP, Azure}",

87 "Trusted cloud buckets: {TRUSTED_BUCKETS, e.g. s3://acme-builds, gs://acme-datasets}",

88 "Trusted internal domains: {TRUSTED_DOMAINS, e.g. *.internal.example.com, api.example.com}",

89 "Key internal services: {SERVICES, e.g. Jenkins at ci.example.com, Artifactory at artifacts.example.com}",

90 "Additional context: {EXTRA, e.g. regulated industry, multi-tenant infrastructure, compliance requirements}"

91 ]

92 }

93}

94```

95 

96The more specific context you give, the better the classifier can distinguish routine internal operations from exfiltration attempts.

97 

98You don't need to fill everything in at once. A reasonable rollout: start with the defaults and add your source control org and key internal services, which resolves the most common false positives like pushing to your own repos. Add trusted domains and cloud buckets next. Fill the rest as blocks come up.

99 

100## Override the block and allow rules

101 

102Three additional fields let you replace the classifier's built-in rule lists: `autoMode.hard_deny` for unconditional security boundaries, `autoMode.soft_deny` for destructive actions that user intent can clear, and `autoMode.allow` for exceptions. Each is an array of prose descriptions, read as natural-language rules. For tool-pattern-based hard blocks that run before the classifier, use [`permissions.deny`](/en/permissions).

103 

104Inside the classifier, precedence works in four tiers:

105 

106* `hard_deny` rules block unconditionally. User intent and `allow` exceptions do not apply.

107* `soft_deny` rules block next. User intent and `allow` exceptions can override these.

108* `allow` rules then override matching `soft_deny` rules as exceptions.

109* Explicit user intent overrides the remaining soft blocks: if the user's message directly and specifically describes the exact action Claude is about to take, the classifier allows it even when a `soft_deny` rule matches.

110 

111General requests don't count as explicit intent. Asking Claude to "clean up the repo" does not authorize force-pushing, but asking Claude to "force-push this branch" does.

112 

113To loosen, add to `allow` when the classifier repeatedly flags a routine pattern the default exceptions don't cover. To tighten, add to `soft_deny` for destructive risks specific to your environment that the defaults miss, or to `hard_deny` for security boundaries that must never be crossed. To keep the built-in rules while adding your own, include the literal string `"$defaults"` in the array. The default rules are spliced in at that position, so your custom rules can go before or after them, and you continue to inherit updates as the built-in list changes across releases.

114 

115```json theme={null}

116{

117 "autoMode": {

118 "environment": [

119 "$defaults",

120 "Source control: github.example.com/acme-corp and all repos under it"

121 ],

122 "allow": [

123 "$defaults",

124 "Deploying to the staging namespace is allowed: staging is isolated from production and resets nightly",

125 "Writing to s3://acme-scratch/ is allowed: ephemeral bucket with a 7-day lifecycle policy"

126 ],

127 "soft_deny": [

128 "$defaults",

129 "Never run database migrations outside the migrations CLI, even against dev databases",

130 "Never modify files under infra/terraform/prod/: production infrastructure changes go through the review workflow"

131 ],

132 "hard_deny": [

133 "$defaults",

134 "Never send repository contents to third-party code-review APIs"

135 ]

136 }

137}

138```

139 

140<Danger>

141 Setting any of `environment`, `allow`, `soft_deny`, or `hard_deny` without `"$defaults"` replaces the entire default list for that section. A `soft_deny` array without `"$defaults"` discards every built-in soft block rule, including force push, `curl | bash`, and production deploys. A `hard_deny` array without `"$defaults"` discards the built-in data exfiltration and safety-check bypass rules.

142</Danger>

143 

144Each section is evaluated independently, so setting `environment` alone leaves the default `allow`, `soft_deny`, and `hard_deny` lists intact. Only omit `"$defaults"` when you intend to take full ownership of the list. To do that safely, run `claude auto-mode defaults` to print the built-in rules, copy them into your settings file, then review each rule against your own pipeline and risk tolerance.

145 

146## Inspect the defaults and your effective config

147 

148Three CLI subcommands help you inspect and validate your configuration.

149 

150Print the built-in `environment`, `allow`, `soft_deny`, and `hard_deny` rules as JSON:

151 

152```bash theme={null}

153claude auto-mode defaults

154```

155 

156Print what the classifier actually uses as JSON, with your settings applied where set and defaults otherwise:

157 

158```bash theme={null}

159claude auto-mode config

160```

161 

162Get AI feedback on your custom `allow`, `soft_deny`, and `hard_deny` rules:

163 

164```bash theme={null}

165claude auto-mode critique

166```

167 

168Run `claude auto-mode config` after saving your settings to confirm the effective rules are what you expect, with `"$defaults"` expanded in place. If you've written custom rules, `claude auto-mode critique` reviews them and flags entries that are ambiguous, redundant, or likely to cause false positives. If you need to remove or rewrite a built-in rule rather than add alongside it, save the output of `claude auto-mode defaults` to a file, edit the lists, and paste the result into your settings file in place of `"$defaults"`.

169 

170## Review denials

171 

172When auto mode denies a tool call, the denial is recorded in `/permissions` under the Recently denied tab. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation.

173 

174Repeated denials for the same destination usually mean the classifier is missing context. Add that destination to `autoMode.environment`, then run `claude auto-mode config` to confirm it took effect.

175 

176To react to denials programmatically, use the [`PermissionDenied` hook](/en/hooks#permissiondenied).

177 

178## See also

179 

180* [Permission modes](/en/permission-modes#eliminate-prompts-with-auto-mode): what auto mode is, what it blocks by default, and how to enable it

181* [Managed settings](/en/server-managed-settings): deploy `autoMode` configuration across your organization

182* [Permissions](/en/permissions): allow, ask, and deny rules that apply before the classifier runs

183* [Settings](/en/settings): the full settings reference, including the `autoMode` key

best-practices.md +18 −24

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> 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.3> Use this file to discover all available pages before exploring further.

4 4 

5# Best Practices for Claude Code5# Best practices for Claude Code

6 6 

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

8 8 


52 Separate research and planning from implementation to avoid solving the wrong problem.52 Separate research and planning from implementation to avoid solving the wrong problem.

53</Tip>53</Tip>

54 54 

55Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [Plan Mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to separate exploration from execution.55Letting Claude jump straight to coding can produce code that solves the wrong problem. Use [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) to separate exploration from execution.

56 56 

57The recommended workflow has four phases:57The recommended workflow has four phases:

58 58 

59<Steps>59<Steps>

60 <Step title="Explore">60 <Step title="Explore">

61 Enter Plan Mode. Claude reads files and answers questions without making changes.61 Enter plan mode. Claude reads files and answers questions without making changes.

62 62 

63 ```txt claude (Plan Mode) theme={null}63 ```txt claude (plan mode) theme={null}

64 read /src/auth and understand how we handle sessions and login.64 read /src/auth and understand how we handle sessions and login.

65 also look at how we manage environment variables for secrets.65 also look at how we manage environment variables for secrets.

66 ```66 ```


69 <Step title="Plan">69 <Step title="Plan">

70 Ask Claude to create a detailed implementation plan.70 Ask Claude to create a detailed implementation plan.

71 71 

72 ```txt claude (Plan Mode) theme={null}72 ```txt claude (plan mode) theme={null}

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

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

75 ```75 ```


78 </Step>78 </Step>

79 79 

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

81 Switch back to Normal Mode and let Claude code, verifying against its plan.81 Switch out of plan mode and let Claude code, verifying against its plan.

82 82 

83 ```txt claude (Normal Mode) theme={null}83 ```txt claude (default mode) theme={null}

84 implement the OAuth flow from your plan. write tests for the84 implement the OAuth flow from your plan. write tests for the

85 callback handler, run the test suite and fix any failures.85 callback handler, run the test suite and fix any failures.

86 ```86 ```


89 <Step title="Commit">89 <Step title="Commit">

90 Ask Claude to commit with a descriptive message and create a PR.90 Ask Claude to commit with a descriptive message and create a PR.

91 91 

92 ```txt claude (Normal Mode) theme={null}92 ```txt claude (default mode) theme={null}

93 commit with a descriptive message and open a PR93 commit with a descriptive message and open a PR

94 ```94 ```

95 </Step>95 </Step>

96</Steps>96</Steps>

97 97 

98<Callout>98<Callout>

99 Plan Mode is useful, but also adds overhead.99 Plan mode is useful, but also adds overhead.

100 100 

101 For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.101 For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.

102 102 


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

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

400* 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 summarization400* 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

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

402 402 

403### Use subagents for investigation403### Use subagents for investigation

404 404 


438### Resume conversations438### Resume conversations

439 439 

440<Tip>440<Tip>

441 Run `claude --continue` to pick up where you left off, or `--resume` to choose from recent sessions.441 Name sessions with `/rename` and treat them like branches: each workstream gets its own persistent context.

442</Tip>442</Tip>

443 443 

444Claude Code saves conversations locally. When a task spans multiple sessions, you don't have to re-explain the context:444Claude Code saves conversations locally, so when a task spans multiple sittings you don't have to re-explain the context. Run `claude --continue` to pick up the most recent session, or `claude --resume` to choose from a list. Give sessions descriptive names like `oauth-migration` so you can find them later. See [Manage sessions](/en/sessions) for the full set of resume, branch, and naming controls.

445 

446```bash theme={null}

447claude --continue # Resume the most recent conversation

448claude --resume # Select from recent conversations

449```

450 

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

452 445 

453***446***

454 447 


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

465</Tip>458</Tip>

466 459 

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

468 461 

469```bash theme={null}462```bash theme={null}

470# One-off queries463# One-off queries


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

484</Tip>477</Tip>

485 478 

486There are three main ways to run parallel sessions:479Pick the parallel approach that fits how much coordination you want to do yourself:

487 480 

488* [Claude Code desktop app](/en/desktop#work-in-parallel-with-sessions): Manage multiple local sessions visually. Each session gets its own isolated worktree.481* [Worktrees](/en/worktrees): run separate CLI sessions in isolated git checkouts so edits don't collide

489* [Claude Code on the web](/en/claude-code-on-the-web): Run on Anthropic's secure cloud infrastructure in isolated VMs.482* [Desktop app](/en/desktop#work-in-parallel-with-sessions): manage multiple local sessions visually, each in its own worktree

490* [Agent teams](/en/agent-teams): Automated coordination of multiple sessions with shared tasks, messaging, and a team lead.483* [Claude Code on the web](/en/claude-code-on-the-web): run sessions on Anthropic-managed cloud infrastructure in isolated VMs

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

491 485 

492Beyond 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.486Beyond 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.

493 487 

champion-kit.md +195 −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# Champion kit

6 

7> A playbook for engineers advocating Claude Code internally: what to share, how to answer questions, and how to grow adoption on your team.

8 

9This page is for individual engineers who are already using Claude Code and want to help their team adopt it. It covers what to share, how to answer the questions you will get, a thirty-day playbook, and responses to common concerns.

10 

11Adoption of a developer tool rarely happens because of a rollout announcement. It happens because someone on the team begins using the tool well, talks about it openly, and makes it easy for others to follow. The work you do as a champion has a disproportionate effect: every example you share shortens the learning curve for the engineers who come after you, and every question you answer in public turns one person's experience into something the whole team can build on. You are acting as a multiplier for your team, not a help desk, and this guide is structured to keep the role sustainable on those terms.

12 

13## The champion role

14 

15The role consists of three behaviors that reinforce one another.

16 

17| Behavior | What it looks like in practice | Why it matters |

18| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

19| Share what you discover | Post the prompts, screenshots, and small wins from your own work in the places your team already reads, such as an engineering channel, a standup thread, or a pull-request description. | Examples drawn from your own codebase are more persuasive than any external documentation, because colleagues can see exactly how the tool applies to the problems they share with you. |

20| Be the person people ask | When a colleague asks how you accomplished something, respond with the actual prompt you used so they can apply it directly to their own task. | A concrete, runnable example removes the gap between curiosity and a first successful use, which is where most adoption efforts stall. |

21| Grow the circle | Establish a small number of lightweight, recurring habits, such as a dedicated channel or a weekly thread, so that momentum continues even when your attention is elsewhere. | Adoption that depends on a single person is fragile. Adoption that is carried by shared habits continues to compound on its own. |

22 

23Most of this fits naturally inside the work you are already doing. The difference is a small amount of additional intention about where your discoveries are posted and how your answers travel.

24 

25### What this should cost you

26 

27Set expectations with yourself and with your lead. The activities below are intended to fit inside a normal working week, and the role should remain a multiplier on your existing work rather than an additional support responsibility.

28 

29| Activity | Time per week | Guidance |

30| --------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------ |

31| Posting wins and prompts | About 15 minutes | Capture these in the moment with a screenshot and one or two sentences; avoid turning them into formal write-ups. |

32| Answering questions in a shared channel | About 20 minutes | Answer publicly once, then link back to that answer when the question recurs. |

33| Hosting a weekly show-and-tell thread | About 5 minutes | You post the opening prompt; the team supplies the content. |

34| Optional pairing or walkthroughs | 0 to 30 minutes | Reserve this for colleagues who are genuinely blocked, and offer the [Quickstart](/en/quickstart) link before scheduling time. |

35 

36## Share what you discover

37 

38Your own experience is the most persuasive material your colleagues will encounter, because it is specific to the codebase, workflows, and problems you all share. Documentation tells people what is possible; your posts show them what is actually working in your environment.

39 

40### What is worth sharing

41 

42The most useful posts describe a technique a colleague can reuse tomorrow rather than an outcome that is already complete. Techniques compound as they spread through a team; status updates do not.

43 

44Examples of reusable techniques:

45 

46* "I learned that @-mentioning a directory works. Pointing it at `@src/components/` and asking which were missing tests surfaced two I had overlooked."

47* "Plan mode (`Shift+Tab`) shows exactly which files will be touched before any edit is made, which is why I am comfortable using it on shared code."

48* "I configured a Stop hook so I receive a desktop notification when a long task completes. Configuration is in the thread."

49* "Running `/init` generates a `CLAUDE.md` from the repository so the assistant stops re-asking about our conventions."

50 

51### Where to share it

52 

53Post wherever your team already reads. The goal is to place examples in the path of normal work rather than to create a destination.

54 

55| Location | Best suited for | Recommended format |

56| ----------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |

57| A `#claude-code` or general engineering channel | Discoveries, prompts, and "today I learned" moments | A screenshot accompanied by one or two sentences of context |

58| Pull-request descriptions | Demonstrating the approach on real code that reviewers are already reading | A single line such as "Claude and I did this refactor; happy to walk through the approach." |

59| Standups or weekly written updates | Normalizing usage with leads and skip-level managers | One sentence describing one concrete outcome |

60| Team wiki or internal documentation | Durable patterns, custom skills, and `CLAUDE.md` examples | A short page, linked from the channel topic so it remains discoverable |

61 

62### The format that works

63 

64A screenshot accompanied by a single line of context, or a brief before-and-after description, is generally the right level of detail. Keep each post short enough that someone scrolling past still absorbs the point. A long write-up tends to be saved for later and forgotten, whereas a short post with a screenshot tends to be copied and tried.

65 

66The example posts below illustrate tone and length; adapt them rather than copying verbatim.

67 

68```text theme={null}

69Learned today that @-mentioning a directory works. I pointed it at

70@src/components/ and asked which components were missing tests, and it

71surfaced two I had forgotten about.

72```

73 

74```text theme={null}

75I configured a Stop hook so I receive a desktop notification when a long

76task completes. I started a refactor, stepped away, and was notified when

77it finished. Configuration is in the thread.

78```

79 

80```text theme={null}

81Plan mode is the reason I am comfortable using this on code that matters.

82Press Shift+Tab until you see "plan"; it lays out exactly which files it

83intends to touch before changing anything.

84```

85 

86## Be the person people ask

87 

88Once you have shared a few examples, questions will follow. This is where the champion role has the greatest leverage, because a good answer to one person frequently unblocks several others who are watching the same channel.

89 

90### Answer with a prompt rather than an explanation

91 

92When a colleague asks how you accomplished something, the most useful response is the prompt you actually used. They will learn more from running that prompt against their own problem than from any description you could write, and it gives them something they can act on immediately.

93 

94```text theme={null}

95Colleague: How did you get it to find that race condition?

96 

97Champion: I asked, "The test in @tests/scheduler.test.ts is flaky, figure

98out why," and it traced two unjoined promises in the scheduler. Try the

99same phrasing on your test.

100```

101 

102### Point at the feature rather than the documentation

103 

104A response such as "Try plan mode, press `Shift+Tab` until you see it" is more useful in the moment than a link to the documentation. If the person needs more depth later they will find it on their own; right now they need the single thing that unblocks them.

105 

106### Questions you are likely to hear

107 

108| Question | Suggested response | Follow-up resource |

109| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |

110| "What should I try it on first?" | Recommend a real but contained task, ideally a bug or chore the person has been postponing because it is tedious rather than difficult. | [Common workflows](/en/common-workflows) |

111| "How do I trust it with my code?" | Introduce plan mode: pressing `Shift+Tab` cycles into it, Claude proposes exactly what it intends to change, and nothing is modified until the user approves. | [Permissions](/en/permissions) |

112| "Is the setup worth the effort?" | Installation takes roughly two minutes, runs in the terminal, and requires no IDE extension. Running `/init` once is sufficient to begin working. | [Quickstart](/en/quickstart) |

113| "It produced an incorrect result." | Encourage them to provide the failure back to Claude. Pasting the error message or failing test is far more effective than rephrasing the original request. | [Common workflows](/en/common-workflows) |

114| "It does not understand our codebase conventions." | Suggest running `/init` to generate a `CLAUDE.md` file, then adding the team's conventions, test commands, and any directories that should be avoided. | [Memory](/en/memory) |

115| "Is this just autocomplete?" | Offer a brief demonstration in which Claude explains an unfamiliar file, traces a bug across services, or drafts a migration plan. These tasks require reasoning across the repository rather than completing a single line. | A two-minute live demonstration |

116| "What about security and data handling?" | Refer this question to your administrator. Your organization's deployment and data-handling policy is already configured, and champions should not improvise this answer. | [Security](/en/security) · [Data usage](/en/data-usage) |

117 

118## Grow the circle

119 

120The objective is not to build a program or to own a rollout. It is to establish a small number of lightweight habits that allow momentum to continue after you have stopped actively driving it. When questions in the channel are being answered by people other than you, the role has done its job.

121 

122### Patterns that tend to work

123 

124| Pattern | How to run it | Effort required |

125| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |

126| A dedicated channel | Create a `#claude-code` channel (or a recurring thread in an existing one), pin the [Quickstart](/en/quickstart) link and one strong example, and answer questions publicly so each answer benefits everyone watching. | About five minutes to set up, then ambient |

127| A weekly show-and-tell thread | Each Friday, post "What did Claude help you with this week?" No preparation, slides, or meeting are required; screenshots and short descriptions are sufficient. | About two minutes per week |

128| Share a custom skill | Post your most useful `.claude/skills/<name>/SKILL.md` file, for example a `/ship` skill that runs tests and lint before committing, with a one-line description. Because skills are plain Markdown, colleagues can adopt them immediately. | About five minutes per skill |

129| Generate a setup guide from your own usage | Run `/team-onboarding` in a project you have spent real time in. Claude scans your recent sessions, commands, and MCP servers, then produces a guide a new teammate can paste as their first message to replay your setup. Pin it in the channel. | About two minutes |

130| Pair on a first task | Offer a single fifteen-minute pairing session to anyone getting started. One successful outcome on their own code is more persuasive than any presentation. | About fifteen minutes per person |

131| Identify the next champion | The colleague who asks you the most questions is usually ready to take on this role. Forward them this page and divide the channel responsibilities between you. | Negligible |

132 

133### Thirty-day playbook

134 

135If a loose plan is helpful, the sequence below reflects what tends to work across most teams. Adjust freely to fit your context.

136 

137<Steps>

138 <Step title="Week 1: Seed the channel">

139 Create the channel, pin the [Quickstart](/en/quickstart), and post two or three of your own examples with the prompts included.

140 

141 **Signal that it is working:** a few colleagues react or reply, and at least one question is asked in the channel.

142 </Step>

143 

144 <Step title="Week 2: Start the rhythm">

145 Start the weekly show-and-tell thread, answer every question publicly, and share one custom skill or `CLAUDE.md` snippet.

146 

147 **Signal that it is working:** someone other than you posts an example of their own.

148 </Step>

149 

150 <Step title="Week 3: Pair and consolidate">

151 Offer two or three short pairing sessions and consolidate the most common questions and answers into a pinned FAQ message.

152 

153 **Signal that it is working:** you see repeat usage, with the same colleagues returning rather than trying once and stopping.

154 </Step>

155 

156 <Step title="Week 4: Hand off">

157 Identify a second champion and share a brief summary of what is working and what is not with your lead or administrator.

158 

159 **Signal that it is working:** questions in the channel are being answered by people other than you.

160 </Step>

161</Steps>

162 

163### When someone wants to go deeper

164 

165You are the warm introduction rather than the onboarding program. When a colleague moves past "should I try this" into "how do I become effective with it," point them to the [Quickstart](/en/quickstart) and [Common workflows](/en/common-workflows) pages. They contain short sections covering the features that are genuinely useful but difficult to discover on your own.

166 

167## Respond to common concerns

168 

169Healthy skepticism is expected; engineers should be cautious about tools that touch their code. The most effective response is rarely to argue the general case. Instead, acknowledge the concern, offer a brief reframe, and propose one concrete demonstration on the person's own code. Most concerns are resolved by a single successful experience.

170 

171| Concern | Suggested response | Evidence to offer |

172| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |

173| "I am faster without it." | That is likely true for code the person writes routinely. Suggest trying it on the work they tend to avoid: legacy files, unfamiliar services, or test scaffolding, where the leverage is highest. | Time one tedious task both ways and compare. |

174| "I do not trust AI to touch production code." | Agree that no change should land unread. Plan mode combined with normal diff review means nothing is applied that the engineer has not inspected, the same standard as any pull request. | Demonstrate plan mode on a real file. |

175| "It will make junior engineers weaker." | Used well, it is an effective explainer. Encourage junior engineers to ask Claude to explain a file and its call sites before asking it to change anything. | Run "Explain @file and where it is called from" together. |

176| "I tried it once and it hallucinated." | This is usually a context problem rather than a model problem. @-mentioning the relevant files, running `/init`, and providing the actual error output typically resolves it. | Re-run their original prompt with proper `@`-context. |

177| "We do not have time to learn another tool." | Claude Code is a terminal command rather than a platform. If it does not return value within the first session, it is reasonable to set it aside. | A two-minute install followed by one real bug. |

178 

179## Quick-reference sheet

180 

181The techniques below are the ones that most reliably move someone from a first trial to daily use. Pin this table in a channel or share it on its own.

182 

183| Technique | How to apply it |

184| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |

185| Provide the right context | Use `@file` or `@directory/` references, or paste the error or log output directly. Supplying relevant context is more effective than elaborate prompting. |

186| Review the plan before the edit | Press `Shift+Tab` to enter plan mode. Claude will describe the intended changes for your approval before executing them. |

187| Teach it your repository | Run `/init` to generate a `CLAUDE.md` file, then add your conventions, test commands, and any directories that should not be modified. See [Memory](/en/memory). |

188| Reuse a workflow | Save a `SKILL.md` file in `.claude/skills/<name>/` to create a `/name` skill that the entire team can use. See [Skills](/en/skills). |

189| Stay informed during long tasks | Configure a Stop hook to receive a desktop notification when a long-running task completes. See [Hooks](/en/hooks-guide). |

190| Recover from an incorrect result | Rather than rephrasing the request, paste the failing test or stack trace back to Claude and ask it to address that specific failure. |

191| Keep edits surgical | Ask for a diff, or specify "only change X." Claude respects scope when scope is stated. |

192 

193<Tip>

194 Claude Code is updated frequently. Verify version-specific details against the [documentation home page](/en/overview) before distributing this material internally.

195</Tip>

channels.md +13 −8

Details

7> Use channels to push messages, alerts, and webhooks into your Claude Code session from an MCP server. Forward CI results, chat messages, and monitoring events so Claude can react while you're away.7> Use channels to push messages, alerts, and webhooks into your Claude Code session from an MCP server. Forward CI results, chat messages, and monitoring events so Claude can react while you're away.

8 8 

9<Note>9<Note>

10 Channels are in [research preview](#research-preview) and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must [explicitly enable them](#enterprise-controls).10 Channels are in [research preview](#research-preview) and require Claude Code v2.1.80 or later. They require Anthropic authentication through claude.ai or a Console API key, and are not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. Team and Enterprise organizations must [explicitly enable them](#enterprise-controls).

11</Note>11</Note>

12 12 

13A channel is an MCP server that pushes events into your running Claude Code session, so Claude can react to things that happen while you're not at the terminal. Channels can be two-way: Claude reads the event and replies back through the same channel, like a chat bridge. Events only arrive while the session is open, so for an always-on setup you run Claude in a background process or persistent terminal.13A channel is an MCP server that pushes events into your running Claude Code session, so Claude can react to things that happen while you're not at the terminal. Channels can be two-way: Claude reads the event and replies back through the same channel, like a chat bridge. Events only arrive while the session is open, so for an always-on setup you run Claude in a background process or persistent terminal.


23* [Supported channels](#supported-channels): Telegram, Discord, and iMessage setup23* [Supported channels](#supported-channels): Telegram, Discord, and iMessage setup

24* [Install and run a channel](#quickstart) with fakechat, a localhost demo24* [Install and run a channel](#quickstart) with fakechat, a localhost demo

25* [Who can push messages](#security): sender allowlists and how you pair25* [Who can push messages](#security): sender allowlists and how you pair

26* [Enable channels for your organization](#enterprise-controls) on Team and Enterprise26* [Enable channels for your organization](#enterprise-controls) if you manage a Team, Enterprise, or Console org

27* [How channels compare](#how-channels-compare) to web sessions, Slack, MCP, and Remote Control27* [How channels compare](#how-channels-compare) to web sessions, Slack, MCP, and Remote Control

28 28 

29To build your own channel, see the [Channels reference](/en/channels-reference).29To build your own channel, see the [Channels reference](/en/channels-reference).


225 225 

226To try the fakechat demo, you'll need:226To try the fakechat demo, you'll need:

227 227 

228* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) with a claude.ai account228* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) with a claude.ai account or a Claude Console API key

229* [Bun](https://bun.sh) installed. The pre-built channel plugins are Bun scripts. Check with `bun --version`; if that fails, [install Bun](https://bun.sh/docs/installation).229* [Bun](https://bun.sh) installed. The pre-built channel plugins are Bun scripts. Check with `bun --version`; if that fails, [install Bun](https://bun.sh/docs/installation).

230* **Team/Enterprise users**: your organization admin must [enable channels](#enterprise-controls) in managed settings230* **Team, Enterprise, or managed Console org**: your admin must [enable channels](#enterprise-controls) in managed settings

231 231 

232<Steps>232<Steps>

233 <Step title="Install the fakechat channel plugin">233 <Step title="Install the fakechat channel plugin">


280 280 

281iMessage works differently: texting yourself bypasses the gate automatically, and you add other contacts by handle with `/imessage:access allow`.281iMessage works differently: texting yourself bypasses the gate automatically, and you add other contacts by handle with `/imessage:access allow`.

282 282 

283On top of that, you control which servers are enabled each session with `--channels`, and on Team and Enterprise plans your organization controls availability with [`channelsEnabled`](#enterprise-controls).283On top of that, you control which servers are enabled each session with `--channels`, and your organization controls availability with [`channelsEnabled`](#enterprise-controls) on claude.ai Team and Enterprise plans and on Console organizations that deploy managed settings.

284 284 

285Being in `.mcp.json` isn't enough to push messages: a server also has to be named in `--channels`.285Being in `.mcp.json` isn't enough to push messages: a server also has to be named in `--channels`.

286 286 


288 288 

289## Enterprise controls289## Enterprise controls

290 290 

291On Team and Enterprise plans, channels are off by default. Admins control availability through two [managed settings](/en/settings) that users cannot override:291Admins control availability through two [managed settings](/en/settings) that users cannot override. The default depends on how you authenticate:

292 

293* **claude.ai Team and Enterprise**: channels are blocked until an admin enables them.

294* **Anthropic Console with API key authentication**: channels are permitted by default. You only need this setting if your organization deploys managed settings.

295 

296In all cases, no channel runs until a user opts it in for the session with `--channels`.

292 297 

293| Setting | Purpose | When not configured |298| Setting | Purpose | When not configured |

294| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |299| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

295| `channelsEnabled` | Master switch. Must be `true` for any channel to deliver messages. Set via the [claude.ai Admin console](https://claude.ai/admin-settings/claude-code) toggle or directly in managed settings. Blocks all channels including the development flag when off. | Channels blocked |300| `channelsEnabled` | Master switch. Must be `true` for any channel to deliver messages. Set via the [claude.ai Admin console](https://claude.ai/admin-settings/claude-code) toggle or directly in managed settings. Blocks all channels including the development flag when off. | claude.ai Team and Enterprise: channels blocked. Console: channels allowed unless your organization deploys managed settings, in which case channels are blocked until this key is set |

296| `allowedChannelPlugins` | Which plugins can register once channels are enabled. Replaces the Anthropic-maintained list when set. Only applies when `channelsEnabled` is `true`. | Anthropic default list applies |301| `allowedChannelPlugins` | Which plugins can register once channels are enabled. Replaces the Anthropic-maintained list when set. Only applies when `channelsEnabled` is `true`. | Anthropic default list applies |

297 302 

298Pro and Max users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`.303Pro and Max users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`.

Details

7> Build an MCP server that pushes webhooks, alerts, and chat messages into a Claude Code session. Reference for the channel contract: capability declaration, notification events, reply tools, sender gating, and permission relay.7> Build an MCP server that pushes webhooks, alerts, and chat messages into a Claude Code session. Reference for the channel contract: capability declaration, notification events, reply tools, sender gating, and permission relay.

8 8 

9<Note>9<Note>

10 Channels are in [research preview](/en/channels#research-preview) and require Claude Code v2.1.80 or later. They require claude.ai login. Console and API key authentication is not supported. Team and Enterprise organizations must [explicitly enable them](/en/channels#enterprise-controls).10 Channels are in [research preview](/en/channels#research-preview) and require Claude Code v2.1.80 or later. Team and Enterprise organizations must [explicitly enable them](/en/channels#enterprise-controls).

11</Note>11</Note>

12 12 

13A channel is an MCP server that pushes events into a Claude Code session so Claude can react to things happening outside the terminal.13A channel is an MCP server that pushes events into a Claude Code session so Claude can react to things happening outside the terminal.


138 138 

139 When Claude Code starts, it reads your MCP config, spawns your `webhook.ts` as a subprocess, and the HTTP listener starts automatically on the port you configured (8788 in this example). You don't need to run the server yourself.139 When Claude Code starts, it reads your MCP config, spawns your `webhook.ts` as a subprocess, and the HTTP listener starts automatically on the port you configured (8788 in this example). You don't need to run the server yourself.

140 140 

141 If you see "blocked by org policy," your Team or Enterprise admin needs to [enable channels](/en/channels#enterprise-controls) first.141 If you see "blocked by org policy," your organization admin needs to [enable channels](/en/channels#enterprise-controls) first.

142 142 

143 In a separate terminal, simulate a webhook by sending an HTTP POST with a message to your server. This example sends a CI failure alert to port 8788 (or whichever port you configured):143 In a separate terminal, simulate a webhook by sending an HTTP POST with a message to your server. This example sends a CI failure alert to port 8788 (or whichever port you configured):

144 144 

Details

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

46<Note>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`).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/sessions#branch-a-session) instead (`claude --continue --fork-session`).

48</Note>48</Note>

49 49 

50## Common use cases50## Common use cases

chrome.md +1 −1

Details

6 6 

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

8 8 

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.9Claude Code integrates with the [Claude in Chrome browser extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) 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.

10 10 

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

12 12 

Details

109 </Step>109 </Step>

110</Steps>110</Steps>

111 111 

112### Link artifacts back to the session

113 

114Each cloud session has a transcript URL on claude.ai, and the session can read its own ID from the `CLAUDE_CODE_REMOTE_SESSION_ID` environment variable. Use this to put a traceable link in PR bodies, commit messages, Slack posts, or generated reports so a reviewer can open the run that produced them.

115 

116The variable's value uses a `cse_` prefix, while the transcript URL path takes the same ID with a `session_` prefix. Substitute the prefix when building the link. The following command prints the URL:

117 

118```bash theme={null}

119echo "https://claude.ai/code/${CLAUDE_CODE_REMOTE_SESSION_ID/#cse_/session_}"

120```

121 

112### Run tests, start services, and add packages122### Run tests, start services, and add packages

113 123 

114Claude runs tests as part of working on a task. Ask for it in your prompt, like "fix the failing tests in `tests/`" or "run pytest after each change." Test runners like pytest, jest, and cargo test work out of the box since they're pre-installed.124Claude runs tests as part of working on a task. Ask for it in your prompt, like "fix the failing tests in `tests/`" or "run pytest after each change." Test runners like pytest, jest, and cargo test work out of the box since they're pre-installed.

115 125 

116PostgreSQL and Redis are pre-installed but not running by default. Start each one in a [setup script](#setup-scripts) or ask Claude to start it during the session:126PostgreSQL and Redis are pre-installed but not running by default. Ask Claude to start each one during the session:

117 127 

118```bash theme={null}128```bash theme={null}

119service postgresql start129service postgresql start


123service redis-server start133service redis-server start

124```134```

125 135 

126Docker is available for running containerized services. Network access to pull images follows your environment's [access level](#access-levels).136Docker is available for running containerized services. Ask Claude to run `docker compose up` to start your project's services. Network access to pull images follows your environment's [access level](#access-levels), and the [Trusted defaults](#default-allowed-domains) include Docker Hub and other common registries.

127 137 

128To add packages that aren't pre-installed, use a [setup script](#setup-scripts) so they're available at session start. You can also ask Claude to install packages during the session, but those installs don't persist across sessions.138If your images are large or slow to pull, add `docker compose pull` or `docker compose build` to your [setup script](#setup-scripts). The pulled images are saved in the [cached environment](#environment-caching), so each new session has them on disk. The cache stores files only, not running processes, so Claude still starts the containers each session.

139 

140To add packages that aren't pre-installed, use a [setup script](#setup-scripts). The script's output is [cached](#environment-caching), so packages you install there are available at the start of every session without reinstalling each time. You can also ask Claude to install packages mid-session, but those installs don't carry over to other sessions.

129 141 

130### Resource limits142### Resource limits

131 143 


144| Action | How |156| Action | How |

145| :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |157| :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

146| Add an environment | Select the current environment to open the selector, then select **Add environment**. The dialog includes name, network access level, environment variables, and setup script. |158| Add an environment | Select the current environment to open the selector, then select **Add environment**. The dialog includes name, network access level, environment variables, and setup script. |

147| Edit an environment | Select the settings icon to the right of the environment name. |159| Edit an environment | Select the cloud icon showing the current environment's name to open the selector, hover over an environment, and click the settings icon that appears on the right. |

148| Archive an environment | Open the environment for editing and select **Archive**. Archived environments are hidden from the selector but existing sessions keep running. |160| Archive an environment | Open the environment for editing and select **Archive**. Archived environments are hidden from the selector but existing sessions keep running. |

149| Set the default for `--remote` | Run `/remote-env` in your terminal. If you have a single environment, this command shows your current configuration. `/remote-env` only selects the default; add, edit, and archive environments from the web interface. |161| Set the default for `--remote` | Run `/remote-env` in your terminal. If you have a single environment, this command shows your current configuration. `/remote-env` only selects the default; add, edit, and archive environments from the web interface. |

150 162 


171apt update && apt install -y gh183apt update && apt install -y gh

172```184```

173 185 

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

175 

176If the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands to avoid blocking the session on an intermittent install failure.186If the script exits non-zero, the session fails to start. Append `|| true` to non-critical commands to avoid blocking the session on an intermittent install failure.

177 187 

188Keep the script's total runtime under roughly five minutes so the [environment cache](#environment-caching) can build. Run independent installs in parallel with `&` and `wait`. If a single download won't fit in the five-minute limit, move it to a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks) that launches it in the background.

189 

178<Note>190<Note>

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

180</Note>192</Note>

181 193 

194### Environment caching

195 

196The setup script runs the first time you start a session in an environment. After it completes, Anthropic snapshots the filesystem and reuses that snapshot as the starting point for later sessions. New sessions start with your dependencies, tools, and Docker images already on disk, and the setup script step is skipped. This keeps startup fast even when the script installs large toolchains or pulls container images.

197 

198The cache captures files, not running processes. Anything the setup script writes to disk carries over. Services or containers it starts do not, so start those per session by asking Claude or with a [SessionStart hook](#setup-scripts-vs-sessionstart-hooks).

199 

200The setup script runs again to rebuild the cache when you change the environment's setup script or allowed network hosts, and when the cache reaches its expiry after roughly seven days. Resuming an existing session never re-runs the setup script.

201 

202You don't need to enable caching or manage snapshots yourself.

203 

182### Setup scripts vs. SessionStart hooks204### Setup scripts vs. SessionStart hooks

183 205 

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


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

187 209 

188| | Setup scripts | SessionStart hooks |210| | Setup scripts | SessionStart hooks |

189| ------------- | ------------------------------------------------- | -------------------------------------------------------------- |211| ------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |

190| Attached to | The cloud environment | Your repository |212| Attached to | The cloud environment | Your repository |

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

192| Runs | Before Claude Code launches, on new sessions only | After Claude Code launches, on every session including resumed |214| Runs | Before Claude Code launches, when no [cached environment](#environment-caching) is available | After Claude Code launches, on every session including resumed |

193| Scope | Cloud environments only | Both local and cloud |215| Scope | Cloud environments only | Both local and cloud |

194 216 

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


235* **No cloud-only scoping**: hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.257* **No cloud-only scoping**: hooks run in both local and cloud sessions. To skip local execution, check the `CLAUDE_CODE_REMOTE` environment variable as shown above.

236* **Requires network access**: install commands need to reach package registries. If your environment uses **None** network access, these hooks fail. The [default allowlist](#default-allowed-domains) under **Trusted** covers npm, PyPI, RubyGems, and crates.io.258* **Requires network access**: install commands need to reach package registries. If your environment uses **None** network access, these hooks fail. The [default allowlist](#default-allowed-domains) under **Trusted** covers npm, PyPI, RubyGems, and crates.io.

237* **Proxy compatibility**: all outbound traffic passes through a [security proxy](#security-proxy). Some package managers don't work correctly with this proxy. Bun is a known example.259* **Proxy compatibility**: all outbound traffic passes through a [security proxy](#security-proxy). Some package managers don't work correctly with this proxy. Bun is a known example.

238* **Adds startup latency**: hooks run each time a session starts or resumes. Keep install scripts fast by checking whether dependencies are already present before reinstalling.260* **Adds startup latency**: hooks run each time a session starts or resumes, unlike setup scripts which benefit from [environment caching](#environment-caching). Keep install scripts fast by checking whether dependencies are already present before reinstalling.

239 261 

240To persist environment variables for subsequent Bash commands, write to the file at `$CLAUDE_ENV_FILE`. See [SessionStart hooks](/en/hooks#sessionstart) for details.262To persist environment variables for subsequent Bash commands, write to the file at `$CLAUDE_ENV_FILE`. See [SessionStart hooks](/en/hooks#sessionstart) for details.

241 263 

242Custom environment images and snapshots are not yet supported.264Replacing the base image with your own Docker image is not yet supported. Use a setup script to install what you need on top of the [provided image](#installed-tools), or run your image as a container alongside Claude with `docker compose`.

243 265 

244## Network access266## Network access

245 267 

246Network access controls outbound connections from the cloud environment. Each environment specifies one access level, and you can extend it with custom allowed domains. The default is **Trusted**, which allows package registries and other [allowlisted domains](#default-allowed-domains).268Network access controls outbound connections from the cloud environment. Each environment specifies one access level, and you can extend it with custom allowed domains. The default is **Trusted**, which allows package registries and other [allowlisted domains](#default-allowed-domains).

247 269 

270To change an environment's network access, [open it for editing](#configure-your-environment) and use the **Network access** selector in the dialog. There is no separate Environments page. The cloud icon appears wherever you start a cloud session or configure a [routine](/en/routines#environments-and-network-access).

271 

272<Note>

273 MCP connector traffic is routed through Anthropic's servers, so the connectors you enable on a session or routine work without adding their hosts to **Allowed domains**. Connectors are configured per session or per routine; remove any you don't need to limit which tools Claude can reach. This relies on the same Anthropic-bound channel noted under [Security and isolation](#security-and-isolation).

274</Note>

275 

248### Access levels276### Access levels

249 277 

250Choose an access level when you create or edit an environment:278Choose an access level when you create or edit an environment:


734* **Credential protection**: sensitive credentials such as git credentials or signing keys are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials.762* **Credential protection**: sensitive credentials such as git credentials or signing keys are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials.

735* **Secure analysis**: code is analyzed and modified within isolated VMs before creating PRs763* **Secure analysis**: code is analyzed and modified within isolated VMs before creating PRs

736 764 

765## Troubleshooting

766 

767For runtime API errors that appear in the conversation such as `API Error: 500`, `529 Overloaded`, `429`, or `Prompt is too long`, see the [Error reference](/en/errors). Those errors and their fixes are shared with the CLI and Desktop app. The sections below cover issues specific to cloud sessions.

768 

769### Session creation failed

770 

771If a new session fails to start with `Session creation failed` or stalls at provisioning, Claude Code could not allocate a cloud environment.

772 

773* Check [status.claude.com](https://status.claude.com) for cloud session incidents

774* Retry after a minute, as capacity is provisioned on demand

775* Confirm your repository is reachable. Private repositories require either the GitHub App installed with access to that repository, or a `gh` token synced via `/web-setup`. See [GitHub authentication options](#github-authentication-options).

776 

777### Remote Control session expired or access denied

778 

779`--teleport` connects through the same Remote Control session infrastructure that cloud sessions use, so authentication and session-expiry errors surface with Remote Control wording. You may see `Remote Control session has expired` or `Access denied`. The connection token is short-lived and scoped to your account.

780 

781* Run `/login` locally to refresh your credentials, then reconnect

782* Confirm you are signed in to the same account that owns the session

783* If you see `Remote Control may not be available for this organization`, your admin has not enabled remote sessions for your plan

784 

785### Environment expired

786 

787Cloud sessions stop after a period of inactivity and the underlying environment is reclaimed. From a local terminal, this surfaces as `Could not resume session ... its environment has expired. Creating a fresh session instead.` On the web, the session is marked expired in the session list.

788 

789Reopen the session from [claude.ai/code](https://claude.ai/code) to provision a fresh environment with your conversation history restored.

790 

737## Limitations791## Limitations

738 792 

739Before relying on cloud sessions for a workflow, account for these constraints:793Before relying on cloud sessions for a workflow, account for these constraints:


741* **Rate limits**: Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel consumes more rate limits proportionately. There is no separate compute charge for the cloud VM.795* **Rate limits**: Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel consumes more rate limits proportionately. There is no separate compute charge for the cloud VM.

742* **Repository authentication**: you can only move sessions from web to local when you are authenticated to the same account796* **Repository authentication**: you can only move sessions from web to local when you are authenticated to the same account

743* **Platform restrictions**: repository cloning and pull request creation require GitHub. Self-hosted [GitHub Enterprise Server](/en/github-enterprise-server) instances are supported for Team and Enterprise plans. GitLab, Bitbucket, and other non-GitHub repositories can be sent to cloud sessions as a [local bundle](#send-local-repositories-without-github), but the session can't push results back to the remote797* **Platform restrictions**: repository cloning and pull request creation require GitHub. Self-hosted [GitHub Enterprise Server](/en/github-enterprise-server) instances are supported for Team and Enterprise plans. GitLab, Bitbucket, and other non-GitHub repositories can be sent to cloud sessions as a [local bundle](#send-local-repositories-without-github), but the session can't push results back to the remote

798* **Organization IP allowlist**: cloud sessions call the Anthropic API from Anthropic-managed infrastructure, not your network. If your organization has [IP allowlisting](https://support.claude.com/en/articles/13200993-restrict-access-to-claude-with-ip-allowlisting) enabled, every cloud session fails with an authentication error. The same applies to [Code Review](/en/code-review) and [Routines](/en/routines). Contact [Anthropic support](https://support.claude.com/) to exempt Anthropic-hosted services from your organization's IP allowlist.

744 799 

745## Related resources800## Related resources

746 801 

802* [Ultraplan](/en/ultraplan): draft a plan in a cloud session and review it in your browser

803* [Ultrareview](/en/ultrareview): run a deep multi-agent code review in a cloud sandbox

747* [Routines](/en/routines): automate work on a schedule, via API call, or in response to GitHub events804* [Routines](/en/routines): automate work on a schedule, via API call, or in response to GitHub events

748* [Hooks configuration](/en/hooks): run scripts at session lifecycle events805* [Hooks configuration](/en/hooks): run scripts at session lifecycle events

749* [Settings reference](/en/settings): all configuration options806* [Settings reference](/en/settings): all configuration options

Details

9 9 

10Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects.10Claude Code reads instructions, settings, skills, subagents, and memory from your project directory and from `~/.claude` in your home directory. Commit project files to git to share them with your team; files in `~/.claude` are personal configuration that applies across all your projects.

11 11 

12If you set [`CLAUDE_CONFIG_DIR`](/en/env-vars), every `~/.claude` path on this page lives under that directory instead.12On Windows, `~/.claude` resolves to `%USERPROFILE%\.claude`. If you set [`CLAUDE_CONFIG_DIR`](/en/env-vars), every `~/.claude` path on this page lives under that directory instead.

13 13 

14Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them.14Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them.

15 15 

16This page is an interactive explorer: click files in the tree to see what each one does, when it loads, and an example. For a quick reference, see the [file reference table](#file-reference) below.16## Explore the directory

17 

18Click files in the tree to see what each one does, when it loads, and an example.

17 19 

18<ClaudeExplorer />20<ClaudeExplorer />

19 21 


25| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |27| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

26| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings that you can't override. See [server-managed settings](/en/server-managed-settings). |28| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings that you can't override. See [server-managed settings](/en/server-managed-settings). |

27| `CLAUDE.local.md` | Project root | Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`. |29| `CLAUDE.local.md` | Project root | Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`. |

28| Installed plugins | `~/.claude/plugins/` | Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. Orphaned versions are deleted 7 days after a plugin update or uninstall. See [plugin caching](/en/plugins-reference#plugin-caching-and-file-resolution). |30| Installed plugins | `~/.claude/plugins` | Cloned marketplaces, installed plugin versions, and per-plugin data, managed by `claude plugin` commands. Orphaned versions are deleted 7 days after a plugin update or uninstall. See [plugin caching](/en/plugins-reference#plugin-caching-and-file-resolution). |

29 31 

30`~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See [application data](#application-data) below.32`~/.claude` also holds data Claude Code writes as you work: transcripts, prompt history, file snapshots, caches, and logs. See [application data](#application-data) below.

31 33 

34## Choose the right file

35 

36Different kinds of customization live in different files. Use this table to find where a change belongs.

37 

38| You want to | Edit | Scope | Reference |

39| :------------------------------------------------- | :--------------------------------------- | :---------------- | :------------------------------------------------- |

40| Give Claude project context and conventions | `CLAUDE.md` | project or global | [Memory](/en/memory) |

41| Allow or block specific tool calls | `settings.json` `permissions` or `hooks` | project or global | [Permissions](/en/permissions), [Hooks](/en/hooks) |

42| Run a script before or after tool calls | `settings.json` `hooks` | project or global | [Hooks](/en/hooks) |

43| Set environment variables for the session | `settings.json` `env` | project or global | [Settings](/en/settings#available-settings) |

44| Keep personal overrides out of git | `settings.local.json` | project only | [Settings scopes](/en/settings#settings-files) |

45| Add a prompt or capability you invoke with `/name` | `skills/<name>/SKILL.md` | project or global | [Skills](/en/skills) |

46| Define a specialized subagent with its own tools | `agents/*.md` | project or global | [Subagents](/en/sub-agents) |

47| Connect external tools over MCP | `.mcp.json` | project only | [MCP](/en/mcp) |

48| Change how Claude formats responses | `output-styles/*.md` | project or global | [Output styles](/en/output-styles) |

49 

32## File reference50## File reference

33 51 

34This table lists every file the explorer covers. Project-scope files live in your repo under `.claude/` (or at the root for `CLAUDE.md`, `.mcp.json`, and `.worktreeinclude`). Global-scope files live in `~/.claude/` and apply across all projects.52This table lists every file the explorer covers. Project-scope files live in your repo under `.claude/` (or at the root for `CLAUDE.md`, `.mcp.json`, and `.worktreeinclude`). Global-scope files live in `~/.claude/` and apply across all projects.


46Click a filename to open that node in the explorer above.64Click a filename to open that node in the explorer above.

47 65 

48| File | Scope | Commit | What it does | Reference |66| File | Scope | Commit | What it does | Reference |

49| --------------------------------------------------- | ------------------ | ------ | ----------------------------------------------------- | -------------------------------------------------------------------- |67| --------------------------------------------------- | ------------------ | ------ | ----------------------------------------------------- | --------------------------------------------------------------- |

50| [`CLAUDE.md`](#ce-claude-md) | Project and global | ✓ | Instructions loaded every session | [Memory](/en/memory) |68| [`CLAUDE.md`](#ce-claude-md) | Project and global | ✓ | Instructions loaded every session | [Memory](/en/memory) |

51| [`rules/*.md`](#ce-rules) | Project and global | ✓ | Topic-scoped instructions, optionally path-gated | [Rules](/en/memory#organize-rules-with-claude/rules/) |69| [`rules/*.md`](#ce-rules) | Project and global | ✓ | Topic-scoped instructions, optionally path-gated | [Rules](/en/memory#organize-rules-with-claude/rules/) |

52| [`settings.json`](#ce-settings-json) | Project and global | ✓ | Permissions, hooks, env vars, model defaults | [Settings](/en/settings) |70| [`settings.json`](#ce-settings-json) | Project and global | ✓ | Permissions, hooks, env vars, model defaults | [Settings](/en/settings) |

53| [`settings.local.json`](#ce-settings-local-json) | Project only | | Your personal overrides, auto-gitignored | [Settings scopes](/en/settings#settings-files) |71| [`settings.local.json`](#ce-settings-local-json) | Project only | | Your personal overrides, auto-gitignored | [Settings scopes](/en/settings#settings-files) |

54| [`.mcp.json`](#ce-mcp-json) | Project only | ✓ | Team-shared MCP servers | [MCP scopes](/en/mcp#mcp-installation-scopes) |72| [`.mcp.json`](#ce-mcp-json) | Project only | ✓ | Team-shared MCP servers | [MCP scopes](/en/mcp#mcp-installation-scopes) |

55| [`.worktreeinclude`](#ce-worktreeinclude) | Project only | ✓ | Gitignored files to copy into new worktrees | [Worktrees](/en/common-workflows#copy-gitignored-files-to-worktrees) |73| [`.worktreeinclude`](#ce-worktreeinclude) | Project only | ✓ | Gitignored files to copy into new worktrees | [Worktrees](/en/worktrees#copy-gitignored-files-into-worktrees) |

56| [`skills/<name>/SKILL.md`](#ce-skills) | Project and global | ✓ | Reusable prompts invoked with `/name` or auto-invoked | [Skills](/en/skills) |74| [`skills/<name>/SKILL.md`](#ce-skills) | Project and global | ✓ | Reusable prompts invoked with `/name` or auto-invoked | [Skills](/en/skills) |

57| [`commands/*.md`](#ce-commands) | Project and global | ✓ | Single-file prompts; same mechanism as skills | [Skills](/en/skills) |75| [`commands/*.md`](#ce-commands) | Project and global | ✓ | Single-file prompts; same mechanism as skills | [Skills](/en/skills) |

58| [`output-styles/*.md`](#ce-output-styles) | Project and global | ✓ | Custom system-prompt sections | [Output styles](/en/output-styles) |76| [`output-styles/*.md`](#ce-output-styles) | Project and global | ✓ | Custom system-prompt sections | [Output styles](/en/output-styles) |


61| [`~/.claude.json`](#ce-claude-json) | Global only | | App state, OAuth, UI toggles, personal MCP servers | [Global config](/en/settings#global-config-settings) |79| [`~/.claude.json`](#ce-claude-json) | Global only | | App state, OAuth, UI toggles, personal MCP servers | [Global config](/en/settings#global-config-settings) |

62| [`projects/<project>/memory/`](#ce-global-projects) | Global only | | Auto memory: Claude's notes to itself across sessions | [Auto memory](/en/memory#auto-memory) |80| [`projects/<project>/memory/`](#ce-global-projects) | Global only | | Auto memory: Claude's notes to itself across sessions | [Auto memory](/en/memory#auto-memory) |

63| [`keybindings.json`](#ce-keybindings) | Global only | | Custom keyboard shortcuts | [Keybindings](/en/keybindings) |81| [`keybindings.json`](#ce-keybindings) | Global only | | Custom keyboard shortcuts | [Keybindings](/en/keybindings) |

82| [`themes/*.json`](#ce-themes) | Global only | | Custom color themes | [Custom themes](/en/terminal-config#create-a-custom-theme) |

64 83 

65## Check what loaded84## Troubleshoot configuration

66 

67The explorer shows what files can exist. To see what actually loaded in your current session, use these commands:

68 85 

69| Command | Shows |86If a setting, hook, or file isn't taking effect, see [Debug your configuration](/en/debug-your-config) for the inspection commands and a symptom-first lookup table.

70| -------------- | ------------------------------------------------------------------------------------- |

71| `/context` | Token usage by category: system prompt, memory files, skills, MCP tools, and messages |

72| `/memory` | Which CLAUDE.md and rules files loaded, plus auto-memory entries |

73| `/agents` | Configured subagents and their settings |

74| `/hooks` | Active hook configurations |

75| `/mcp` | Connected MCP servers and their status |

76| `/skills` | Available skills from project, user, and plugin sources |

77| `/permissions` | Current allow and deny rules |

78| `/doctor` | Installation and configuration diagnostics |

79 

80Run `/context` first for the overview, then the specific command for the area you want to investigate.

81 87 

82## Application data88## Application data

83 89 


88Files in the paths below are deleted on startup once they're older than [`cleanupPeriodDays`](/en/settings#available-settings). The default is 30 days.94Files in the paths below are deleted on startup once they're older than [`cleanupPeriodDays`](/en/settings#available-settings). The default is 30 days.

89 95 

90| Path under `~/.claude/` | Contents |96| Path under `~/.claude/` | Contents |

91| -------------------------------------------- | -------------------------------------------------------------------------------------------------- |97| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |

92| `projects/<project>/<session>.jsonl` | Full conversation transcript: every message, tool call, and tool result |98| `projects/<project>/<session>.jsonl` | Full conversation transcript: every message, tool call, and tool result |

93| `projects/<project>/<session>/tool-results/` | Large tool outputs spilled to separate files |99| `projects/<project>/<session>/tool-results/` | Large tool outputs spilled to separate files |

94| `file-history/<session>/` | Pre-edit snapshots of files Claude changed, used for [checkpoint restore](/en/checkpointing) |100| `file-history/<session>/` | Pre-edit snapshots of files Claude changed, used for [checkpoint restore](/en/checkpointing) |


96| `debug/` | Per-session debug logs, written only when you start with `--debug` or run `/debug` |102| `debug/` | Per-session debug logs, written only when you start with `--debug` or run `/debug` |

97| `paste-cache/`, `image-cache/` | Contents of large pastes and attached images |103| `paste-cache/`, `image-cache/` | Contents of large pastes and attached images |

98| `session-env/` | Per-session environment metadata |104| `session-env/` | Per-session environment metadata |

105| `tasks/` | Per-session task lists written by the task tools |

106| `shell-snapshots/` | Captured shell environment used by the Bash tool. Removed on clean exit. The sweep clears any left after a crash. |

107| `backups/` | Timestamped copies of `~/.claude.json` taken before config migrations |

99 108 

100### Kept until you delete them109### Kept until you delete them

101 110 


104| Path under `~/.claude/` | Contents |113| Path under `~/.claude/` | Contents |

105| ----------------------- | ------------------------------------------------------------------------------------- |114| ----------------------- | ------------------------------------------------------------------------------------- |

106| `history.jsonl` | Every prompt you've typed, with timestamp and project path. Used for up-arrow recall. |115| `history.jsonl` | Every prompt you've typed, with timestamp and project path. Used for up-arrow recall. |

107| `stats-cache.json` | Aggregated token and cost counts shown by `/cost` |116| `stats-cache.json` | Aggregated token and cost counts shown by `/usage` |

108| `backups/` | Timestamped copies of `~/.claude.json` taken before config migrations |

109| `todos/` | Legacy per-session task lists. No longer written by current versions; safe to delete. |117| `todos/` | Legacy per-session task lists. No longer written by current versions; safe to delete. |

110 118 

111`shell-snapshots/` holds runtime files removed when the session exits cleanly. Other small cache and lock files appear depending on which features you use and are safe to delete.119Other small cache and lock files appear depending on which features you use and are safe to delete.

112 120 

113### Plaintext storage121### Plaintext storage

114 122 


120 128 

121### Clear local data129### Clear local data

122 130 

123You can delete any of the application-data paths above at any time. New sessions are unaffected. The table below shows what you lose for past sessions.131Run `claude project purge` to delete the state Claude Code holds for one project:

132 

133* Transcripts and auto memory under `projects/`

134* Per-session `tasks/`, `debug/`, and `file-history/` entries

135* Matching prompt lines in `history.jsonl`

136* The project's entry in `~/.claude.json`

137 

138The command prints the full deletion plan and asks for confirmation before removing anything.

139 

140Preview the plan without deleting anything:

141 

142```bash theme={null}

143claude project purge ~/work/my-repo --dry-run

144```

145 

146Delete with a single confirmation prompt:

147 

148```bash theme={null}

149claude project purge ~/work/my-repo

150```

151 

152Omit the path to pick a project from an interactive list.

153 

154Skip the confirmation prompt for use in scripts:

155 

156```bash theme={null}

157claude project purge ~/work/my-repo --yes

158```

159 

160Pass `--all` instead of a path to purge state for every project at once, which deletes `history.jsonl` outright rather than filtering it. Pass `-i` to step through the deletion plan one item at a time.

161 

162The command leaves `shell-snapshots/` and `backups/` alone because those are not project-scoped, and warns about them in the plan output. It exits with status 1 if no state matches the given path.

163 

164You can also delete any of the application-data paths above by hand. New sessions are unaffected. The table below shows what you lose for past sessions.

124 165 

125| Delete | You lose |166| Delete | You lose |

126| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |167| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |

127| `~/.claude/projects/` | Resume, continue, and rewind for past sessions |168| `~/.claude/projects/` | Resume, continue, and rewind for past sessions |

128| `~/.claude/history.jsonl` | Up-arrow prompt recall |169| `~/.claude/history.jsonl` | Up-arrow prompt recall |

129| `~/.claude/file-history/` | Checkpoint restore for past sessions |170| `~/.claude/file-history/` | Checkpoint restore for past sessions |

130| `~/.claude/stats-cache.json` | Historical totals shown by `/cost` |171| `~/.claude/stats-cache.json` | Historical totals shown by `/usage` |

131| `~/.claude/backups/` | Rollback copies of `~/.claude.json` from past config migrations |172| `~/.claude/debug/`, `~/.claude/plans/`, `~/.claude/paste-cache/`, `~/.claude/image-cache/`, `~/.claude/session-env/`, `~/.claude/tasks/`, `~/.claude/shell-snapshots/`, `~/.claude/backups/` | Nothing user-facing |

132| `~/.claude/debug/`, `~/.claude/plans/`, `~/.claude/paste-cache/`, `~/.claude/image-cache/`, `~/.claude/session-env/` | Nothing user-facing |

133| `~/.claude/todos/` | Nothing. Legacy directory not written by current versions. |173| `~/.claude/todos/` | Nothing. Legacy directory not written by current versions. |

134 174 

135Don't delete `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/`: those hold your auth, preferences, and installed plugins.175Don't delete `~/.claude.json`, `~/.claude/settings.json`, or `~/.claude/plugins/`: those hold your auth, preferences, and installed plugins.

cli-reference.md +24 −18

Details

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

12 12 

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

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

15| `claude` | Start interactive session | `claude` |15| `claude` | Start interactive session | `claude` |

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

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


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

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

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

23| `claude install [version]` | Install or reinstall the native binary. Accepts a version like `2.1.118`, or `stable` or `latest`. See [Install a specific version](/en/setup#install-a-specific-version) | `claude install stable` |

23| `claude auth login` | Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription | `claude auth login --console` |24| `claude auth login` | Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription | `claude auth login --console` |

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

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


27| `claude auto-mode defaults` | Print the built-in [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied | `claude auto-mode defaults > rules.json` |28| `claude auto-mode defaults` | Print the built-in [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied | `claude auto-mode defaults > rules.json` |

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

29| `claude plugin` | Manage Claude Code [plugins](/en/plugins). Alias: `claude plugins`. See [plugin reference](/en/plugins-reference#cli-commands-reference) for subcommands | `claude plugin install code-review@claude-plugins-official` |30| `claude plugin` | Manage Claude Code [plugins](/en/plugins). Alias: `claude plugins`. See [plugin reference](/en/plugins-reference#cli-commands-reference) for subcommands | `claude plugin install code-review@claude-plugins-official` |

31| `claude project purge [path]` | Delete all local Claude Code state for a project: transcripts, task lists, debug logs, file-edit history, prompt history lines, and the project's entry in `~/.claude.json`. Omit `[path]` to pick from an interactive list. Flags: `--dry-run` to preview, `-y`/`--yes` to skip confirmation, `-i`/`--interactive` to confirm each item, `--all` for every project. See [Clear local data](/en/claude-directory#clear-local-data) | `claude project purge ~/work/repo --dry-run` |

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

31| `claude setup-token` | Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](/en/authentication#generate-a-long-lived-token) | `claude setup-token` |33| `claude setup-token` | Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](/en/authentication#generate-a-long-lived-token) | `claude setup-token` |

34| `claude ultrareview [target]` | Run [ultrareview](/en/ultrareview#run-ultrareview-non-interactively) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 30-minute default | `claude ultrareview 1234 --json` |

35 

36If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`.

32 37 

33## CLI flags38## CLI flags

34 39 

35Customize Claude Code's behavior with these command-line flags. `claude --help` does not list every flag, so a flag's absence from `--help` does not mean it is unavailable.40Customize Claude Code's behavior with these command-line flags. `claude --help` does not list every flag, so a flag's absence from `--help` does not mean it is unavailable.

36 41 

37| Flag | Description | Example |42| Flag | Description | Example |

38| :---------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |43| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |

39| `--add-dir` | Add additional working directories for Claude to read and edit files. Grants file access; most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from these directories. Validates each path exists as a directory | `claude --add-dir ../apps ../lib` |44| `--add-dir` | Add additional working directories for Claude to read and edit files. Grants file access; most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from these directories. Validates each path exists as a directory. To persist these directories across sessions, set [`permissions.additionalDirectories`](/en/settings#permission-settings) in settings | `claude --add-dir ../apps ../lib` |

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

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

42| `--allow-dangerously-skip-permissions` | Add `bypassPermissions` to the `Shift+Tab` mode cycle without starting in it. Lets you begin in a different mode like `plan` and switch to `bypassPermissions` later. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |47| `--allow-dangerously-skip-permissions` | Add `bypassPermissions` to the `Shift+Tab` mode cycle without starting in it. Lets you begin in a different mode like `plan` and switch to `bypassPermissions` later. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |


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

48| `--channels` | (Research preview) MCP servers whose [channel](/en/channels) notifications Claude should listen for in this session. Space-separated list of `plugin:<name>@<marketplace>` entries. Requires Claude.ai authentication | `claude --channels plugin:my-notifier@my-marketplace` |53| `--channels` | (Research preview) MCP servers whose [channel](/en/channels) notifications Claude should listen for in this session. Space-separated list of `plugin:<name>@<marketplace>` entries. Requires Claude.ai authentication | `claude --channels plugin:my-notifier@my-marketplace` |

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

50| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` |55| `--continue`, `-c` | Load the most recent conversation in the current directory. Includes sessions that added this directory with `/add-dir` | `claude --continue` |

51| `--dangerously-load-development-channels` | Enable [channels](/en/channels-reference#test-during-the-research-preview) that are not on the approved allowlist, for local development. Accepts `plugin:<name>@<marketplace>` and `server:<name>` entries. Prompts for confirmation | `claude --dangerously-load-development-channels server:webhook` |56| `--dangerously-load-development-channels` | Enable [channels](/en/channels-reference#test-during-the-research-preview) that are not on the approved allowlist, for local development. Accepts `plugin:<name>@<marketplace>` and `server:<name>` entries. Prompts for confirmation | `claude --dangerously-load-development-channels server:webhook` |

52| `--dangerously-skip-permissions` | Skip permission prompts. Equivalent to `--permission-mode bypassPermissions`. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) for what this does and does not skip | `claude --dangerously-skip-permissions` |57| `--dangerously-skip-permissions` | Skip permission prompts. Equivalent to `--permission-mode bypassPermissions`. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) for what this does and does not skip | `claude --dangerously-skip-permissions` |

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

54| `--debug-file <path>` | Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over `CLAUDE_CODE_DEBUG_LOGS_DIR` | `claude --debug-file /tmp/claude-debug.log` |59| `--debug-file <path>` | Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over `CLAUDE_CODE_DEBUG_LOGS_DIR` | `claude --debug-file /tmp/claude-debug.log` |

55| `--disable-slash-commands` | Disable all skills and commands for this session | `claude --disable-slash-commands` |60| `--disable-slash-commands` | Disable all skills and commands for this session | `claude --disable-slash-commands` |

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

57| `--effort` | Set the [effort level](/en/model-config#adjust-effort-level) for the current session. Options: `low`, `medium`, `high`, `max` (Opus 4.6 only). Session-scoped and does not persist to settings | `claude --effort high` |62| `--effort` | Set the [effort level](/en/model-config#adjust-effort-level) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. Overrides the [`effortLevel`](/en/settings#available-settings) setting for this session and does not persist | `claude --effort high` |

63| `--enable-auto-mode` | {/* max-version: 2.1.110 */}Removed in v2.1.111. Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it | `claude --permission-mode auto` |

58| `--exclude-dynamic-system-prompt-sections` | Move per-machine sections from the system prompt (working directory, environment info, memory paths, git status) into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads | `claude -p --exclude-dynamic-system-prompt-sections "query"` |64| `--exclude-dynamic-system-prompt-sections` | Move per-machine sections from the system prompt (working directory, environment info, memory paths, git status) into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads | `claude -p --exclude-dynamic-system-prompt-sections "query"` |

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

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

61| `--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` |67| `--from-pr` | Resume sessions linked to a specific pull request. Accepts a PR number, a GitHub or GitHub Enterprise PR URL, a GitLab merge request URL, or a Bitbucket pull request URL. Sessions are linked automatically when Claude creates the pull request | `claude --from-pr 123` |

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

63| `--init` | Run initialization hooks and start interactive mode | `claude --init` |69| `--init` | Run [Setup hooks](/en/hooks#setup) with the `init` matcher before the session (print mode only) | `claude -p --init "query"` |

64| `--init-only` | Run initialization hooks and exit (no interactive session) | `claude --init-only` |70| `--init-only` | Run [Setup](/en/hooks#setup) and `SessionStart` hooks, then exit without starting a conversation | `claude --init-only` |

65| `--include-hook-events` | Include all hook lifecycle events in the output stream. Requires `--output-format stream-json` | `claude -p --output-format stream-json --include-hook-events "query"` |71| `--include-hook-events` | Include all hook lifecycle events in the output stream. Requires `--output-format stream-json` | `claude -p --output-format stream-json --include-hook-events "query"` |

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

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

68| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |74| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |

69| `--maintenance` | Run maintenance hooks and start interactive mode | `claude --maintenance` |75| `--maintenance` | Run [Setup hooks](/en/hooks#setup) with the `maintenance` matcher before the session (print mode only) | `claude -p --maintenance "query"` |

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

71| `--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"` |77| `--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"` |

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

73| `--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` |79| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name. Overrides the [`model`](/en/settings#available-settings) setting and [`ANTHROPIC_MODEL`](/en/model-config#environment-variables) | `claude --model claude-sonnet-4-6` |

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

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

76| `--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"` |82| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed. Print mode only. The [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/en/env-vars) environment variable does the same in any mode | `claude -p --no-session-persistence "query"` |

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

78| `--enable-auto-mode` | Unlock [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) in the `Shift+Tab` cycle. Requires a Team, Enterprise, or API plan and Claude Sonnet 4.6 or Opus 4.6 | `claude --enable-auto-mode` |

79| `--permission-mode` | Begin in a specified [permission mode](/en/permission-modes). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files | `claude --permission-mode plan` |84| `--permission-mode` | Begin in a specified [permission mode](/en/permission-modes). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files | `claude --permission-mode plan` |

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

81| `--plugin-dir` | Load plugins from a directory for this session only. Each flag takes one path. Repeat the flag for multiple directories: `--plugin-dir A --plugin-dir B` | `claude --plugin-dir ./my-plugins` |86| `--plugin-dir` | Load a plugin from a directory or `.zip` archive for this session only. Each flag takes one path. Repeat the flag for multiple plugins: `--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |

87| `--plugin-url` | Fetch a plugin `.zip` archive from a URL for this session only. Repeat the flag for multiple plugins, or pass space-separated URLs in a single quoted value | `claude --plugin-url https://example.com/plugin.zip` |

82| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |88| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |

83| `--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"` |89| `--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"` |

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

85| `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated [Remote Control](/en/remote-control) session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect | `claude remote-control --remote-control-session-name-prefix dev-box` |91| `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated [Remote Control](/en/remote-control) session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect | `claude remote-control --remote-control-session-name-prefix dev-box` |

86| `--replay-user-messages` | Re-emit user messages from stdin back on stdout for acknowledgment. Requires `--input-format stream-json` and `--output-format stream-json` | `claude -p --input-format stream-json --output-format stream-json --replay-user-messages` |92| `--replay-user-messages` | Re-emit user messages from stdin back on stdout for acknowledgment. Requires `--input-format stream-json` and `--output-format stream-json` | `claude -p --input-format stream-json --output-format stream-json --replay-user-messages` |

87| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` |93| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session. Includes sessions that added this directory with `/add-dir` | `claude --resume auth-refactor` |

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

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

90| `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.json` |96| `--settings` | Path to a settings JSON file or an inline JSON string. Values you set here override the same keys in your `settings.json` files for this session. Keys you omit keep their file-based values. See [settings precedence](/en/settings#settings-precedence) | `claude --settings ./settings.json` |

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

92| `--system-prompt` | Replace the entire system prompt with custom text | `claude --system-prompt "You are a Python expert"` |98| `--system-prompt` | Replace the entire system prompt with custom text | `claude --system-prompt "You are a Python expert"` |

93| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt | `claude --system-prompt-file ./custom-prompt.txt` |99| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt | `claude --system-prompt-file ./custom-prompt.txt` |

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

95| `--teammate-mode` | Set how [agent team](/en/agent-teams) teammates display: `auto` (default), `in-process`, or `tmux`. See [Choose a display mode](/en/agent-teams#choose-a-display-mode) | `claude --teammate-mode in-process` |101| `--teammate-mode` | Set how [agent team](/en/agent-teams) teammates display: `auto` (default), `in-process`, or `tmux`. Overrides the [`teammateMode`](/en/settings#available-settings) setting for this session. See [Choose a display mode](/en/agent-teams#choose-a-display-mode) | `claude --teammate-mode in-process` |

96| `--tmux` | Create a tmux session for the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` for traditional tmux | `claude -w feature-auth --tmux` |102| `--tmux` | Create a tmux session for the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` for traditional tmux | `claude -w feature-auth --tmux` |

97| `--tools` | Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |103| `--tools` | Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |

98| `--verbose` | Enable verbose logging, shows full turn-by-turn output | `claude --verbose` |104| `--verbose` | Enable verbose logging, shows full turn-by-turn output. Overrides the [`viewMode`](/en/settings#available-settings) setting for this session | `claude --verbose` |

99| `--version`, `-v` | Output the version number | `claude -v` |105| `--version`, `-v` | Output the version number | `claude -v` |

100| `--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` |106| `--worktree`, `-w` | Start Claude in an isolated [git worktree](/en/worktrees) at `<repo>/.claude/worktrees/<name>`. If no name is given, one is auto-generated. Pass `#<number>` or a GitHub pull request URL to fetch that PR from `origin` and branch the worktree from it | `claude -w feature-auth` |

101 107 

102### System prompt flags108### System prompt flags

103 109 

code-review.md +62 −25

Details

29 29 

30Once an admin [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting `@claude review` [starts reviews on a PR](#manually-trigger-reviews) in any mode.30Once an admin [enables Code Review](#set-up-code-review) for your organization, reviews trigger when a PR opens, on every push, or when manually requested, depending on the repository's configured behavior. Commenting `@claude review` [starts reviews on a PR](#manually-trigger-reviews) in any mode.

31 31 

32When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found. If no issues are found, Claude posts a short confirmation comment on the PR.32When a review runs, multiple agents analyze the diff and surrounding code in parallel on Anthropic infrastructure. Each agent looks for a different class of issue, then a verification step checks candidates against actual code behavior to filter out false positives. The results are deduplicated, ranked by severity, and posted as inline comments on the specific lines where issues were found, with a summary in the review body. If no issues are found, Claude posts a short confirmation comment on the PR.

33 33 

34Reviews scale in cost with PR size and complexity, completing in 20 minutes on average. Admins can monitor review activity and spend via the [analytics dashboard](#view-usage).34Reviews scale in cost with PR size and complexity, completing in 20 minutes on average. Admins can monitor review activity and spend via the [analytics dashboard](#view-usage).

35 35 


141 141 

142## Customize reviews142## Customize reviews

143 143 

144Code Review reads two files from your repository to guide what it flags. Both are additive on top of the default correctness checks:144Code Review reads two files from your repository to guide what it flags. They differ in how strongly they influence the review:

145 145 

146* **`CLAUDE.md`**: shared project instructions that Claude Code uses for all tasks, not just reviews. Use it when guidance also applies to interactive Claude Code sessions.146* **`CLAUDE.md`**: shared project instructions that Claude Code uses for all tasks, not just reviews. Code Review reads it as project context and flags newly introduced violations as nits.

147* **`REVIEW.md`**: review-only guidance, read exclusively during code reviews. Use it for rules that are strictly about what to flag or skip during review and would clutter your general `CLAUDE.md`.147* **`REVIEW.md`**: review-only instructions, injected directly into every agent in the review pipeline as highest priority. Use it to change what gets flagged, at what severity, and how findings are reported.

148 148 

149### CLAUDE.md149### CLAUDE.md

150 150 

151Code Review reads your repository's `CLAUDE.md` files and treats newly-introduced violations as nit-level findings. This works bidirectionally: if your PR changes code in a way that makes a `CLAUDE.md` statement outdated, Claude flags that the docs need updating too.151Code Review reads your repository's `CLAUDE.md` files and treats newly introduced violations as [nit-level](#severity-levels) findings. This works bidirectionally: if your PR changes code in a way that makes a `CLAUDE.md` statement outdated, Claude flags that the docs need updating too.

152 152 

153Claude reads `CLAUDE.md` files at every level of your directory hierarchy, so rules in a subdirectory's `CLAUDE.md` apply only to files under that path. See the [memory documentation](/en/memory) for more on how `CLAUDE.md` works.153Claude reads `CLAUDE.md` files at every level of your directory hierarchy, so rules in a subdirectory's `CLAUDE.md` apply only to files under that path. See the [memory documentation](/en/memory) for more on how `CLAUDE.md` works.

154 154 


156 156 

157### REVIEW\.md157### REVIEW\.md

158 158 

159Add a `REVIEW.md` file to your repository root for review-specific rules. Use it to encode:159`REVIEW.md` is a file at your repository root that overrides how Code Review behaves on your repo. Its contents are injected into the system prompt of every agent in the review pipeline as the highest-priority instruction block, taking precedence over the default review guidance.

160 160 

161* Company or team style guidelines: "prefer early returns over nested conditionals"161Because it's pasted verbatim, `REVIEW.md` is plain instructions: [`@` import syntax](/en/memory#import-additional-files) is not expanded, and referenced files are not read into the prompt. Put the rules you want enforced directly in the file.

162* Language- or framework-specific conventions not covered by linters

163* Things Claude should always flag: "any new API route must have an integration test"

164* Things Claude should skip: "don't comment on formatting in generated code under `/gen/`"

165 162 

166Example `REVIEW.md`:163#### What you can tune

164 

165`REVIEW.md` is freeform markdown, so anything you can express as a review instruction is in scope. The patterns below have the most impact in practice.

166 

167**Severity**: redefine what 🔴 Important means for your repo. The default calibration targets production code; a docs repo, a config repo, or a prototype might want a much narrower definition. State explicitly which classes of finding are Important and which are Nit at most. You can also escalate in the other direction, for example treating any `CLAUDE.md` violation as Important rather than the default nit.

168 

169**Nit volume**: cap how many 🟡 Nit comments a single review posts. Prose and config files can be polished forever. A cap like "report at most five nits, mention the rest as a count in the summary" keeps reviews actionable.

170 

171**Skip rules**: list paths, branch patterns, and finding categories where Claude should post no findings. Common candidates are generated code, lockfiles, vendored dependencies, and machine-authored branches, along with anything your CI already enforces like linting or spellcheck. For paths that warrant some review but not full scrutiny, set a higher bar instead of skipping entirely: "in `scripts/`, only report if near-certain and severe."

172 

173**Repo-specific checks**: add rules you want flagged on every PR, like "new API routes must have an integration test." Because `REVIEW.md` is injected as highest priority, these land more reliably than the same rules in a long `CLAUDE.md`.

174 

175**Verification bar**: require evidence before a class of finding is posted. For example, "behavior claims need a `file:line` citation in the source, not an inference from naming" cuts false positives that would otherwise cost the author a round trip.

176 

177**Re-review convergence**: tell Claude how to behave when a PR has already been reviewed. A rule like "after the first review, suppress new nits and post Important findings only" stops a one-line fix from reaching round seven on style alone.

178 

179**Summary shape**: ask for the review body to open with a one-line tally such as `2 factual, 4 style`, and to lead with "no factual issues" when that's the case. The author wants to know the shape of the work before the details.

180 

181#### Example

182 

183This `REVIEW.md` recalibrates severity for a backend service, caps nits, skips generated files, and adds repo-specific checks.

167 184 

168```markdown theme={null}185```markdown theme={null}

169# Code Review Guidelines186# Review instructions

170 187 

171## Always check188## What Important means here

172- New API endpoints have corresponding integration tests189 

173- Database migrations are backward-compatible190Reserve Important for findings that would break behavior, leak data,

174- Error messages don't leak internal details to users191or block a rollback: incorrect logic, unscoped database queries, PII

192in logs or error messages, and migrations that aren't backward

193compatible. Style, naming, and refactoring suggestions are Nit at

194most.

195 

196## Cap the nits

197 

198Report at most five Nits per review. If you found more, say "plus N

199similar items" in the summary instead of posting them inline. If

200everything you found is a Nit, lead the summary with "No blocking

201issues."

202 

203## Do not report

175 204 

176## Style205- Anything CI already enforces: lint, formatting, type errors

177- Prefer `match` statements over chained `isinstance` checks206- Generated files under `src/gen/` and any `*.lock` file

178- Use structured logging, not f-string interpolation in log calls207- Test-only code that intentionally violates production rules

179 208 

180## Skip209## Always check

181- Generated files under `src/gen/`210 

182- Formatting-only changes in `*.lock` files211- New API routes have an integration test

212- Log lines don't include email addresses, user IDs, or request bodies

213- Database queries are scoped to the caller's tenant

183```214```

184 215 

185Claude auto-discovers `REVIEW.md` at the repository root. No configuration needed.216#### Keep it focused

217 

218Length has a cost: a long `REVIEW.md` dilutes the rules that matter most. Keep it to instructions that change review behavior, and leave general project context in `CLAUDE.md`.

186 219 

187## View usage220## View usage

188 221 


195| Feedback | Count of review comments that were auto-resolved because a developer addressed the issue |228| Feedback | Count of review comments that were auto-resolved because a developer addressed the issue |

196| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved |229| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved |

197 230 

198The repositories table in admin settings also shows average cost per review for each repo.231The repositories table in admin settings also shows average cost per review for each repo. Dashboard cost figures are estimates for monitoring activity; for invoice-accurate spend, refer to your Anthropic bill.

199 232 

200## Pricing233## Pricing

201 234 


209 242 

210In any mode, commenting `@claude review` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment. To run a single review without subscribing to future pushes, comment `@claude review once` instead.243In any mode, commenting `@claude review` [opts the PR into push-triggered reviews](#manually-trigger-reviews), so additional cost accrues per push after that comment. To run a single review without subscribing to future pushes, comment `@claude review once` instead.

211 244 

212Costs appear on your Anthropic bill regardless of whether your organization uses AWS Bedrock or Google Vertex AI for other Claude Code features. To set a monthly spend cap for Code Review, go to [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) and configure the limit for the Claude Code Review service.245Costs appear on your Anthropic bill regardless of whether your organization uses Amazon Bedrock or Google Vertex AI for other Claude Code features. To set a monthly spend cap for Code Review, go to [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage) and configure the limit for the Claude Code Review service.

213 246 

214Monitor spend via the weekly cost chart in [analytics](#view-usage) or the per-repo average cost column in admin settings.247Monitor spend via the weekly cost chart in [analytics](#view-usage) or the per-repo average cost column in admin settings.

215 248 


225 258 

226The **Re-run** button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.259The **Re-run** button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.

227 260 

261### Review didn't run and the PR shows a spend-cap message

262 

263When your organization's monthly spend cap is reached, Code Review posts a single comment on the PR explaining that the review was skipped. Reviews resume automatically at the start of the next billing period, or immediately when an admin raises the cap at [claude.ai/admin-settings/usage](https://claude.ai/admin-settings/usage).

264 

228### Find issues that aren't showing as inline comments265### Find issues that aren't showing as inline comments

229 266 

230If the check run title says issues were found but you don't see inline review comments on the diff, look in these other locations where findings are surfaced:267If the check run title says issues were found but you don't see inline review comments on the diff, look in these other locations where findings are surfaced:

commands.md +53 −26

Details

10 10 

11Type `/` to see every command available to you, or type `/` followed by letters to filter.11Type `/` to see every command available to you, or type `/` followed by letters to filter.

12 12 

13The table below lists all the commands included in Claude Code. Entries marked **[Skill](/en/skills#bundled-skills)** are bundled skills. They use the same mechanism as skills you write yourself: a prompt handed to Claude, which Claude can also invoke automatically when relevant. Everything else is a built-in command whose behavior is coded into the CLI. To add your own commands, see [skills](/en/skills).13A command is only recognized at the start of your message. Text that follows the command name is passed to it as arguments.

14 

15## Commands across a typical workflow

16 

17Most commands are useful at a specific point in a session, from setting up a project to shipping a change.

18 

19**First session in a repo.** Run `/init` to generate a starter `CLAUDE.md`, then `/memory` to refine it. Use `/mcp` and `/agents` to set up any servers or subagents the project needs, and `/permissions` to set the approval rules you want.

20 

21**During a task.** `/plan` switches into plan mode before a large change. `/model` and `/effort` adjust how much reasoning you're spending. When the conversation gets long, `/context` shows where the window is going and `/compact` summarizes it down; use `/btw` for a quick aside that shouldn't bloat history.

22 

23**Before you ship.** `/diff` shows what changed, `/simplify` reviews recent files and applies quality and efficiency fixes, and `/review` or `/security-review` give a deeper read-only pass.

14 24 

15Not every command appears for every user. Availability depends on your platform, plan, and environment. For example, `/desktop` only shows on macOS and Windows, and `/upgrade` only shows on Pro and Max plans.25**Between sessions.** `/clear` starts fresh on a new task while keeping project memory. `/resume` and `/branch` let you return to or fork an earlier conversation. `/teleport` pulls a web session into this terminal, and `/remote-control` lets you continue this local session from another device.

26 

27**When something is wrong.** `/rewind` rolls code and conversation back to a checkpoint. `/doctor` and `/debug` diagnose install and runtime issues, and `/feedback` reports a bug with session context attached.

28 

29## All commands

30 

31The table below lists all the commands included in Claude Code. Entries marked **[Skill](/en/skills#bundled-skills)** are bundled skills. They use the same mechanism as skills you write yourself: a prompt handed to Claude, which Claude can also invoke automatically when relevant. Everything else is a built-in command whose behavior is coded into the CLI. To add your own commands, see [skills](/en/skills).

16 32 

17In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.33In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

18 34 

35<Note>

36 Not every command appears for every user. Availability depends on your platform, plan, and environment. For example, `/desktop` only shows on macOS and Windows, and `/upgrade` only shows on Pro and Max plans.

37</Note>

38 

19| Command | Purpose |39| Command | Purpose |

20| :--------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |40| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

21| `/add-dir <path>` | Add a working directory for file access during the current session. Most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from the added directory |41| `/add-dir <path>` | Add a working directory for file access during the current session. Most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from the added directory. You can later resume the session from the added directory with `--continue` or `--resume` |

22| `/agents` | Manage [agent](/en/sub-agents) configurations |42| `/agents` | Manage [agent](/en/sub-agents) configurations |

23| `/autofix-pr [prompt]` | Spawn a [Claude Code on the web](/en/claude-code-on-the-web#auto-fix-pull-requests) session that watches the current branch's PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the remote session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web) |43| `/autofix-pr [prompt]` | Spawn a [Claude Code on the web](/en/claude-code-on-the-web#auto-fix-pull-requests) session that watches the current branch's PR and pushes fixes when CI fails or reviewers leave comments. Detects the open PR from your checked-out branch with `gh pr view`; to watch a different PR, check out its branch first. By default the remote session is told to fix every CI failure and review comment; pass a prompt to give it different instructions, for example `/autofix-pr only fix lint and type errors`. Requires the `gh` CLI and access to [Claude Code on the web](/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web) |

24| `/batch <instruction>` | **[Skill](/en/skills#bundled-skills).** Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one background agent per unit in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Each agent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React` |44| `/batch <instruction>` | **[Skill](/en/skills#bundled-skills).** Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one background agent per unit in an isolated [git worktree](/en/worktrees). Each agent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React` |

25| `/branch [name]` | Create a branch of the current conversation at this point. Switches you into the branch and preserves the original, which you can return to with `/resume`. Alias: `/fork` |45| `/branch [name]` | Create a branch of the current conversation at this point. Switches you into the branch and preserves the original, which you can return to with `/resume`. Alias: `/fork`. When [`CLAUDE_CODE_FORK_SUBAGENT`](/en/env-vars) is set, `/fork` instead spawns a [forked subagent](/en/sub-agents#fork-the-current-conversation) and is no longer an alias for this command |

26| `/btw <question>` | Ask a quick [side question](/en/interactive-mode#side-questions-with-btw) without adding to the conversation |46| `/btw <question>` | Ask a quick [side question](/en/interactive-mode#side-questions-with-%2Fbtw) without adding to the conversation |

27| `/chrome` | Configure [Claude in Chrome](/en/chrome) settings |47| `/chrome` | Configure [Claude in Chrome](/en/chrome) settings |

28| `/claude-api` | **[Skill](/en/skills#bundled-skills).** Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Managed Agents reference. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk` |48| `/claude-api [migrate\|managed-agents-onboard]` | **[Skill](/en/skills#bundled-skills).** Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Managed Agents reference. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic` or `@anthropic-ai/sdk`. Run `/claude-api migrate` to upgrade existing Claude API code to a newer model: Claude asks which files to scan and which model to target, then updates model IDs, thinking configuration, and other parameters that changed between versions. Run `/claude-api managed-agents-onboard` for an interactive walkthrough that creates a new Managed Agent from scratch |

29| `/clear` | Clear conversation history and free up context. Aliases: `/reset`, `/new` |49| `/clear [name]` | Start a new conversation with empty context. The previous conversation stays available in `/resume`. Pass a name to label the previous conversation in the `/resume` picker. To free up context while continuing the same conversation, use `/compact` instead. Aliases: `/reset`, `/new` |

30| `/color [color\|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset |50| `/color [color\|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset, or run with no argument to pick a random color. When [Remote Control](/en/remote-control) is connected, the color syncs to claude.ai/code |

31| `/compact [instructions]` | Compact conversation with optional focus instructions |51| `/compact [instructions]` | Free up context by summarizing the conversation so far. Optionally pass focus instructions for the summary. See [how compaction handles rules, skills, and memory files](/en/context-window#what-survives-compaction) |

32| `/config` | Open the [Settings](/en/settings) interface to adjust theme, model, [output style](/en/output-styles), and other preferences. Alias: `/settings` |52| `/config` | Open the [Settings](/en/settings) interface to adjust theme, model, [output style](/en/output-styles), and other preferences. Alias: `/settings` |

33| `/context` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings |53| `/context [all]` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings. In [fullscreen mode](/en/fullscreen) the per-item breakdown is collapsed to keep the grid visible. Pass `all` to expand it |

34| `/copy [N]` | Copy the last assistant response to clipboard. Pass a number `N` to copy the Nth-latest response: `/copy 2` copies the second-to-last. When code blocks are present, shows an interactive picker to select individual blocks or the full response. Press `w` in the picker to write the selection to a file instead of the clipboard, which is useful over SSH |54| `/copy [N]` | Copy the last assistant response to clipboard. Pass a number `N` to copy the Nth-latest response: `/copy 2` copies the second-to-last. When code blocks are present, shows an interactive picker to select individual blocks or the full response. Press `w` in the picker to write the selection to a file instead of the clipboard, which is useful over SSH |

35| `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details |55| `/cost` | Alias for `/usage` |

36| `/debug [description]` | **[Skill](/en/skills#bundled-skills).** Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis |56| `/debug [description]` | **[Skill](/en/skills#bundled-skills).** Enable debug logging for the current session and troubleshoot issues by reading the session debug log. Debug logging is off by default unless you started with `claude --debug`, so running `/debug` mid-session starts capturing logs from that point forward. Optionally describe the issue to focus the analysis |

37| `/desktop` | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app` |57| `/desktop` | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app` |

38| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files |58| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files |

39| `/doctor` | Diagnose and verify your Claude Code installation and settings. Results show with status icons. Press `f` to have Claude fix any reported issues |59| `/doctor` | Diagnose and verify your Claude Code installation and settings. Results show with status icons. Press `f` to have Claude fix any reported issues |

40| `/effort [low\|medium\|high\|max\|auto]` | Set the model [effort level](/en/model-config#adjust-effort-level). `low`, `medium`, and `high` persist across sessions. `max` applies to the current session only and requires Opus 4.6. `auto` resets to the model default. Without an argument, shows the current level. Takes effect immediately without waiting for the current response to finish |60| `/effort [level\|auto]` | Set the model [effort level](/en/model-config#adjust-effort-level). Accepts `low`, `medium`, `high`, `xhigh`, or `max`; available levels depend on the model and `max` is session-only. `auto` resets to the model default. Without an argument, opens an interactive slider; use left and right arrows to pick a level and `Enter` to apply. Takes effect immediately without waiting for the current response to finish |

41| `/exit` | Exit the CLI. Alias: `/quit` |61| `/exit` | Exit the CLI. Alias: `/quit` |

42| `/export [filename]` | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file |62| `/export [filename]` | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file |

43| `/extra-usage` | Configure extra usage to keep working when rate limits are hit |63| `/extra-usage` | Configure extra usage to keep working when rate limits are hit |

44| `/fast [on\|off]` | Toggle [fast mode](/en/fast-mode) on or off |64| `/fast [on\|off]` | Toggle [fast mode](/en/fast-mode) on or off |

45| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |65| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |

66| `/fewer-permission-prompts` | **[Skill](/en/skills#bundled-skills).** Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project `.claude/settings.json` to reduce permission prompts |

67| `/focus` | Toggle the focus view, which shows only your last prompt, a one-line tool-call summary with edit diffstats, and the final response. The selection persists across sessions; set [`viewMode`](/en/settings#available-settings) in settings to override it. Only available in [fullscreen rendering](/en/fullscreen) |

68| `/heapdump` | Write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`, or your home directory on Linux without a Desktop folder, for diagnosing high memory usage. See [troubleshooting](/en/troubleshooting#high-cpu-or-memory-usage) |

46| `/help` | Show help and available commands |69| `/help` | Show help and available commands |

47| `/hooks` | View [hook](/en/hooks) configurations for tool events |70| `/hooks` | View [hook](/en/hooks) configurations for tool events |

48| `/ide` | Manage IDE integrations and show status |71| `/ide` | Manage IDE integrations and show status |


57| `/mcp` | Manage MCP server connections and OAuth authentication |80| `/mcp` | Manage MCP server connections and OAuth authentication |

58| `/memory` | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/en/memory#auto-memory), and view auto-memory entries |81| `/memory` | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/en/memory#auto-memory), and view auto-memory entries |

59| `/mobile` | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` |82| `/mobile` | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` |

60| `/model [model]` | Select or change the AI model. For models that support it, use left/right arrows to [adjust effort level](/en/model-config#adjust-effort-level). The change takes effect immediately without waiting for the current response to finish |83| `/model [model]` | Select or change the AI model. For models that support it, use left/right arrows to [adjust effort level](/en/model-config#adjust-effort-level). With no argument, opens a picker that asks for confirmation when the conversation has prior output, since the next response re-reads the full history without cached context. Once confirmed, the change applies without waiting for the current response to finish |

61| `/passes` | Share a free week of Claude Code with friends. Only visible if your account is eligible |84| `/passes` | Share a free week of Claude Code with friends. Only visible if your account is eligible |

62| `/permissions` | Manage allow, ask, and deny rules for tool permissions. Opens an interactive dialog where you can view rules by scope, add or remove rules, manage working directories, and review [recent auto mode denials](/en/permissions#review-auto-mode-denials). Alias: `/allowed-tools` |85| `/permissions` | Manage allow, ask, and deny rules for tool permissions. Opens an interactive dialog where you can view rules by scope, add or remove rules, manage working directories, and review [recent auto mode denials](/en/auto-mode-config#review-denials). Alias: `/allowed-tools` |

63| `/plan [description]` | Enter plan mode directly from the prompt. Pass an optional description to enter plan mode and immediately start with that task, for example `/plan fix the auth bug` |86| `/plan [description]` | Enter plan mode directly from the prompt. Pass an optional description to enter plan mode and immediately start with that task, for example `/plan fix the auth bug` |

64| `/plugin` | Manage Claude Code [plugins](/en/plugins) |87| `/plugin` | Manage Claude Code [plugins](/en/plugins) |

65| `/powerup` | Discover Claude Code features through quick interactive lessons with animated demos |88| `/powerup` | Discover Claude Code features through quick interactive lessons with animated demos |

66| `/pr-comments [PR]` | {/* max-version: 2.1.90 */}Removed in v2.1.91. Ask Claude directly to view pull request comments instead. On earlier versions, fetches and displays comments from a GitHub pull request; automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI |89| `/pr-comments [PR]` | {/* max-version: 2.1.90 */}Removed in v2.1.91. Ask Claude directly to view pull request comments instead. On earlier versions, fetches and displays comments from a GitHub pull request; automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI |

67| `/privacy-settings` | View and update your privacy settings. Only available for Pro and Max plan subscribers |90| `/privacy-settings` | View and update your privacy settings. Only available for Pro and Max plan subscribers |

91| `/radio` | Open Claude FM lo-fi radio in your browser. Prints the stream URL when no browser is available. Not available on Bedrock, Vertex, or Foundry |

92| `/recap` | Generate a one-line summary of the current session on demand. See [Session recap](/en/interactive-mode#session-recap) for the automatic recap that appears after you've been away |

68| `/release-notes` | View the changelog in an interactive version picker. Select a specific version to see its release notes, or choose to show all versions |93| `/release-notes` | View the changelog in an interactive version picker. Select a specific version to see its release notes, or choose to show all versions |

69| `/reload-plugins` | Reload all active [plugins](/en/plugins) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors |94| `/reload-plugins` | Reload all active [plugins](/en/plugins) to apply pending changes without restarting. Reports counts for each reloaded component and flags any load errors |

70| `/remote-control` | Make this session available for [remote control](/en/remote-control) from claude.ai. Alias: `/rc` |95| `/remote-control` | Make this session available for [remote control](/en/remote-control) from claude.ai. Alias: `/rc` |

71| `/remote-env` | Configure the default remote environment for [web sessions started with `--remote`](/en/claude-code-on-the-web#configure-your-environment) |96| `/remote-env` | Configure the default remote environment for [web sessions started with `--remote`](/en/claude-code-on-the-web#configure-your-environment) |

72| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history |97| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history |

73| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. Alias: `/continue` |98| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. Alias: `/continue` |

74| `/review` | Deprecated. Install the [`code-review` plugin](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-review) instead: `claude plugin install code-review@claude-plugins-official` |99| `/review [PR]` | Review a pull request locally in your current session. For a deeper cloud-based review, see [`/ultrareview`](/en/ultrareview) |

75| `/rewind` | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](/en/checkpointing). Alias: `/checkpoint` |100| `/rewind` | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](/en/checkpointing). Aliases: `/checkpoint`, `/undo` |

76| `/sandbox` | Toggle [sandbox mode](/en/sandboxing). Available on supported platforms only |101| `/sandbox` | Toggle [sandbox mode](/en/sandboxing). Available on supported platforms only |

77| `/schedule [description]` | Create, update, list, or run [routines](/en/routines). Claude walks you through the setup conversationally |102| `/schedule [description]` | Create, update, list, or run [routines](/en/routines), which execute on Anthropic-managed cloud infrastructure. Claude walks you through the setup conversationally. Alias: `/routines` |

78| `/security-review` | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure |103| `/security-review` | Analyze pending changes on the current branch for security vulnerabilities. Reviews the git diff and identifies risks like injection, auth issues, and data exposure |

79| `/setup-bedrock` | Configure [Amazon Bedrock](/en/amazon-bedrock) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Bedrock users can also access this wizard from the login screen |104| `/setup-bedrock` | Configure [Amazon Bedrock](/en/amazon-bedrock) authentication, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_BEDROCK=1` is set. First-time Bedrock users can also access this wizard from the login screen |

80| `/setup-vertex` | Configure [Google Vertex AI](/en/google-vertex-ai) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Vertex AI users can also access this wizard from the login screen |105| `/setup-vertex` | Configure [Google Vertex AI](/en/google-vertex-ai) authentication, project, region, and model pins through an interactive wizard. Only visible when `CLAUDE_CODE_USE_VERTEX=1` is set. First-time Vertex AI users can also access this wizard from the login screen |

81| `/simplify [focus]` | **[Skill](/en/skills#bundled-skills).** Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency` |106| `/simplify [focus]` | **[Skill](/en/skills#bundled-skills).** Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency` |

82| `/skills` | List available [skills](/en/skills) |107| `/skills` | List available [skills](/en/skills). Press `t` to sort by token count. Press `Space` to [hide a skill from Claude or the `/` menu](/en/skills#override-skill-visibility-from-settings), then `Enter` to save |

83| `/stats` | Visualize daily usage, session history, streaks, and model preferences |108| `/stats` | Alias for `/usage`. Opens on the Stats tab |

84| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity. Works while Claude is responding, without waiting for the current response to finish |109| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity. Works while Claude is responding, without waiting for the current response to finish |

85| `/statusline` | Configure Claude Code's [status line](/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |110| `/statusline` | Configure Claude Code's [status line](/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |

86| `/stickers` | Order Claude Code stickers |111| `/stickers` | Order Claude Code stickers |

87| `/tasks` | List and manage background tasks. Also available as `/bashes` |112| `/tasks` | List and manage background tasks. Also available as `/bashes` |

88| `/team-onboarding` | Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly |113| `/team-onboarding` | Generate a team onboarding guide from your Claude Code usage history. Claude analyzes your sessions, commands, and MCP server usage from the past 30 days and produces a markdown guide a teammate can paste as a first message to get set up quickly. For claude.ai subscribers on Pro, Max, Team, and Enterprise plans, also returns a share link teammates can open directly in Claude Code |

89| `/teleport` | Pull a [Claude Code on the web](/en/claude-code-on-the-web#from-web-to-terminal) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription |114| `/teleport` | Pull a [Claude Code on the web](/en/claude-code-on-the-web#from-web-to-terminal) session into this terminal: opens a picker, then fetches the branch and conversation. Also available as `/tp`. Requires a claude.ai subscription |

90| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Alacritty, or Warp |115| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Cursor, Windsurf, Alacritty, or Zed |

91| `/theme` | Change the color theme. Includes light and dark variants, colorblind-accessible (daltonized) themes, and ANSI themes that use your terminal's color palette |116| `/theme` | Change the color theme. Includes an `auto` option that matches your terminal's light or dark background, light and dark variants, colorblind-accessible (daltonized) themes, ANSI themes that use your terminal's color palette, and any [custom themes](/en/terminal-config#create-a-custom-theme) from `~/.claude/themes/` or plugins. Select **New custom theme…** to create one |

117| `/tui [default\|fullscreen]` | Set the terminal UI renderer and relaunch into it with your conversation intact. `fullscreen` enables the [flicker-free alt-screen renderer](/en/fullscreen). With no argument, prints the active renderer |

92| `/ultraplan <prompt>` | Draft a plan in an [ultraplan](/en/ultraplan) session, review it in your browser, then execute remotely or send it back to your terminal |118| `/ultraplan <prompt>` | Draft a plan in an [ultraplan](/en/ultraplan) session, review it in your browser, then execute remotely or send it back to your terminal |

119| `/ultrareview [PR]` | Run a deep, multi-agent code review in a cloud sandbox with [ultrareview](/en/ultrareview). Includes 3 free runs on Pro and Max through May 5, 2026, then requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

93| `/upgrade` | Open the upgrade page to switch to a higher plan tier |120| `/upgrade` | Open the upgrade page to switch to a higher plan tier |

94| `/usage` | Show plan usage limits and rate limit status |121| `/usage` | Show session cost, plan usage limits, and activity stats. See the [cost tracking guide](/en/costs#using-the-%2Fusage-command) for subscription-specific details. `/cost` and `/stats` are aliases |

95| `/vim` | {/* max-version: 2.1.91 */}Removed in v2.1.92. To toggle between Vim and Normal editing modes, use `/config` → Editor mode |122| `/vim` | {/* max-version: 2.1.91 */}Removed in v2.1.92. To toggle between Vim and Normal editing modes, use `/config` → Editor mode |

96| `/voice` | Toggle push-to-talk [voice dictation](/en/voice-dictation). Requires a Claude.ai account |123| `/voice [hold\|tap\|off]` | Toggle [voice dictation](/en/voice-dictation), or enable it in a specific mode. Requires a Claude.ai account |

97| `/web-setup` | Connect your GitHub account to [Claude Code on the web](/en/web-quickstart#connect-from-your-terminal) using your local `gh` CLI credentials. `/schedule` prompts for this automatically if GitHub isn't connected |124| `/web-setup` | Connect your GitHub account to [Claude Code on the web](/en/web-quickstart#connect-from-your-terminal) using your local `gh` CLI credentials. `/schedule` prompts for this automatically if GitHub isn't connected |

98 125 

99## MCP prompts126## MCP prompts

common-workflows.md +93 −575

Details

6 6 

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

8 8 

9This page covers practical workflows for everyday development: exploring unfamiliar code, debugging, refactoring, writing tests, creating PRs, and managing sessions. Each section includes example prompts you can adapt to your own projects. For higher-level patterns and tips, see [Best practices](/en/best-practices).9This page collects short recipes for everyday development. For higher-level guidance on prompting and context management, see [Best practices](/en/best-practices).

10 10 

11## Understand new codebases11This page covers:

12 12 

13### Get a quick codebase overview13* [Prompt recipes](#prompt-recipes) for exploring code, fixing bugs, refactoring, testing, PRs, and documentation

14* [Resume previous conversations](#resume-previous-conversations) so a task can span multiple sittings

15* [Run parallel sessions with worktrees](#run-parallel-sessions-with-worktrees) so concurrent edits don't collide

16* [Plan before editing](#plan-before-editing) to review changes before they touch disk

17* [Delegate research to subagents](#delegate-research-to-subagents) to keep your main context clean

18* [Pipe Claude into scripts](#pipe-claude-into-scripts) for CI and batch processing

19 

20## Prompt recipes

21 

22These are prompt patterns for everyday tasks like exploring unfamiliar code, debugging, refactoring, writing tests, and creating PRs. Each works in any Claude Code surface; adapt the wording to your project.

23 

24### Understand new codebases

25 

26#### Get a quick codebase overview

14 27 

15Suppose you've just joined a new project and need to understand its structure quickly.28Suppose you've just joined a new project and need to understand its structure quickly.

16 29 


56 * Request a glossary of project-specific terms69 * Request a glossary of project-specific terms

57</Tip>70</Tip>

58 71 

59### Find relevant code72#### Find relevant code

60 73 

61Suppose you need to locate code related to a specific feature or functionality.74Suppose you need to locate code related to a specific feature or functionality.

62 75 


90 103 

91***104***

92 105 

93## Fix bugs efficiently106### Fix bugs efficiently

94 107 

95Suppose you've encountered an error message and need to find and fix its source.108Suppose you've encountered an error message and need to find and fix its source.

96 109 


124 137 

125***138***

126 139 

127## Refactor code140### Refactor code

128 141 

129Suppose you need to update old code to use modern patterns and practices.142Suppose you need to update old code to use modern patterns and practices.

130 143 


164 177 

165***178***

166 179 

167## Use specialized subagents180### Work with tests

168 

169Suppose you want to use specialized AI subagents to handle specific tasks more effectively.

170 

171<Steps>

172 <Step title="View available subagents">

173 ```text theme={null}

174 /agents

175 ```

176 

177 This shows all available subagents and lets you create new ones.

178 </Step>

179 

180 <Step title="Use subagents automatically">

181 Claude Code automatically delegates appropriate tasks to specialized subagents:

182 

183 ```text theme={null}

184 review my recent code changes for security issues

185 ```

186 

187 ```text theme={null}

188 run all tests and fix any failures

189 ```

190 </Step>

191 

192 <Step title="Explicitly request specific subagents">

193 ```text theme={null}

194 use the code-reviewer subagent to check the auth module

195 ```

196 

197 ```text theme={null}

198 have the debugger subagent investigate why users can't log in

199 ```

200 </Step>

201 

202 <Step title="Create custom subagents for your workflow">

203 ```text theme={null}

204 /agents

205 ```

206 

207 Then select "Create New subagent" and follow the prompts to define:

208 

209 * A unique identifier that describes the subagent's purpose (for example, `code-reviewer`, `api-designer`).

210 * When Claude should use this agent

211 * Which tools it can access

212 * A system prompt describing the agent's role and behavior

213 </Step>

214</Steps>

215 

216<Tip>

217 Tips:

218 

219 * Create project-specific subagents in `.claude/agents/` for team sharing

220 * Use descriptive `description` fields to enable automatic delegation

221 * Limit tool access to what each subagent actually needs

222 * Check the [subagents documentation](/en/sub-agents) for detailed examples

223</Tip>

224 

225***

226 

227## Use Plan Mode for safe code analysis

228 

229Plan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely. In Plan Mode, Claude uses [`AskUserQuestion`](/en/tools-reference) to gather requirements and clarify your goals before proposing a plan.

230 

231### When to use Plan Mode

232 

233* **Multi-step implementation**: When your feature requires making edits to many files

234* **Code exploration**: When you want to research the codebase thoroughly before changing anything

235* **Interactive development**: When you want to iterate on the direction with Claude

236 

237### How to use Plan Mode

238 

239**Turn on Plan Mode during a session**

240 

241You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes.

242 

243If you are in Normal Mode, **Shift+Tab** first switches into Auto-Accept Mode, indicated by `⏵⏵ accept edits on` at the bottom of the terminal. A subsequent **Shift+Tab** will switch into Plan Mode, indicated by `⏸ plan mode on`.

244 

245**Start a new session in Plan Mode**

246 

247To start a new session in Plan Mode, use the `--permission-mode plan` flag:

248 

249```bash theme={null}

250claude --permission-mode plan

251```

252 

253**Run "headless" queries in Plan Mode**

254 

255You can also run a query in Plan Mode directly with `-p` (that is, in ["headless mode"](/en/headless)):

256 

257```bash theme={null}

258claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"

259```

260 

261### Example: Planning a complex refactor

262 

263```bash theme={null}

264claude --permission-mode plan

265```

266 

267```text theme={null}

268I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.

269```

270 

271Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:

272 

273```text theme={null}

274What about backward compatibility?

275```

276 

277```text theme={null}

278How should we handle database migration?

279```

280 

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

282 

283When you accept a plan, Claude automatically names the session from the plan content. The name appears on the prompt bar and in the session picker. If you've already set a name with `--name` or `/rename`, accepting a plan won't overwrite it.

284 

285### Configure Plan Mode as default

286 

287```json theme={null}

288// .claude/settings.json

289{

290 "permissions": {

291 "defaultMode": "plan"

292 }

293}

294```

295 

296See [settings documentation](/en/settings#available-settings) for more configuration options.

297 

298***

299 

300## Work with tests

301 181 

302Suppose you need to add tests for uncovered code.182Suppose you need to add tests for uncovered code.

303 183 


333 213 

334***214***

335 215 

336## Create pull requests216### Create pull requests

337 217 

338You can create pull requests by asking Claude directly ("create a pr for my changes"), or guide Claude through it step-by-step:218You can create pull requests by asking Claude directly ("create a pr for my changes"), or guide Claude through it step-by-step:

339 219 


357 </Step>237 </Step>

358</Steps>238</Steps>

359 239 

360When 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>`.240When you create a PR using `gh pr create`, the session is automatically linked to that PR. To return to it later, run `claude --from-pr <number>` or paste the PR URL into the [`/resume` picker](/en/sessions#use-the-session-picker) search.

361 241 

362<Tip>242<Tip>

363 Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations.243 Review Claude's generated PR before submitting and ask Claude to highlight potential risks or considerations.

364</Tip>244</Tip>

365 245 

366## Handle documentation246### Handle documentation

367 247 

368Suppose you need to add or update documentation for your code.248Suppose you need to add or update documentation for your code.

369 249 


403 283 

404***284***

405 285 

406## Work with images286### Work in notes and non-code folders

287 

288Claude Code works in any directory. Run it inside a notes vault, a documentation folder, or any collection of markdown files to search, edit, and reorganize content the same way you would code.

289 

290The `.claude/` directory and `CLAUDE.md` sit alongside other tools' config directories without conflict. Claude reads files fresh on each tool call, so it sees edits you make in another application the next time it reads that file.

291 

292***

293 

294### Work with images

407 295 

408Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content.296Suppose you need to work with images in your codebase, and you want Claude's help analyzing image content.

409 297 


463 351 

464***352***

465 353 

466## Reference files and directories354### Reference files and directories

467 355 

468Use @ to quickly include files or directories without waiting for Claude to read them.356Use @ to quickly include files or directories without waiting for Claude to read them.

469 357 


504 392 

505***393***

506 394 

507## Use extended thinking (thinking mode)395### Run Claude on a schedule

508 

509[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`.

510 

511Additionally, Opus 4.6 and Sonnet 4.6 support adaptive reasoning: instead of a fixed thinking token budget, the model dynamically allocates thinking based on your [effort level](/en/model-config#adjust-effort-level) setting. Extended thinking and adaptive reasoning work together to give you control over how deeply Claude reasons before responding.

512 

513Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches.

514 

515<Note>

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

517</Note>

518 

519### Configure thinking mode

520 

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

522 

523| Scope | How to configure | Details |

524| ------------------------ | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

525| **Effort level** | Run `/effort`, adjust in `/model`, or set [`CLAUDE_CODE_EFFORT_LEVEL`](/en/env-vars) | Control thinking depth for Opus 4.6 and Sonnet 4.6. See [Adjust effort level](/en/model-config#adjust-effort-level) |

526| **`ultrathink` keyword** | Include "ultrathink" anywhere in your prompt | Sets effort to high for that turn on Opus 4.6 and Sonnet 4.6. Useful for one-off tasks requiring deep reasoning without permanently changing your effort setting |

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

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

529| **Limit token budget** | Set [`MAX_THINKING_TOKENS`](/en/env-vars) environment variable | Limit the thinking budget to a specific number of tokens. On Opus 4.6 and Sonnet 4.6, only `0` applies unless adaptive reasoning is disabled. Example: `export MAX_THINKING_TOKENS=10000` |

530 

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

532 

533### How extended thinking works

534 

535Extended 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.

536 

537**With Opus 4.6 and Sonnet 4.6**, thinking uses adaptive reasoning: the model dynamically allocates thinking tokens based on the [effort level](/en/model-config#adjust-effort-level) you select. This is the recommended way to tune the tradeoff between speed and reasoning depth.

538 

539**With older models**, thinking uses a fixed token budget drawn from your output allocation. The budget varies by model; see [`MAX_THINKING_TOKENS`](/en/env-vars) for per-model ceilings. You can limit the budget with that environment variable, or disable thinking entirely via `/config` or the `Option+T`/`Alt+T` toggle.

540 

541On Opus 4.6 and Sonnet 4.6, [adaptive reasoning](/en/model-config#adjust-effort-level) controls thinking depth, so `MAX_THINKING_TOKENS` only applies when set to `0` to disable thinking, or when `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` reverts these models to the fixed budget. See [environment variables](/en/env-vars).

542 

543<Warning>

544 You're charged for all thinking tokens used even when thinking summaries are redacted. In interactive mode, thinking appears as a collapsed stub by default. Set `showThinkingSummaries: true` in `settings.json` to show full summaries.

545</Warning>

546 

547***

548 

549## Resume previous conversations

550 

551When starting Claude Code, you can resume a previous session:

552 

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

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

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

556 

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

558 

559Sessions are stored per project directory. The `/resume` picker shows interactive sessions from the same git repository, including worktrees. When you select a session from another worktree of the same repository, Claude Code resumes it directly without requiring you to switch directories first. Sessions created by `claude -p` or SDK invocations do not appear in the picker, but you can still resume one by passing its session ID or custom name to `claude --resume <session-id-or-name>`. Custom names set with `--name` or `/rename` are accepted in addition to session IDs.

560 

561### Name your sessions

562 

563Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features.

564 

565<Steps>

566 <Step title="Name the session">

567 Name a session at startup with `-n`:

568 

569 ```bash theme={null}

570 claude -n auth-refactor

571 ```

572 

573 Or use `/rename` during a session, which also shows the name on the prompt bar:

574 

575 ```text theme={null}

576 /rename auth-refactor

577 ```

578 

579 You can also rename any session from the picker: run `/resume`, navigate to a session, and press `R`.

580 </Step>

581 

582 <Step title="Resume by name later">

583 From the command line:

584 

585 ```bash theme={null}

586 claude --resume auth-refactor

587 ```

588 

589 Or from inside an active session:

590 

591 ```text theme={null}

592 /resume auth-refactor

593 ```

594 </Step>

595</Steps>

596 

597### Use the session picker

598 

599The `/resume` command (or `claude --resume` without arguments) opens an interactive session picker with these features:

600 

601**Keyboard shortcuts in the picker:**

602 

603| Shortcut | Action |

604| :-------- | :------------------------------------------------ |

605| `↑` / `↓` | Navigate between sessions |

606| `→` / `←` | Expand or collapse grouped sessions |

607| `Enter` | Select and resume the highlighted session |

608| `P` | Preview the session content |

609| `R` | Rename the highlighted session |

610| `/` | Search to filter sessions |

611| `A` | Toggle between current directory and all projects |

612| `B` | Filter to sessions from your current git branch |

613| `Esc` | Exit the picker or search mode |

614 

615**Session organization:**

616 

617The picker displays sessions with helpful metadata:

618 

619* Session name or initial prompt

620* Time elapsed since last activity

621* Message count

622* Git branch (if applicable)

623 

624Forked sessions (created with `/branch`, `/rewind`, or `--fork-session`) are grouped together under their root session, making it easier to find related conversations.

625 

626<Tip>

627 Tips:

628 

629 * **Name sessions early**: Use `/rename` when starting work on a distinct task: it's much easier to find "payment-integration" than "explain this function" later

630 * Use `--continue` for quick access to your most recent conversation in the current directory

631 * Use `--resume session-name` when you know which session you need

632 * Use `--resume` (without a name) when you need to browse and select

633 * For scripts, use `claude --continue --print "prompt"` to resume in non-interactive mode

634 * Press `P` in the picker to preview a session before resuming it

635 * The resumed conversation starts with the same model and configuration as the original

636 

637 How it works:

638 

639 1. **Conversation Storage**: All conversations are automatically saved locally with their full message history

640 2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context

641 3. **Tool State**: Tool usage and results from the previous conversation are preserved

642 4. **Context Restoration**: The conversation resumes with all previous context intact

643</Tip>

644 

645***

646 

647## Run parallel Claude Code sessions with Git worktrees

648 

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

650 

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

652 

653```bash theme={null}

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

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

656claude --worktree feature-auth

657 

658# Start another session in a separate worktree

659claude --worktree bugfix-123

660```

661 

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

663 

664```bash theme={null}

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

666claude --worktree

667```

668 

669Worktrees are created at `<repo>/.claude/worktrees/<name>` and branch from the default remote branch, which is where `origin/HEAD` points. The worktree branch is named `worktree-<name>`.

670 

671The base branch is not configurable through a Claude Code flag or setting. `origin/HEAD` is a reference stored in your local `.git` directory that Git set once when you cloned. If the repository's default branch later changes on GitHub or GitLab, your local `origin/HEAD` keeps pointing at the old one, and worktrees will branch from there. To re-sync your local reference with whatever the remote currently considers its default:

672 

673```bash theme={null}

674git remote set-head origin -a

675```

676 

677This is a standard Git command that only updates your local `.git` directory. Nothing on the remote server changes. If you want worktrees to base off a specific branch rather than the remote's default, set it explicitly with `git remote set-head origin your-branch-name`.

678 

679For full control over how worktrees are created, including choosing a different base per invocation, configure a [WorktreeCreate hook](/en/hooks#worktreecreate). The hook replaces Claude Code's default `git worktree` logic entirely, so you can fetch and branch from whatever ref you need.

680 

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

682 

683### Subagent worktrees

684 

685Subagents can also use worktree isolation to work in parallel without conflicts. Ask Claude to "use worktrees for your agents" or configure it in a [custom subagent](/en/sub-agents#supported-frontmatter-fields) by adding `isolation: worktree` to the agent's frontmatter. Each subagent gets its own worktree that is automatically cleaned up when the subagent finishes without changes.

686 

687### Worktree cleanup

688 

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

690 

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

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

693 

694Subagent worktrees orphaned by a crash or an interrupted parallel run are removed automatically at startup once they are older than your [`cleanupPeriodDays`](/en/settings#available-settings) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep.

695 

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

697 

698<Tip>

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

700</Tip>

701 

702### Copy gitignored files to worktrees

703 

704Git worktrees are fresh checkouts, so they don't include untracked files like `.env` or `.env.local` from your main repository. To automatically copy these files when Claude creates a worktree, add a `.worktreeinclude` file to your project root.

705 

706The file uses `.gitignore` syntax to list which files to copy. Only files that match a pattern and are also gitignored get copied, so tracked files are never duplicated.

707 

708```text .worktreeinclude theme={null}

709.env

710.env.local

711config/secrets.json

712```

713 

714This applies to worktrees created with `--worktree`, subagent worktrees, and parallel sessions in the [desktop app](/en/desktop#work-in-parallel-with-sessions).

715 

716### Manage worktrees manually

717 

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

719 

720```bash theme={null}

721# Create a worktree with a new branch

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

723 

724# Create a worktree with an existing branch

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

726 

727# Start Claude in the worktree

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

729 

730# Clean up when done

731git worktree list

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

733```

734 

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

736 

737<Tip>

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

739</Tip>

740 

741### Non-git version control

742 

743Worktree isolation works with git by default. For other version control systems like SVN, Perforce, or Mercurial, configure [WorktreeCreate and WorktreeRemove hooks](/en/hooks#worktreecreate) to provide custom worktree creation and cleanup logic. When configured, these hooks replace the default git behavior when you use `--worktree`, so [`.worktreeinclude`](#copy-gitignored-files-to-worktrees) is not processed. Copy any local configuration files inside your hook script instead.

744 

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

746 

747***

748 

749## Get notified when Claude needs your attention

750 

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

752 

753<Steps>

754 <Step title="Add the hook to your settings">

755 Open `~/.claude/settings.json` and add a `Notification` hook that calls your platform's native notification command:

756 

757 <Tabs>

758 <Tab title="macOS">

759 ```json theme={null}

760 {

761 "hooks": {

762 "Notification": [

763 {

764 "matcher": "",

765 "hooks": [

766 {

767 "type": "command",

768 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

769 }

770 ]

771 }

772 ]

773 }

774 }

775 ```

776 </Tab>

777 

778 <Tab title="Linux">

779 ```json theme={null}

780 {

781 "hooks": {

782 "Notification": [

783 {

784 "matcher": "",

785 "hooks": [

786 {

787 "type": "command",

788 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

789 }

790 ]

791 }

792 ]

793 }

794 }

795 ```

796 </Tab>

797 

798 <Tab title="Windows">

799 ```json theme={null}

800 {

801 "hooks": {

802 "Notification": [

803 {

804 "matcher": "",

805 "hooks": [

806 {

807 "type": "command",

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

809 }

810 ]

811 }

812 ]

813 }

814 }

815 ```

816 </Tab>

817 </Tabs>

818 

819 If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than overwriting. You can also ask Claude to write the hook for you by describing what you want in the CLI.

820 </Step>

821 

822 <Step title="Optionally narrow the matcher">

823 By default the hook fires on all notification types. To fire only for specific events, set the `matcher` field to one of these values:

824 

825 | Matcher | Fires when |

826 | :------------------- | :---------------------------------------------- |

827 | `permission_prompt` | Claude needs you to approve a tool use |

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

829 | `auth_success` | Authentication completes |

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

831 </Step>

832 

833 <Step title="Verify the hook">

834 Type `/hooks` and select `Notification` to confirm the hook appears. Selecting it shows the command that will run. To test it end-to-end, ask Claude to run a command that requires permission and switch away from the terminal, or ask Claude to trigger a notification directly.

835 </Step>

836</Steps>

837 

838For the complete event schema and notification types, see the [Notification reference](/en/hooks#notification).

839 

840***

841 

842## Use Claude as a unix-style utility

843 

844### Add Claude to your verification process

845 

846Suppose you want to use Claude Code as a linter or code reviewer.

847 

848**Add Claude to your build script:**

849 

850```json theme={null}

851// package.json

852{

853 ...

854 "scripts": {

855 ...

856 "lint:claude": "claude -p 'you are a linter. please look at the changes vs. main and report any issues related to typos. report the filename and line number on one line, and a description of the issue on the second line. do not return any other text.'"

857 }

858}

859```

860 

861<Tip>

862 Tips:

863 

864 * Use Claude for automated code review in your CI/CD pipeline

865 * Customize the prompt to check for specific issues relevant to your project

866 * Consider creating multiple scripts for different types of verification

867</Tip>

868 

869### Pipe in, pipe out

870 

871Suppose you want to pipe data into Claude, and get back data in a structured format.

872 

873**Pipe data through Claude:**

874 

875```bash theme={null}

876cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

877```

878 

879<Tip>

880 Tips:

881 

882 * Use pipes to integrate Claude into existing shell scripts

883 * Combine with other Unix tools for powerful workflows

884 * Consider using `--output-format` for structured output

885</Tip>

886 

887### Control output format

888 

889Suppose you need Claude's output in a specific format, especially when integrating Claude Code into scripts or other tools.

890 

891<Steps>

892 <Step title="Use text format (default)">

893 ```bash theme={null}

894 cat data.txt | claude -p 'summarize this data' --output-format text > summary.txt

895 ```

896 

897 This outputs just Claude's plain text response (default behavior).

898 </Step>

899 

900 <Step title="Use JSON format">

901 ```bash theme={null}

902 cat code.py | claude -p 'analyze this code for bugs' --output-format json > analysis.json

903 ```

904 

905 This outputs a JSON array of messages with metadata including cost and duration.

906 </Step>

907 

908 <Step title="Use streaming JSON format">

909 ```bash theme={null}

910 cat log.txt | claude -p 'parse this log file for errors' --output-format stream-json

911 ```

912 

913 This outputs a series of JSON objects in real-time as Claude processes the request. Each message is a valid JSON object, but the entire output is not valid JSON if concatenated.

914 </Step>

915</Steps>

916 

917<Tip>

918 Tips:

919 

920 * Use `--output-format text` for simple integrations where you just need Claude's response

921 * Use `--output-format json` when you need the full conversation log

922 * Use `--output-format stream-json` for real-time output of each conversation turn

923</Tip>

924 

925***

926 

927## Run Claude on a schedule

928 396 

929Suppose you want Claude to handle a task automatically on a recurring basis, like reviewing open PRs every morning, auditing dependencies weekly, or checking for CI failures overnight.397Suppose you want Claude to handle a task automatically on a recurring basis, like reviewing open PRs every morning, auditing dependencies weekly, or checking for CI failures overnight.

930 398 


935| [Routines](/en/routines) | Anthropic-managed infrastructure | Tasks that should run even when your computer is off. Can also trigger on API calls or GitHub events in addition to a schedule. Configure at [claude.ai/code/routines](https://claude.ai/code/routines). |403| [Routines](/en/routines) | Anthropic-managed infrastructure | Tasks that should run even when your computer is off. Can also trigger on API calls or GitHub events in addition to a schedule. Configure at [claude.ai/code/routines](https://claude.ai/code/routines). |

936| [Desktop scheduled tasks](/en/desktop-scheduled-tasks) | Your machine, via the desktop app | Tasks that need direct access to local files, tools, or uncommitted changes. |404| [Desktop scheduled tasks](/en/desktop-scheduled-tasks) | Your machine, via the desktop app | Tasks that need direct access to local files, tools, or uncommitted changes. |

937| [GitHub Actions](/en/github-actions) | Your CI pipeline | Tasks tied to repo events like opened PRs, or cron schedules that should live alongside your workflow config. |405| [GitHub Actions](/en/github-actions) | Your CI pipeline | Tasks tied to repo events like opened PRs, or cron schedules that should live alongside your workflow config. |

938| [`/loop`](/en/scheduled-tasks) | The current CLI session | Quick polling while a session is open. Tasks are cancelled when you exit. |406| [`/loop`](/en/scheduled-tasks) | The current CLI session | Quick polling while a session is open. Tasks stop when you start a new conversation; `--resume` and `--continue` restore unexpired ones. |

939 407 

940<Tip>408<Tip>

941 When writing prompts for scheduled tasks, be explicit about what success looks like and what to do with results. The task runs autonomously, so it can't ask clarifying questions. For example: "Review open PRs labeled `needs-review`, leave inline comments on any issues, and post a summary in the `#eng-reviews` Slack channel."409 When writing prompts for scheduled tasks, be explicit about what success looks like and what to do with results. The task runs autonomously, so it can't ask clarifying questions. For example: "Review open PRs labeled `needs-review`, leave inline comments on any issues, and post a summary in the `#eng-reviews` Slack channel."


943 411 

944***412***

945 413 

946## Ask Claude about its capabilities414### Ask Claude about its capabilities

947 415 

948Claude has built-in access to its documentation and can answer questions about its own features and limitations.416Claude has built-in access to its documentation and can answer questions about its own features and limitations.

949 417 

950### Example questions418#### Example questions

951 419 

952```text theme={null}420```text theme={null}

953can Claude Code create pull requests?421can Claude Code create pull requests?


987 455 

988***456***

989 457 

458## Resume previous conversations

459 

460When a task spans multiple sittings, pick up where you left off instead of re-explaining context. Claude Code saves every conversation locally.

461 

462```bash theme={null}

463claude --continue

464```

465 

466This resumes the most recent session in the current directory; if there isn't one yet, it prints `No conversation found to continue` and exits. Use `claude --resume` to choose from a list, or `/resume` from inside a running session. See [Manage sessions](/en/sessions) for naming, branching, and the full picker reference.

467 

468## Run parallel sessions with worktrees

469 

470Work on a feature in one terminal while Claude fixes a bug in another, without the edits colliding. Each worktree is a separate checkout on its own branch.

471 

472```bash theme={null}

473claude --worktree feature-auth

474```

475 

476Run the same command with a different name in a second terminal to start an isolated parallel session. See [Worktrees](/en/worktrees) for cleanup, `.worktreeinclude`, and non-git VCS support.

477 

478## Plan before editing

479 

480For changes you want to review before they touch disk, switch to plan mode. Claude reads files and proposes a plan but makes no edits until you approve.

481 

482```bash theme={null}

483claude --permission-mode plan

484```

485 

486You can also press `Shift+Tab` mid-session to toggle into plan mode. See [Plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) for the approval flow and editing the plan in your text editor.

487 

488## Delegate research to subagents

489 

490Exploring a large codebase fills your context with file reads. Delegate the exploration so only the findings come back.

491 

492```text theme={null}

493use a subagent to investigate how our auth system handles token refresh

494```

495 

496The subagent reads files in its own context window and reports a summary. See [Subagents](/en/sub-agents) for defining custom agents with their own tools and prompts.

497 

498## Pipe Claude into scripts

499 

500Run Claude non-interactively for CI, pre-commit hooks, or batch processing. Stdin and stdout work like any Unix tool.

501 

502```bash theme={null}

503git log --oneline -20 | claude -p "summarize these recent commits"

504```

505 

506See [Non-interactive mode](/en/headless) for output formats, permission flags, and fan-out patterns.

507 

990## Next steps508## Next steps

991 509 

992<CardGroup cols={2}>510<CardGroup cols={2}>


994 Patterns for getting the most out of Claude Code512 Patterns for getting the most out of Claude Code

995 </Card>513 </Card>

996 514 

997 <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">515 <Card title="Manage sessions" icon="rotate-left" href="/en/sessions">

998 Understand the agentic loop and context management516 Resume, name, and branch conversations

999 </Card>517 </Card>

1000 518 

1001 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">519 <Card title="Worktrees" icon="code-branch" href="/en/worktrees">

1002 Add skills, hooks, MCP, subagents, and plugins520 Run isolated parallel sessions

1003 </Card>521 </Card>

1004 522 

1005 <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">523 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">

1006 Clone the development container reference implementation524 Add skills, hooks, MCP, subagents, and plugins

1007 </Card>525 </Card>

1008</CardGroup>526</CardGroup>

communications-kit.md +525 −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# Communications kit

6 

7> Launch announcements, drip-campaign messages, and FAQ responses for rolling Claude Code out to your engineering organization.

8 

9This page is for administrators and engineering leads rolling Claude Code out to a team. It provides copy-ready launch announcements, a tips-and-tricks drip campaign, and one-line FAQ responses for the questions you will be asked most.

10 

11<Note>

12 Treat everything here as draft copy, not finished copy. Rewrite each message in your organization's voice, swap the example tasks for real bugs and modules from your own codebase, and replace the `[bracketed placeholders]` before sending. The announcements that drive adoption are the ones that read like someone at your company wrote them.

13</Note>

14 

15## Launch communications

16 

17One announcement in two formats, plus two optional variants. Pick whichever fits your rollout and rewrite it from there.

18 

19### Before you send

20 

21Work through this checklist before the announcement goes out. Each item closes a gap that otherwise turns into a launch-day support thread.

22 

23| Item | Why it matters |

24| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |

25| `#claude-code` channel created and linked in the message | Gives questions one place to land |

26| Install command tested on at least one machine in your environment | Catches proxy or firewall issues before everyone hits them at once |

27| Security and data-handling link ready ([Data usage](/en/data-usage) or your internal equivalent) | "Where does my code go?" will be the first reply |

28| One concrete first task chosen, a real bug or file in your codebase | Generic examples don't convert; "fix the flaky test in `auth_test.go`" does |

29| A named owner for the channel for the first 48 hours | Unanswered launch-day questions kill momentum |

30| A C-suite sponsor lined up to send or co-sign the announcement | Exec-sent launches consistently see higher first-week adoption than admin-sent ones |

31 

32### The announcement

33 

34Use this as your standard org-wide rollout message. It covers what Claude Code is, gives a two-minute install path, hands readers one concrete task to try, and answers "where does my code go?" before anyone has to ask.

35 

36<Tabs>

37 <Tab title="Email">

38 ```text theme={null}

39 Subject: Claude Code is live for [Engineering / your team]

40 

41 Team,

42 

43 As of today you have access to Claude Code, an AI coding agent that runs in

44 your terminal, reads your actual codebase, and works through real tasks end

45 to end: debugging, refactors, tests, PRs. It is not autocomplete and it is

46 not a chat window. It edits files, runs your commands, and asks permission

47 before anything risky.

48 

49 Get running in two minutes:

50 

51 curl -fsSL https://claude.ai/install.sh | bash

52 cd <your-repo>

53 claude

54 

55 Then run /init once. Claude reads your project and writes a CLAUDE.md with

56 your build commands and conventions, so you stop re-explaining the basics.

57 

58 Then try one of these on the repo you are already in:

59 

60 - "The test in [file] is flaky. Figure out why and fix it"

61 - "Walk me through how [module] handles [X]"

62 - "Look at my working diff and tell me what's risky before I push"

63 

64 Where your code goes: Claude Code runs in your terminal and talks directly

65 to Anthropic's API, with no third-party servers in the loop. It asks before

66 editing files or running commands. Under our Enterprise agreement, Anthropic

67 does not use your code or prompts to train its models.

68 Details: https://code.claude.com/docs/en/data-usage

69 https://code.claude.com/docs/en/security

70 

71 Where to go with questions: #claude-code. [Owner name] is watching it

72 this week.

73 

74 - [Name]

75 

76 P.S. Prefer your editor? There is a VS Code extension and a JetBrains

77 plugin. Same agent, no terminal required.

78 ```

79 </Tab>

80 

81 <Tab title="Slack or Teams">

82 ```markdown theme={null}

83 🚀 *Claude Code is live for [team]*

84 

85 AI coding agent, runs in your terminal, reads your repo, does real work:

86 bugs, refactors, tests, PRs. Asks before it touches anything.

87 

88 `curl -fsSL https://claude.ai/install.sh | bash` → `cd your-repo` → `claude`

89 

90 *First thing to try* → run `/init`, then: "the test in [file] is flaky,

91 figure out why and fix it."

92 

93 🔒 Runs in your terminal, talks only to Anthropic's API. Under our

94 Enterprise plan your code and prompts are not used to train models.

95 Data usage → https://code.claude.com/docs/en/data-usage

96 

97 📚 Quickstart · VS Code · Free 1-hr course

98 https://code.claude.com/docs/en/quickstart

99 https://code.claude.com/docs/en/vs-code

100 https://anthropic.skilljar.com/claude-code-in-action

101 

102 Questions → this thread. [Owner] is on point.

103 ```

104 </Tab>

105</Tabs>

106 

107### Executive sponsor variant

108 

109Send this from your sponsoring executive, such as the CTO, CIO, or SVP Engineering, under their name and from their account. Launches that go out under an exec's name consistently see higher open rates and faster first-week activation than the same message from an admin or tooling team. It signals a company priority rather than an optional experiment.

110 

111This version is deliberately stripped to one ask: install it and run it on one real task. The exec's job is to make the ask land; the standard announcement and `#claude-code` handle the how.

112 

113<Tabs>

114 <Tab title="Email">

115 ```text theme={null}

116 Subject: One thing I'd like every engineer to try this week

117 

118 Team,

119 

120 We have turned on Claude Code for all of engineering. It is an AI agent

121 that works directly in your terminal, on your actual codebase, and the

122 early results from teams already using it are strong enough that I want

123 everyone on it this week.

124 

125 I am asking for ten minutes:

126 

127 curl -fsSL https://claude.ai/install.sh | bash

128 cd <your-repo>

129 claude

130 

131 Then hand it one real task: the bug you have been putting off, or "walk me

132 through how [module] works."

133 

134 That is the whole ask. [Owner name] and team are in #claude-code for

135 anything you hit along the way.

136 

137 - [Exec Name]

138 [Title]

139 ```

140 </Tab>

141 

142 <Tab title="Slack or Teams">

143 ```markdown theme={null}

144 📣 *From [Exec Name]: one thing to try this week*

145 

146 We have turned on *Claude Code* for all of engineering. Early results are

147 strong enough that I am asking everyone to give it ten minutes on real

148 work this week.

149 

150 `curl -fsSL https://claude.ai/install.sh | bash` → `cd your-repo` →

151 `claude` → hand it one real task.

152 

153 That's it. Questions → #claude-code.

154 ```

155 </Tab>

156</Tabs>

157 

158### Pilot group variant

159 

160Use for a phased rollout. Send to the pilot cohort only.

161 

162```text theme={null}

163Subject: You're in the Claude Code pilot

164 

165[Name / team],

166 

167You are in the first wave of Claude Code at [company]. We picked this group

168because you will put it on real problems and tell us the truth about it.

169 

170The ask: use it on at least one real task this week, then drop a note in

171#claude-code-pilot covering what worked, what was annoying, and what

172surprised you. That feedback decides how we roll it out to everyone else.

173 

174[Continue with "Get running in two minutes" from the standard announcement]

175 

176One extra thing for pilots: on your first multi-file change, press Shift+Tab

177until you see "plan". Claude will lay out exactly what it intends to do

178before it touches a file. It is the fastest way to calibrate how much to

179trust it.

180```

181 

182### Champion recruitment DM

183 

184After launch, DM the two or three people who are most active in `#claude-code`.

185 

186```text theme={null}

187Hey [name], your #claude-code posts are doing more for adoption than my

188announcement did. A couple of people told me your [thread / screenshot]

189was why they actually tried it.

190 

191Want to make that semi-official? Low lift: mostly keep posting what you

192are posting, plus first crack at new features and a direct line to the

193Anthropic team. I can share a short playbook if you're in.

194```

195 

196## Tips and tricks campaign

197 

198Ready-to-paste Slack or Teams messages designed to drive feature activation after launch. Each follows the same pattern: a hook, the payoff, a "try it now" prompt, and a docs link. Drip them one or two a week in `#claude-code`, or pick the handful that match your team's gaps. They stand alone with no required order.

199 

200Copy the message body from each block directly into Slack or Teams. Replace `[bracketed placeholders]` before sending.

201 

202### Get started

203 

204**Choosing the right model**

205 

206```markdown theme={null}

207🎯 *Tip: Match the model to the moment*

208 

209Using Opus to fix a typo burns compute. Using Haiku for a 12-file refactor

210is asking for a re-do.

211 

212Claude Code runs on the same models as the Claude app, and you can switch

213mid-session. *Sonnet* is the workhorse default for everyday feature work,

214bugs, tests, and reviews. Reach for *Opus* on large refactors, gnarly

215debugging, or anything high-stakes. Drop to *Haiku* for quick questions,

216formatting, and mechanical edits where speed wins.

217 

218*Try it now:* type `/model` and pick Sonnet if you haven't already. It is

219the right default for most tasks.

220 

221📖 Model configuration → https://code.claude.com/docs/en/model-config

222```

223 

224| Model | Best for |

225| ------ | ----------------------------------------------------------------------------------------- |

226| Opus | Large-scale refactors, complex debugging, architecture decisions, high-stakes changes |

227| Sonnet | Everyday feature work, bug fixes, tests, documentation, code review. Recommended default. |

228| Haiku | Quick questions, formatting, mechanical edits, rapid iteration |

229 

230**Quick wins to try first**

231 

232```markdown theme={null}

233🚀 *Tip: Three things to try in your first 10 minutes*

234 

235Installed Claude Code but not sure what to actually ask it? Start with the

236stuff that has been bugging you all week.

237 

238 - Fix something annoying: "the test in [file] is flaky, figure out why"

239 - Get oriented in code you didn't write: "walk me through how [module] works"

240 - Sanity-check before you push: "look at my working diff and tell me what

241 looks risky"

242 

243None of these need setup. Just `cd` into your repo and run `claude`.

244 

245*Try it now:* pick the bug you have been avoiding and paste the error

246message in.

247 

248📖 Quickstart → https://code.claude.com/docs/en/quickstart

249```

250 

251### Project memory

252 

253**`/init` and CLAUDE.md**

254 

255```markdown theme={null}

256📁 *Tip: Stop re-explaining your repo every session*

257 

258Telling Claude "we use pnpm, not npm" for the fifth time? There is a

259one-time fix.

260 

261Run `/init` once per repo. Claude reads your project structure and writes a

262CLAUDE.md file with your build commands, architecture, and conventions.

263Every future session in that repo starts from this file automatically. Keep

264it under two screens. It is a cheat sheet, not documentation.

265 

266*Try it now:* open your main repo, run `claude`, type `/init`. Thirty

267seconds, pays off every session after.

268 

269📖 CLAUDE.md and project memory → https://code.claude.com/docs/en/memory

270```

271 

272**@-references**

273 

274```markdown theme={null}

275📎 *Tip: Stop pasting file contents into the chat*

276 

277Copying 200 lines of a component into your prompt so Claude can "see" it?

278You don't have to.

279 

280Type `@` then a file path. Claude pulls the file directly into context.

281Works for whole directories too.

282 

283> the styles in @src/components/Button.tsx look off, check against

284> @docs/design-system.md

285 

286*Try it now:* type `@` then Tab. Autocomplete shows you every file in reach.

287 

288📖 Referencing files → https://code.claude.com/docs/en/common-workflows

289```

290 

291### Control and safety

292 

293**Permission modes**

294 

295```markdown theme={null}

296🛡️ *Tip: One keystroke between "look but don't touch" and "just do it"*

297 

298Sometimes you want Claude to ask before every edit. Sometimes you just want

299it to ship. You shouldn't have to pick one forever.

300 

301*Shift+Tab* cycles through how much leash Claude gets: *default* asks before

302risky stuff, *acceptEdits* lets file edits and common filesystem commands

303flow through while still checking before other shell commands, and *plan*

304proposes changes for your approval before anything is touched. Plan mode is

305the trust-builder, so start there for anything touching multiple files.

306 

307*Try it now:* on your next refactor, hit Shift+Tab until you see "plan",

308then describe the change. You'll get a full proposal before a single file

309moves.

310 

311📖 Permission modes → https://code.claude.com/docs/en/permissions

312```

313 

314**Checkpointing and `/rewind`**

315 

316```markdown theme={null}

317⏪ *Tip: There is an undo button for the whole conversation*

318 

319Claude went down the wrong path three turns ago and now you're untangling

320it? You don't have to fix forward.

321 

322`/rewind` rolls back to an earlier point in the conversation, including the

323file changes Claude made along the way. Checkpointing is automatic; you

324don't set anything up.

325 

326*Try it now:* press *Esc* twice to open the rewind menu, or type `/rewind`.

327Pick the point before things went sideways.

328 

329📖 Checkpointing → https://code.claude.com/docs/en/checkpointing

330```

331 

332### Connect your tools

333 

334**MCP connectors**

335 

336```markdown theme={null}

337🔌 *Tip: Let Claude read your issue tracker so you don't have to paste tickets*

338 

339Copy-pasting Jira tickets into the terminal feels like a step backward.

340It is.

341 

342One config file (`.mcp.json` at your project root) wires Claude into GitHub,

343Jira, Linear, or whatever tracker you use. Then "what's the top-priority

344issue assigned to me?" and "go ahead and fix it" happen in the same

345conversation.

346 

347*Try it now:* ask Claude "set up an MCP connector for [GitHub/Jira/Linear]

348in this repo". It will write the config for you.

349 

350📖 MCP connectors → https://code.claude.com/docs/en/mcp

351```

352 

353### Automate your workflows

354 

355**Skills**

356 

357```markdown theme={null}

358⚡ *Tip: Turn that prompt you keep retyping into a command*

359 

360Typed "summarize what I worked on today from git log, format it for standup"

361three times this week? That's a slash command waiting to happen.

362 

363A SKILL.md file in `.claude/skills/<name>/` becomes a reusable prompt; type

364`/name` to run it. Make one the second time you type a multi-step prompt

365you've typed before. Easiest path: ask Claude to make it for you.

366 

367*Try it now:* type "make me a /standup skill that summarizes what I worked

368on today from git log", then run `/standup` tomorrow morning.

369 

370📖 Skills → https://code.claude.com/docs/en/skills

371```

372 

373**Hooks**

374 

375```markdown theme={null}

376🔔 *Tip: Get pinged when your refactor finishes*

377 

378Sitting at your desk watching Claude work through a long task? You've got

379better things to do for those eight minutes.

380 

381Hooks are shell commands that fire on Claude Code events. A Stop hook that

382sends a desktop notification means you can kick off a long refactor, walk

383away, and get pinged the moment it's done.

384 

385*Try it now:* ask Claude "add a Stop hook that sends a desktop notification

386when you finish". It will write the script and wire it up.

387 

388📖 Hooks guide → https://code.claude.com/docs/en/hooks-guide

389```

390 

391### Day-to-day development

392 

393**Screenshots and images**

394 

395```markdown theme={null}

396📸 *Tip: Stop describing the error dialog. Just show it.*

397 

398Typing out "there's a red box that says something about a null reference

399and it's pointing at line 47-ish"? Screenshot it.

400 

401Drag a screenshot straight into the terminal and Claude sees it: error

402dialogs, UI mockups, whiteboard photos, Figma exports. *Ctrl+V* pastes from

403clipboard (use Ctrl+V on macOS too, not Cmd+V).

404 

405*Try it now:* next time something visual breaks, screenshot it and paste it

406right into the prompt. Then just type "what's wrong here?"

407 

408📖 Working with images → https://code.claude.com/docs/en/common-workflows

409```

410 

411**Git workflows**

412 

413```markdown theme={null}

414🌿 *Tip: Hand off the whole git ceremony*

415 

416The fix took 5 minutes. The commit message, branch, and PR description

417took 15. That ratio is wrong.

418 

419Claude handles the full git flow: commits with conventional messages,

420branches, PRs with proper summaries. One ask: "fix the off-by-one, commit

421with a conventional commit message, and open a PR." Reviewing someone

422else's work? Paste the PR URL and ask Claude to walk you through the diff.

423 

424*Try it now:* after your next fix, instead of switching to your git client,

425just type "commit this with a good message and open a PR".

426 

427📖 Creating pull requests → https://code.claude.com/docs/en/common-workflows

428```

429 

430### Share and scale

431 

432**Plugins**

433 

434```markdown theme={null}

435📦 *Tip: Someone probably already built that skill*

436 

437About to spend an hour building a `/deploy` command? Check if it

438already exists.

439 

440Skills get bundled and shared as plugins. `/plugin` browses what's

441available and installs in one step. Five minutes of browsing can save an

442hour of building.

443 

444*Try it now:* type `/plugin` and scroll through. You'll find at least one

445thing you didn't know you wanted.

446 

447📖 Plugins → https://code.claude.com/docs/en/plugins

448```

449 

450### Security and admin

451 

452**Security architecture**

453 

454```markdown theme={null}

455🔐 *Tip: The answer to "is this safe?" for the next time you're asked*

456 

457Someone on your team is going to ask "wait, where does my code go?"

458Here's the short version you can paste.

459 

460Permission-first by design. Every file edit, shell command, and external

461call is gated by your approval. The CLI runs in your terminal and talks

462directly to Anthropic's API, with no third-party servers, and supports

463optional OS-level sandboxing for shell commands. Under our Enterprise plan,

464Anthropic does not use your code or prompts to train its models.

465 

466*Try it now:* save these two links for the next time the question comes up.

467They answer most security-review questions.

468 

469📖 https://code.claude.com/docs/en/security

470📖 https://code.claude.com/docs/en/data-usage

471```

472 

473**Best practices**

474 

475```markdown theme={null}

476✅ *Tip: The 4 habits that separate "tried it once" from "use it daily"*

477 

478Most people who bounce off Claude Code skipped one of these. Most people

479who stick did all four in week one.

480 

481 - Start in plan mode for anything touching multiple files

482 - Run /init early; context compounds

483 - Review diffs before committing; Claude can be confidently wrong

484 - Verify changes that touch critical paths; treat it like a sharp

485 junior, not an oracle

486 

487*Try it now:* if you've only done one or two of these, pick the one you're

488missing and do it on your next task. Post what changed in #claude-code.

489 

490📖 Best practices → https://code.claude.com/docs/en/best-practices

491```

492 

493## Quick reference

494 

495### FAQ responses

496 

497One-line replies for the questions you will be asked most.

498 

499| Question | Response |

500| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

501| "Does it work in VS Code?" | Yes. There is a VS Code extension and a JetBrains plugin with the same features, embedded in your editor. [VS Code →](/en/vs-code) |

502| "Do I have to configure anything first?" | No. Install, then run `claude` in any repo. Run `/init` once and you're set. [Quickstart →](/en/quickstart) |

503| "Where does my code go?" | The CLI runs in your terminal and sends context to Anthropic's API for inference, with no third-party servers. Under your Enterprise plan, your code and prompts are not used to train models. [Data usage →](/en/data-usage) |

504| "Can it see my whole repo?" | It reads what you give it access to. File reads inside your working directory don't prompt; permission prompts gate edits, shell commands, and anything outside that directory. [Permissions →](/en/permissions) |

505| "How is this different from Copilot?" | Copilot autocompletes lines. Claude Code is an agent that reads files, runs commands, and makes multi-file edits. [Overview →](/en/overview) |

506| "What should I try first?" | A bug you've been putting off because it's tedious. "The test in \[file] is flaky, figure out why." [Quickstart →](/en/quickstart) |

507 

508### Prompt templates

509 

510Share these starter prompts with engineers who have installed but aren't sure what to ask. Each one is phrased the way it would be typed into a real session; replace the bracketed pieces with files from your own repo.

511 

512| Task | Prompt |

513| -------------------- | ---------------------------------------------------------------------------- |

514| Fix a bug | "the tests in \[file] are failing, figure out why and fix it" |

515| Understand code | "walk me through how \[module] works, then tell me where the entry point is" |

516| Safe refactor | "refactor \[module] to \[goal], use plan mode so I can review first" |

517| Write tests | "write tests for \[file] that cover the edge cases around \[scenario]" |

518| Review before commit | "look at my working diff and tell me what looks risky" |

519| Open a PR | "fix \[issue], write a conventional commit, and open a PR with a summary" |

520| Make a skill | "make me a /ship skill that runs tests and lint before commit" |

521| Debug a stack trace | "here's the stack trace, find the root cause, don't just paper over it" |

522 

523<Tip>

524 Claude Code ships frequently. Verify version-specific details against the [documentation home page](/en/overview) before distributing internally.

525</Tip>

costs.md +6 −6

Details

14 14 

15## Track your costs15## Track your costs

16 16 

17### Using the `/cost` command17### Using the `/usage` command

18 18 

19<Note>19<Note>

20 The `/cost` command shows API token usage and is intended for API users. Claude Max and Pro subscribers have usage included in their subscription, so `/cost` data isn't relevant for billing purposes. Subscribers can use `/stats` to view usage patterns.20 The Session block in `/usage` shows API token usage and is intended for API users. Claude Max and Pro subscribers have usage included in their subscription, so the session cost figure isn't relevant for billing purposes. Subscribers see plan usage bars and activity stats on the same screen.

21</Note>21</Note>

22 22 

23The `/cost` command provides detailed token usage statistics for your current session:23The `/usage` command provides detailed token usage statistics for your current session. The dollar figure is an estimate computed locally from token counts and may differ from your actual bill. For authoritative billing, see the Usage page in the [Claude Console](https://platform.claude.com/usage).

24 24 

25```text theme={null}25```text theme={null}

26Total cost: $0.5526Total cost: $0.55


82 82 

83### Manage context proactively83### Manage context proactively

84 84 

85Use `/cost` to check your current token usage, or [configure your status line](/en/statusline#context-window-usage) to display it continuously.85Use `/usage` to check your current token usage, or [configure your status line](/en/statusline#context-window-usage) to display it continuously.

86 86 

87* **Clear between tasks**: Use `/clear` to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message. Use `/rename` before clearing so you can easily find the session later, then `/resume` to return to it.87* **Clear between tasks**: Use `/clear` to start fresh when switching to unrelated work. Stale context wastes tokens on every subsequent message. Use `/rename` before clearing so you can easily find the session later, then `/resume` to return to it.

88* **Add custom compaction instructions**: `/compact Focus on code samples and API usage` tells Claude what to preserve during summarization.88* **Add custom compaction instructions**: `/compact Focus on code samples and API usage` tells Claude what to preserve during summarization.


184 184 

185For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path:185For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path:

186 186 

187* **Use plan mode for complex tasks**: Press Shift+Tab to enter [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) before implementation. Claude explores the codebase and proposes an approach for your approval, preventing expensive re-work when the initial direction is wrong.187* **Use plan mode for complex tasks**: Press Shift+Tab to enter [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) before implementation. Claude explores the codebase and proposes an approach for your approval, preventing expensive re-work when the initial direction is wrong.

188* **Course-correct early**: If Claude starts heading the wrong direction, press Escape to stop immediately. Use `/rewind` or double-tap Escape to restore conversation and code to a previous checkpoint.188* **Course-correct early**: If Claude starts heading the wrong direction, press Escape to stop immediately. Use `/rewind` or double-tap Escape to restore conversation and code to a previous checkpoint.

189* **Give verification targets**: Include test cases, paste screenshots, or define expected output in your prompt. When Claude can verify its own work, it catches issues before you need to request fixes.189* **Give verification targets**: Include test cases, paste screenshots, or define expected output in your prompt. When Claude can verify its own work, it catches issues before you need to request fixes.

190* **Test incrementally**: Write one file, test it, then continue. This catches issues early when they're cheap to fix.190* **Test incrementally**: Write one file, test it, then continue. This catches issues early when they're cheap to fix.


194Claude Code uses tokens for some background functionality even when idle:194Claude Code uses tokens for some background functionality even when idle:

195 195 

196* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature196* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature

197* **Command processing**: Some commands like `/cost` may generate requests to check status197* **Command processing**: Some commands like `/usage` may generate requests to check status

198 198 

199These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.199These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.

200 200 

data-usage.md +35 −9

Details

25 25 

26### Session quality surveys26### Session quality surveys

27 27 

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 `/feedback` 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", records only your rating. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of the rating prompt itself. Unlike thumbs up/down feedback or `/feedback` reports, this session quality survey is a simple product satisfaction metric.

29 

30After the rating prompt, you may see a separate follow-up asking "Can Anthropic look at your session transcript to help us improve Claude Code?". This is an optional second step distinct from the rating:

31 

32* **Yes**: uploads your conversation transcript, any subagent transcripts, and the raw session log file from disk to Anthropic. Known API key and token patterns are redacted before upload. Source code, file contents, and other conversation content are uploaded as-is. Shared transcripts are retained for up to 6 months.

33* **No**: declines without sending anything

34* **Don't ask again**: declines and stops this follow-up from appearing in future sessions

35 

36Nothing is uploaded unless you explicitly select **Yes**. Organizations with [zero data retention](/en/zero-data-retention), or where product feedback is disabled by organization policy, never see this follow-up. Your responses to this survey, including session transcripts submitted after the rating prompt, do not impact your data training preferences and cannot be used to train our AI models.

29 37 

30To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. To control frequency instead of disabling, set [`feedbackSurveyRate`](/en/settings#available-settings) in your settings file to a probability between `0` and `1`.38To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. To control frequency instead of disabling, set [`feedbackSurveyRate`](/en/settings#available-settings) in your settings file to a probability between `0` and `1`.

31 39 


59 67 

60The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.68The 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.

61 69 

62<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/claude-code-data-flow.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=b3f71c69d743bff63343207dfb7ad6ce" alt="Diagram showing Claude Code's external connections: install/update connects to NPM, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting" width="720" height="520" data-path="images/claude-code-data-flow.svg" />70<img src="https://mintcdn.com/claude-code/RcOyXc06Ja8cuvMZ/images/claude-code-data-flow.svg?fit=max&auto=format&n=RcOyXc06Ja8cuvMZ&q=85&s=b5be40abf333defe984993af89546c19" alt="Diagram showing Claude Code's external connections: install/update connects to the distribution server, and user requests connect to Anthropic services including Console auth, public-api, and optionally metrics, Sentry, and bug reporting" width="720" height="520" data-path="images/claude-code-data-flow.svg" />

71 

72Claude Code runs locally. To interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs, encrypted in transit via TLS 1.2+. Claude Code is compatible with most popular VPNs and LLM proxies.

73 

74Encryption at rest depends on your model provider:

63 75 

64Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.76| Provider | Encryption at rest |

77| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |

78| Anthropic API | Infrastructure-level disk encryption (AES-256). Enable [Zero Data Retention](/en/zero-data-retention) for no server-side persistence. |

79| Amazon Bedrock | AES-256 with AWS-managed keys. Customer-managed keys available via AWS KMS. |

80| Google Cloud Vertex AI | Google-managed encryption keys. CMEK available. |

81| Microsoft Foundry | Requests route to Anthropic infrastructure with AES-256 disk encryption. |

65 82 

66Claude Code is built on Anthropic's APIs. For details regarding our API's security controls, including our API logging procedures, please refer to compliance artifacts offered in the [Anthropic Trust Center](https://trust.anthropic.com).83Claude Code is built on Anthropic's APIs. For details on API security controls, including API logging procedures, see the compliance artifacts in the [Anthropic Trust Center](https://trust.anthropic.com).

67 84 

68### Cloud execution: Data flow and dependencies85### Cloud execution: Data flow and dependencies

69 86 


78 95 

79## Telemetry services96## Telemetry services

80 97 

81Claude Code connects from users' machines to the Statsig service to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Statsig security documentation](https://www.statsig.com/trust/security). To opt out of Statsig telemetry, set the `DISABLE_TELEMETRY` environment variable.98Claude Code connects from users' machines to Anthropic to log operational metrics such as latency, reliability, and usage patterns. This logging does not include any code or file paths. Data is encrypted in transit and at rest. To opt out of telemetry, set the `DISABLE_TELEMETRY` environment variable.

82 99 

83Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable.100Claude Code connects from users' machines to Sentry for operational error logging. The data is encrypted in transit using TLS and at rest using 256-bit AES encryption. Read more in the [Sentry security documentation](https://sentry.io/security/). To opt out of error logging, set the `DISABLE_ERROR_REPORTING` environment variable.

84 101 

85When users run the `/feedback` command, a copy of their full conversation history including code is sent to Anthropic. The data is encrypted in transit and at rest. Optionally, a Github issue is created in our public repository. To opt out, set the `DISABLE_FEEDBACK_COMMAND` environment variable to `1`.102When users run the `/feedback` command, a copy of their full conversation history including code is sent to Anthropic. The data is encrypted in transit via TLS. Optionally, a GitHub issue is created in the public repository. To opt out, set the `DISABLE_FEEDBACK_COMMAND` environment variable to `1`.

86 103 

87## Default behaviors by API provider104## Default behaviors by API provider

88 105 

89By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, or Foundry. Session quality surveys are the exception and appear regardless of provider. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Here are the full default behaviors:106By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, or Foundry. Session quality surveys and the WebFetch domain safety check are exceptions and run regardless of provider. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. This variable does not affect the WebFetch check, which has its own opt-out. Here are the full default behaviors:

90 107 

91| Service | Claude API | Vertex API | Bedrock API | Foundry API |108| Service | Claude API | Vertex API | Bedrock API | Foundry API |

92| ------------------------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- |109| ------------------------------------ | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |

93| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |110| **Anthropic (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. |

94| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |111| **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. |

95| **Claude API (`/feedback` reports)** | Default on.<br />`DISABLE_FEEDBACK_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. |112| **Claude API (`/feedback` reports)** | Default on.<br />`DISABLE_FEEDBACK_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

96| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. |113| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. |

114| **WebFetch domain safety check** | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. | Default on.<br />`skipWebFetchPreflight: true` in [settings](/en/settings) to disable. |

97 115 

98All environment variables can be checked into `settings.json` (see [settings reference](/en/settings)).116All environment variables can be checked into `settings.json` (see [settings reference](/en/settings)).

117 

118As of v2.1.126, when a host platform sets `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, metrics default to on for Vertex, Bedrock, and Foundry, and follow the standard `DISABLE_TELEMETRY` opt-out. Sentry error reporting and `/feedback` reports remain off by default on those providers.

119 

120### WebFetch domain safety check

121 

122Before fetching a URL, the WebFetch tool sends the requested hostname to `api.anthropic.com` to check it against a safety blocklist maintained by Anthropic. Only the hostname is sent, not the full URL, path, or page contents. Results are cached per hostname for five minutes.

123 

124This check runs regardless of which model provider you use and is not affected by `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. If your network blocks `api.anthropic.com`, WebFetch requests fail until you either allowlist the domain or set `skipWebFetchPreflight: true` in [settings](/en/settings). Disabling the check means WebFetch attempts to retrieve any URL without consulting the blocklist, so combine it with [`WebFetch` permission rules](/en/permissions#webfetch) if you need to restrict which domains Claude can reach.

debug-your-config.md +117 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Debug your configuration

6 

7> Diagnose why CLAUDE.md, settings, hooks, MCP servers, or skills aren't taking effect. Use /context, /doctor, /hooks, and /mcp to see what actually loaded.

8 

9When Claude ignores an instruction or a feature you configured doesn't appear, the cause is usually that the file didn't load, it loaded from a different location than you expected, or another file overrode it. This guide shows how to inspect what Claude Code actually loaded so you can narrow down which applies.

10 

11For installation, authentication, and connectivity problems, see [Troubleshoot installation and login](/en/troubleshoot-install) instead.

12 

13## See what loaded into context

14 

15The `/context` command shows everything occupying the context window for the current session, broken down by category: system prompt, memory files, skills, MCP tools, and conversation messages. Run it first to confirm whether your `CLAUDE.md`, rules, or skill descriptions are present at all.

16 

17For detail on a specific category, follow up with the dedicated command:

18 

19| Command | Shows |

20| :--------------- | :----------------------------------------------------------------------------------------------------------- |

21| `/memory` | Which `CLAUDE.md` and rules files loaded, plus auto-memory entries |

22| `/skills` | Available skills from project, user, and plugin sources |

23| `/agents` | Configured subagents and their settings |

24| `/hooks` | Active hook configurations |

25| `/mcp` | Connected MCP servers and their status |

26| `/permissions` | Resolved allow and deny rules currently in effect |

27| `/doctor` | Configuration diagnostics: invalid keys, schema errors, installation health |

28| `/debug [issue]` | Enables debug logging for the session and prompts Claude to diagnose using the log output and settings paths |

29| `/status` | Active settings sources, including whether managed settings are in effect |

30 

31If a memory file is missing from `/memory`, check its location against [how CLAUDE.md files load](/en/memory#how-claude-md-files-load). Subdirectory `CLAUDE.md` files load on demand when Claude reads a file in that directory with the Read tool, not at session start.

32 

33If `/memory` confirms the file loaded but Claude still isn't following a particular instruction, the issue is likely how the instruction is written rather than whether it loaded. CLAUDE.md works well for the kinds of guidance you'd give a new teammate, such as project conventions, build commands, and where files belong.

34 

35Adherence drops when an instruction is vague enough to interpret multiple ways, when two files give conflicting direction, or when the file has grown long enough that individual rules get less attention. [Write effective instructions](/en/memory#write-effective-instructions) covers the specificity, size, and structure patterns that keep adherence high.

36 

37<Note>

38 CLAUDE.md and permissions solve different problems. CLAUDE.md tells Claude how your project works so it makes good decisions. [Permissions](/en/permissions) and [hooks](/en/hooks) enforce limits regardless of what Claude decides. Use CLAUDE.md for "we do it this way here." Use permissions or hooks for security boundaries and anything that must never happen, where you need a guarantee instead of guidance.

39</Note>

40 

41## Check resolved settings

42 

43Settings merge across managed, user, project, and local scopes. Managed settings always win when present. Among the rest, the closer scope overrides the broader one in the order local, then project, then user. Some settings can also be set by command-line flags or [environment variables](/en/env-vars), which act as another override layer. When a setting doesn't seem to apply, the value you set is usually being overridden by another scope or an environment variable.

44 

45Run `/doctor` to validate your configuration files and surface invalid keys or schema errors. When `/doctor` reports issues, press `f` to send the diagnostic report to Claude and have it walk through fixes with you.

46 

47Run `/status` to see which settings sources are active, including whether managed settings are in effect. To understand which scope wins for a given key, see [How scopes interact](/en/settings#how-scopes-interact).

48 

49## Check MCP servers

50 

51Run `/mcp` to see every configured server, its connection status, and whether you have approved it for the current project. A server can be defined correctly but still not provide tools for a few common reasons:

52 

53* Project-scoped servers in `.mcp.json` require a one-time approval. If the prompt was dismissed, the server stays disabled until you approve it from `/mcp`.

54* A server that fails to start shows as failed in `/mcp`. Relative file paths in `command` or `args` are a frequent cause, since they resolve against the directory you launched Claude Code from rather than the location of `.mcp.json`.

55* A server that shows as connected but lists zero tools has started successfully but isn't returning a tool list. Select **Reconnect** from `/mcp`. If the count stays at zero, run `claude --debug mcp` to see the server's stderr output.

56 

57For configuration locations and scope rules, see [MCP](/en/mcp).

58 

59## Check hooks

60 

61Run `/hooks` to list every hook registered for the current session, grouped by event. If a hook you defined doesn't appear, it isn't being read: hooks go under the `"hooks"` key in a settings file, not in a standalone file.

62 

63If the hook appears but doesn't fire, the matcher is the usual cause. The `matcher` field is a single string that uses `|` to match multiple tool names, for example `"Edit|Write"`. A misspelled tool name fails silently because the matcher never matches. An array value is a schema error: Claude Code shows a settings error notice, `/doctor` reports the validation failure, and the hook entry is dropped so it won't appear in `/hooks`.

64 

65Edits to `settings.json` take effect in the running session after a brief file-stability delay. You don't need to restart. If `/hooks` still shows the old definition a few seconds after saving, run `/hooks` again to refresh the view.

66 

67If `/hooks` shows the hook but it still does not fire, the next step is to watch hook evaluation live. Start a session with `claude --debug hooks` and trigger the tool call. The debug log records each event, which matchers were checked, and the hook's exit code and output. See [Debug hooks](/en/hooks#debug-hooks) for the log format and [hooks troubleshooting](/en/hooks-guide#limitations-and-troubleshooting) for common failure patterns.

68 

69## Test against a clean configuration

70 

71If targeted checks don't isolate the cause, or your configuration is in an unknown state, compare against a session that loads nothing from your usual setup. Point [`CLAUDE_CONFIG_DIR`](/en/env-vars) at an empty directory to bypass everything under `~/.claude`, and launch from a directory that has no `.claude` folder, `.mcp.json`, or `CLAUDE.md` so project configuration is also skipped.

72 

73```bash theme={null}

74cd /tmp && CLAUDE_CONFIG_DIR=/tmp/claude-clean claude

75```

76 

77The clean session has no user or project settings, hooks, MCP servers, plugins, or memory.

78 

79* Managed settings still apply if your organization deploys them, since they live at a system path outside `~/.claude`

80* On Linux and Windows, you'll be prompted to log in again because credentials are stored under the configuration directory

81* On macOS, credentials are in the Keychain and carry over to the clean session

82 

83If the problem disappears here, the cause is somewhere in your real `~/.claude` or project `.claude` files. Reintroduce them one at a time, by copying files into the temporary directory or by launching from your project, to find which one. If it persists in the clean session, the cause is outside your user and project configuration. Run `/status` to check whether managed settings are in effect, look for [environment variables](/en/env-vars) that affect Claude Code, then see [Troubleshooting](/en/troubleshooting).

84 

85## Check common causes

86 

87Most configuration surprises trace back to a small set of location and syntax rules. Check these before assuming a bug:

88 

89| Symptom | Cause | Fix |

90| :------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

91| Hook never fires | `matcher` is a JSON array instead of a string | Use a single string with `\|` to match multiple tools, for example `"Edit\|Write"`. See [matcher patterns](/en/hooks#matcher-patterns). |

92| Hook never fires | `matcher` value is lowercase, for example `"bash"` | Matching is case-sensitive. Tool names are capitalized: `Bash`, `Edit`, `Write`, `Read`. |

93| Hook never fires | Hooks are in a standalone `.claude/hooks.json` file | There is no standalone hooks file. Define hooks under the `"hooks"` key in `settings.json`. See [hook configuration](/en/hooks). |

94| Permissions, hooks, or env set globally are ignored | Configuration was added to `~/.claude.json` | `~/.claude.json` holds app state and UI toggles. `permissions`, `hooks`, and `env` belong in `~/.claude/settings.json`. These are two different files. |

95| A `settings.json` value seems ignored | The same key is set in `settings.local.json` | `settings.local.json` overrides `settings.json`, and both override `~/.claude/settings.json`. See [settings precedence](/en/settings#how-scopes-interact). |

96| Skill doesn't appear in `/skills` | Skill file is at `.claude/skills/name.md` instead of in a folder | Use a folder with `SKILL.md` inside: `.claude/skills/name/SKILL.md`. |

97| Skill appears in `/skills` but Claude never invokes it | Skill has `disable-model-invocation: true` in its frontmatter, or its description doesn't match how you phrase the request | Check the badge in `/skills`: a "user-only" label means Claude won't trigger it on its own. See [skill invocation](/en/skills). |

98| Subdirectory `CLAUDE.md` instructions seem ignored | Subdirectory files load on demand, not at session start | They load when Claude reads a file in that directory with the Read tool, not at launch and not when writing or creating files there. See [how CLAUDE.md files load](/en/memory#how-claude-md-files-load). |

99| Subagent ignores `CLAUDE.md` instructions | Subagents don't always inherit project memory | Put critical rules in the agent file body, which becomes the subagent's system prompt. See [subagent configuration](/en/sub-agents). |

100| Cleanup logic never runs at session end | No `SessionEnd` hook configured | Add a `SessionEnd` hook in `settings.json`. See the [hook events list](/en/hooks#hook-events). |

101| MCP servers in `.mcp.json` never load | File is under `.claude/` or uses Claude Desktop's config format | Project MCP config goes at the repository root as `.mcp.json`, not inside `.claude/`. See [MCP configuration](/en/mcp). |

102| MCP servers added under `mcpServers` in `settings.json` never appear | `settings.json` does not read an `mcpServers` key | Define project servers in `.mcp.json` at the repository root, or run `claude mcp add --scope user` for user-scoped servers. See [MCP configuration](/en/mcp). |

103| Project MCP server added but doesn't appear | The one-time approval prompt was dismissed | Project-scoped servers require approval. Run `/mcp` to see status and approve. |

104| MCP server fails to start from some directories | `command` or `args` uses a relative file path | Use absolute paths for local scripts. Executables on your `PATH` like `npx` or `uvx` work as-is. |

105| MCP server starts without expected environment variables | Variables are in `settings.json` `env`, which doesn't propagate to MCP child processes | Set per-server `env` inside `.mcp.json` instead. |

106| `Bash(rm *)` deny rule doesn't block `/bin/rm` or `find -delete` | Prefix rules match the literal command string, not the underlying executable | Add explicit patterns for each variant, or use a [PreToolUse hook](/en/hooks-guide) or the [sandbox](/en/sandboxing) for a hard guarantee. |

107 

108## Related resources

109 

110For full reference on each configuration surface, see the dedicated page:

111 

112* **[`.claude` directory reference](/en/claude-directory)**: every config file location and what reads it

113* **[Settings](/en/settings)**: precedence order and the full key list

114* **[Hooks reference](/en/hooks)**: event names, payloads, and `--debug hooks` output format

115* **[MCP](/en/mcp)**: server configuration, approval, and `/mcp` output

116* **[Troubleshoot installation and login](/en/troubleshoot-install)**: `command not found`, PATH, and authentication problems

117* **[Troubleshooting](/en/troubleshooting)**: performance, hangs, and search issues

desktop.md +94 −44

Details

6 6 

7> Get more out of Claude Code Desktop: parallel sessions with Git isolation, drag-and-drop pane layout, integrated terminal and file editor, side chats, computer use, Dispatch sessions from your phone, visual diff review, app previews, PR monitoring, connectors, and enterprise configuration.7> Get more out of Claude Code Desktop: parallel sessions with Git isolation, drag-and-drop pane layout, integrated terminal and file editor, side chats, computer use, Dispatch sessions from your phone, visual diff review, app previews, PR monitoring, connectors, and enterprise configuration.

8 8 

9The Code tab within the Claude Desktop app lets you use Claude Code through a graphical interface instead of the terminal.9The Claude Desktop app has three tabs: **Chat** for conversations, **Cowork** for [Dispatch and longer agentic work](https://claude.com/product/cowork), and **Code** for software development. This page is the reference for the Code tab.

10 

11Desktop adds these capabilities on top of the standard Claude Code experience:

12 

13* [Parallel sessions](#work-in-parallel-with-sessions) with automatic Git worktree isolation

14* [Drag-and-drop layout](#arrange-your-workspace) with an integrated terminal, file editor, and preview pane

15* [Side chats](#ask-a-side-question-without-derailing-the-session) that branch off without affecting the main thread

16* [Visual diff review](#review-changes-with-diff-view) with inline comments

17* [Live app preview](#preview-your-app) with dev servers, HTML files, and PDFs

18* [Computer use](#let-claude-use-your-computer) to open apps and control your screen on macOS and Windows

19* [GitHub PR monitoring](#monitor-pull-request-status) with auto-fix, auto-merge, and auto-archive

20* [Dispatch](#sessions-from-dispatch) integration: send a task from your phone, get a session here

21* [Scheduled tasks](/en/desktop-scheduled-tasks) that run Claude on a recurring schedule

22* [Connectors](#connect-external-tools) for GitHub, Slack, Linear, and more

23* Local, [SSH](#ssh-sessions), and [cloud](#run-long-running-tasks-remotely) environments

24 10 

25<Tip>11<CardGroup cols={2}>

26 New to Desktop? Start with [Get started](/en/desktop-quickstart) to install the app and make your first edit.12 <Card title="Download for macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

27</Tip>13 Universal build for Intel and Apple Silicon

14 </Card>

28 15 

29<Note>16 <Card title="Download for Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">

30 The workspace layout, terminal, file editor, side chats, and view modes described on this page require Claude Desktop v1.2581.0 or later. Open **Claude → Check for Updates** on macOS or **Help → Check for Updates** on Windows to update.17 For x64 processors

31</Note>18 </Card>

19</CardGroup>

20 

21For Windows ARM64, download the [ARM64 installer](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs). The desktop app is not available on Linux; use the [CLI](/en/quickstart) instead.

22 

23After installing, launch Claude, sign in, and click the **Code** tab. The first time you open it on Windows, you need [Git for Windows](https://git-scm.com/downloads/win) installed; restart the app after installing it. For a walkthrough of your first session, see the [Get started guide](/en/desktop-quickstart).

32 24 

33This page covers [working with code](#work-with-code), [arranging your workspace](#arrange-your-workspace), [computer use](#let-claude-use-your-computer), [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).25In the Code tab, each conversation is a **session**: it has its own chat history, project folder, and code changes, independent of any other session. The sidebar lists your sessions and lets you run several in parallel. Within a session you can:

26 

27* [Review and comment on diffs](#review-changes-with-diff-view), then [watch the resulting PR through CI](#monitor-pull-request-status)

28* [Preview your running app](#preview-your-app) in an embedded browser while Claude verifies its own changes

29* [Arrange panes](#arrange-your-workspace) for the chat, diff, preview, terminal, and file editor side by side

30* Ask a [side question](#ask-a-side-question-without-derailing-the-session) that uses the session's context without derailing it

31* [Connect external tools](#connect-external-tools) like GitHub, Slack, and Linear

32* Let Claude [open apps and control your screen](#let-claude-use-your-computer)

33* Run on your machine, in the [cloud](#run-long-running-tasks-remotely), or over [SSH](#ssh-sessions)

34 

35For [scheduled recurring work](/en/desktop-scheduled-tasks), [keyboard shortcuts](#keyboard-shortcuts), or [sending tasks from your phone](#sessions-from-dispatch), see the linked pages and sections. If you already use the terminal-based CLI, see the [CLI comparison](#coming-from-the-cli) for what carries over.

34 36 

35## Start a session37## Start a session

36 38 


65Permission modes control how much autonomy Claude has during a session: whether it asks before editing files, running commands, or both. You can switch modes at any time using the mode selector next to the send button. Start with Ask permissions to see exactly what Claude does, then move to Auto accept edits or Plan mode as you get comfortable.67Permission modes control how much autonomy Claude has during a session: whether it asks before editing files, running commands, or both. You can switch modes at any time using the mode selector next to the send button. Start with Ask permissions to see exactly what Claude does, then move to Auto accept edits or Plan mode as you get comfortable.

66 68 

67| Mode | Settings key | Behavior |69| Mode | Settings key | Behavior |

68| ---------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |70| ---------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

69| **Ask permissions** | `default` | Claude asks before editing files or running commands. You see a diff and can accept or reject each change. Recommended for new users. |71| **Ask permissions** | `default` | Claude asks before editing files or running commands. You see a diff and can accept or reject each change. Recommended for new users. |

70| **Auto accept edits** | `acceptEdits` | Claude auto-accepts file edits and common filesystem commands like `mkdir`, `touch`, and `mv`, but still asks before running other terminal commands. Use this when you trust file changes and want faster iteration. |72| **Auto accept edits** | `acceptEdits` | Claude auto-accepts file edits and common filesystem commands like `mkdir`, `touch`, and `mv`, but still asks before running other terminal commands. Use this when you trust file changes and want faster iteration. |

71| **Plan mode** | `plan` | Claude reads files and runs commands to explore, then proposes a plan without editing your source code. Good for complex tasks where you want to review the approach first. |73| **Plan mode** | `plan` | Claude reads files and runs commands to explore, then proposes a plan without editing your source code. Good for complex tasks where you want to review the approach first. |

72| **Auto** | `auto` | Claude executes all actions with background safety checks that verify alignment with your request. Reduces permission prompts while maintaining oversight. Currently a research preview. Available on Team, Enterprise, and API plans. Requires Claude Sonnet 4.6 or Opus 4.6. Enable in your Settings → Claude Code. |74| **Auto** | `auto` | Claude executes all actions with background safety checks that verify alignment with your request. Reduces permission prompts while maintaining oversight. Enable in your Settings → Claude Code. See [availability requirements](#auto-mode-availability) below. |

73| **Bypass permissions** | `bypassPermissions` | Claude runs without any permission prompts, equivalent to `--dangerously-skip-permissions` in the CLI. Enable in your Settings → Claude Code under "Allow bypass permissions mode". Only use this in sandboxed containers or VMs. Enterprise admins can disable this option. |75| **Bypass permissions** | `bypassPermissions` | Claude runs without any permission prompts, equivalent to `--dangerously-skip-permissions` in the CLI. Enable in your Settings → Claude Code under "Allow bypass permissions mode". Only use this in sandboxed containers or VMs. Enterprise admins can disable this option. |

74 76 

75The `dontAsk` permission mode is available only in the [CLI](/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode).77The `dontAsk` permission mode is available only in the [CLI](/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode).

76 78 

79<span id="auto-mode-availability" />

80 

81Auto mode is a research preview available on Max, Team, Enterprise, and API plans. It is not available on Pro plans or third-party providers. On Team, Enterprise, and API plans it requires Claude Sonnet 4.6, Opus 4.6, or Opus 4.7. On Max plans it requires Claude Opus 4.7.

82 

77<Tip title="Best practice">83<Tip title="Best practice">

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

79</Tip>85</Tip>


86 92 

87Claude can start a dev server and open an embedded browser to verify its changes. This works for frontend web apps as well as backend servers: Claude can test API endpoints, view server logs, and iterate on issues it finds. In most cases, Claude starts the server automatically after editing project files. You can also ask Claude to preview at any time. By default, Claude [auto-verifies](#auto-verify-changes) changes after every edit.93Claude can start a dev server and open an embedded browser to verify its changes. This works for frontend web apps as well as backend servers: Claude can test API endpoints, view server logs, and iterate on issues it finds. In most cases, Claude starts the server automatically after editing project files. You can also ask Claude to preview at any time. By default, Claude [auto-verifies](#auto-verify-changes) changes after every edit.

88 94 

89The preview pane can also open static HTML files, PDFs, and images from your project. Click an HTML, PDF, or image path in the chat to open it in preview.95The preview pane can also open static HTML files, PDFs, images, and videos from your project. Click an HTML, PDF, image, or video path in the chat to open it in preview.

90 96 

91From the preview pane, you can:97From the preview pane, you can:

92 98 


134 140 

135## Arrange your workspace141## Arrange your workspace

136 142 

137The desktop app is built around panes you can arrange in any layout: chat, diff, preview, terminal, file, plan, tasks, and subagent. Drag a pane by its header to reposition it, or drag a pane edge to resize it. Press **Cmd+\\** on macOS or **Ctrl+\\** on Windows to close the focused pane. Open additional panes from the **Views** menu in the session toolbar.143The Code tab is built around panes you can arrange in any layout: chat, diff, preview, terminal, file, plan, tasks, and subagent. Drag a pane by its header to reposition it, or drag a pane edge to resize it. Press **Cmd+\\** on macOS or **Ctrl+\\** on Windows to close the focused pane. Open additional panes from the **Views** menu in the session toolbar.

144 

145<Note>

146 The pane layout, terminal, file editor, and view modes in this section require Claude Desktop v1.2581.0 or later. Open **Claude → Check for Updates** on macOS or **Help → Check for Updates** on Windows to update.

147</Note>

138 148 

139### Run commands in the terminal149### Run commands in the terminal

140 150 


142 152 

143### Open and edit files153### Open and edit files

144 154 

145Click a file path in the chat or diff viewer to open it in the file pane. HTML, PDF, and image paths open in the [preview pane](#preview-your-app) instead. Make spot edits and click **Save** to write them back. If the file changed on disk since you opened it, the pane warns you and lets you override or discard. Click **Discard** to revert your edits, or click the path in the pane header to copy the absolute path.155Click a file path in the chat or diff viewer to open it in the file pane. HTML, PDF, image, and video paths open in the [preview pane](#preview-your-app) instead. Make spot edits and click **Save** to write them back. If the file changed on disk since you opened it, the pane warns you and lets you override or discard. Click **Discard** to revert your edits, or click the path in the pane header to copy the absolute path.

146 156 

147The file pane is available in local and SSH sessions. For remote sessions, ask Claude to make the change.157The file pane is available in local and SSH sessions. For remote sessions, ask Claude to make the change.

148 158 


272 282 

273### Work in parallel with sessions283### Work in parallel with sessions

274 284 

275Click **+ New session** in the sidebar, or press **Cmd+N** on macOS or **Ctrl+N** on Windows, to work on multiple tasks in parallel. Press **Ctrl+Tab** and **Ctrl+Shift+Tab** to cycle through sessions in the sidebar. 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.285Click **+ New session** in the sidebar, or press **Cmd+N** on macOS or **Ctrl+N** on Windows, to work on multiple tasks in parallel. Press **Ctrl+Tab** and **Ctrl+Shift+Tab** to cycle through sessions in the sidebar. For Git repositories, each session gets its own isolated copy of your project using [Git worktrees](/en/worktrees), so changes in one session don't affect other sessions until you commit them.

286 

287To view two sessions at once, hold **Cmd** on macOS or **Ctrl** on Windows and click a session in the sidebar. The session opens in a second pane alongside the one you already have open. While the split is active, clicking another sidebar session replaces whichever pane has focus. Press **Cmd+\\** on macOS or **Ctrl+\\** on Windows to close the focused pane and return to a single session.

276 288 

277Worktrees 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. To have sessions archive themselves when their pull request merges or closes, turn on **Auto-archive after PR merge or close** in Settings → Claude Code. Auto-archive only applies to local sessions that have finished running.289Worktrees 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. To have sessions archive themselves when their pull request merges or closes, turn on **Auto-archive after PR merge or close** in Settings → Claude Code. Auto-archive only applies to local sessions that have finished running.

278 290 

279To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/en/common-workflows#copy-gitignored-files-to-worktrees) in your project root.291To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/en/worktrees#copy-gitignored-files-into-worktrees) in your project root.

280 292 

281<Note>293<Note>

282 Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check. On Windows, Git is required for the Code tab to work: [download Git for Windows](https://git-scm.com/downloads/win), install it, and restart the app. If you run into Git errors, try a Cowork session to help troubleshoot your setup.294 Session isolation requires [Git](https://git-scm.com/downloads). Most Macs include Git by default. Run `git --version` in Terminal to check. On Windows, Git is required for the Code tab to work: [download Git for Windows](https://git-scm.com/downloads/win), install it, and restart the app. If you run into Git errors, ask Claude in the [Cowork tab](https://claude.com/product/cowork) to help troubleshoot your setup.

283</Note>295</Note>

284 296 

285Use the controls at the top of the sidebar to filter sessions by status, project, or environment, and to group sessions by project. To rename a session, click the session title in the toolbar at the top of the active session. To check context usage, see [Check usage](#check-usage). When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](/en/how-claude-code-works#the-context-window) for details on how compaction works.297Use the controls at the top of the sidebar to filter sessions by status, project, or environment, and to group sessions by project. To rename a session, click the session title in the toolbar at the top of the active session. To check context usage, see [Check usage](#check-usage). When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](/en/how-claude-code-works#the-context-window) for details on how compaction works.


327 339 

328## Extend Claude Code340## Extend Claude Code

329 341 

330Connect external services, add reusable workflows, customize Claude's behavior, and configure preview servers.342Connect external services, add reusable workflows, customize Claude's behavior, and configure preview servers. To manage connectors, skills, and plugins in one place, click **Customize** in the sidebar.

331 343 

332### Connect external tools344### Connect external tools

333 345 


506 518 

507To set environment variables for local sessions and dev servers on any platform, open the environment dropdown in the prompt box, hover over **Local**, and click the gear icon to open the local environment editor. Variables you save here are stored encrypted on your machine and apply to every local session and preview server you start. You can also add variables to the `env` key in your `~/.claude/settings.json` file, though these reach Claude sessions only and not dev servers. See [environment variables](/en/env-vars) for the full list of supported variables.519To set environment variables for local sessions and dev servers on any platform, open the environment dropdown in the prompt box, hover over **Local**, and click the gear icon to open the local environment editor. Variables you save here are stored encrypted on your machine and apply to every local session and preview server you start. You can also add variables to the `env` key in your `~/.claude/settings.json` file, though these reach Claude sessions only and not dev servers. See [environment variables](/en/env-vars) for the full list of supported variables.

508 520 

509[Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS` to `0` in the local environment editor. On Opus 4.6 and Sonnet 4.6, any other `MAX_THINKING_TOKENS` value is ignored because adaptive reasoning controls thinking depth instead. To use a fixed thinking budget on these models, also set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` to `1`.521[Extended thinking](/en/model-config#extended-thinking) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS` to `0` in the local environment editor. On models with [adaptive reasoning](/en/model-config#adjust-effort-level), any other `MAX_THINKING_TOKENS` value is ignored because adaptive reasoning controls thinking depth instead. On Opus 4.6 and Sonnet 4.6, set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` to `1` to use a fixed thinking budget; Opus 4.7 always uses adaptive reasoning and has no fixed-budget mode.

510 522 

511### Remote sessions523### Remote sessions

512 524 


527 539 

528Once 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.540Once 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.

529 541 

530The remote machine must run Linux or macOS, and Claude Code must be installed on it. Once connected, SSH sessions support permission modes, connectors, plugins, and MCP servers.542The remote machine must run Linux or macOS. Desktop installs Claude Code on the remote machine automatically the first time you connect. Once connected, SSH sessions support permission modes, connectors, plugins, and MCP servers.

543 

544#### Pre-configure SSH connections for your team

545 

546Administrators can distribute SSH connections to team members by adding `sshConfigs` to a [managed settings](/en/settings#settings-precedence) file. Connections defined this way appear in each user's environment dropdown automatically and are shown as managed, so users can select them but cannot edit or delete them in the app.

547 

548The following example pre-configures a single connection that opens in `~/projects` on the remote host:

549 

550```json theme={null}

551{

552 "sshConfigs": [

553 {

554 "id": "shared-dev-vm",

555 "name": "Shared Dev VM",

556 "sshHost": "user@dev.example.com",

557 "sshPort": 22,

558 "sshIdentityFile": "~/.ssh/id_ed25519",

559 "startDirectory": "~/projects"

560 }

561 ]

562}

563```

564 

565Each entry requires `id`, `name`, and `sshHost`. The `sshPort`, `sshIdentityFile`, and `startDirectory` fields are optional. Users can also add `sshConfigs` to their own `~/.claude/settings.json`, which is where connections added through the dialog are stored.

566 

567#### Restrict which SSH hosts users can connect to

568 

569Administrators can limit Desktop's SSH sessions to an approved set of hosts by adding `sshHostAllowlist` to a [managed settings](/en/settings#settings-precedence) file. When set, users can only connect to hosts whose resolved hostname matches one of the patterns. Set it to an empty array to disable SSH sessions entirely.

570 

571The following example allows connections to any host under `devboxes.example.com` and to a single named bastion host:

572 

573```json theme={null}

574{

575 "sshHostAllowlist": ["*.devboxes.example.com", "bastion.example.com"]

576}

577```

578 

579Patterns are case-insensitive. `*` matches any host, and `*.example.com` matches `example.com` and any subdomain. Anything else is an exact match. The check runs against the hostname after `~/.ssh/config` resolution via `ssh -G`, so `Host` aliases and `ProxyCommand`/`ProxyJump` entries are permitted as long as the resolved `HostName` matches.

580 

581`sshHostAllowlist` is read from managed settings only; values in user or project settings are ignored. Only the Claude Desktop app honors this setting; the Claude Code CLI and IDE extensions do not read it, and it does not restrict `ssh` commands run through the Bash tool. It governs which hosts the Desktop app connects to, not network egress, so pair it with your organization's network or zero-trust controls if you need a hard boundary.

531 582 

532## Enterprise configuration583## Enterprise configuration

533 584 


547Managed 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.598Managed 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.

548 599 

549| Key | Description |600| Key | Description |

550| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |601| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

551| `permissions.disableBypassPermissionsMode` | set to `"disable"` to prevent users from enabling Bypass permissions mode. |602| `permissions.disableBypassPermissionsMode` | set to `"disable"` to prevent users from enabling Bypass permissions mode. |

552| `disableAutoMode` | set to `"disable"` to prevent users from enabling [Auto](/en/permission-modes#eliminate-prompts-with-auto-mode) mode. Removes Auto from the mode selector. Also accepted under `permissions`. |603| `disableAutoMode` | set to `"disable"` to prevent users from enabling [Auto](/en/permission-modes#eliminate-prompts-with-auto-mode) mode. Removes Auto from the mode selector. Also accepted under `permissions`. |

553| `autoMode` | customize what the auto mode classifier trusts and blocks across your organization. See [Configure the auto mode classifier](/en/permissions#configure-the-auto-mode-classifier). |604| `autoMode` | customize what the auto mode classifier trusts and blocks across your organization. See [Configure auto mode](/en/auto-mode-config). |

605| `sshConfigs` | pre-configure [SSH connections](#pre-configure-ssh-connections-for-your-team) that appear in the environment dropdown. Users cannot edit or delete managed connections. |

606| `sshHostAllowlist` | restrict [SSH sessions](#restrict-which-ssh-hosts-users-can-connect-to) to hosts whose resolved hostname matches one of these patterns. An empty array disables SSH sessions. Read from managed settings only. |

554 607 

555`permissions.disableBypassPermissionsMode` and `disableAutoMode` also work in user and project settings, but placing them in managed settings prevents users from overriding them. `autoMode` is read from user settings, `.claude/settings.local.json`, and managed settings, but not from the checked-in `.claude/settings.json`: a cloned repo cannot inject its own classifier rules. For the complete list of managed-only settings including `allowManagedPermissionRulesOnly` and `allowManagedHooksOnly`, see [managed-only settings](/en/permissions#managed-only-settings).608A managed settings file deployed to disk on each machine applies to Desktop sessions. Managed settings pushed remotely through the admin console currently reach CLI and IDE sessions only, so for Desktop deployments either distribute the file via MDM or use the [admin console controls](#admin-console-controls) above.

556 609 

557Remote 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.610`permissions.disableBypassPermissionsMode` and `disableAutoMode` also work in user and project settings, but placing them in managed settings prevents users from overriding them. `autoMode` is read from user settings, `.claude/settings.local.json`, and managed settings, but not from the checked-in `.claude/settings.json`: a cloned repo cannot inject its own classifier rules. For the complete list of managed-only settings including `allowManagedPermissionRulesOnly` and `allowManagedHooksOnly`, see [managed-only settings](/en/permissions#managed-only-settings).

558 611 

559### Device management policies612### Device management policies

560 613 


603| `--permission-mode` | Mode selector next to the send button |656| `--permission-mode` | Mode selector next to the send button |

604| `--dangerously-skip-permissions` | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode". Enterprise admins can disable this setting. |657| `--dangerously-skip-permissions` | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode". Enterprise admins can disable this setting. |

605| `--add-dir` | Add multiple repos with the **+** button in remote sessions |658| `--add-dir` | Add multiple repos with the **+** button in remote sessions |

606| `--allowedTools`, `--disallowedTools` | Not available in Desktop |659| `--allowedTools`, `--disallowedTools` | No per-session equivalent. Permission rules in [settings files](/en/settings) still apply. |

607| `--verbose` | [Verbose view mode](#switch-view-modes) in the Transcript view dropdown |660| `--verbose` | [Verbose view mode](#switch-view-modes) in the Transcript view dropdown |

608| `--print`, `--output-format` | Not available. Desktop is interactive only. |661| `--print`, `--output-format` | Not available. Desktop is interactive only. |

609| `ANTHROPIC_MODEL` env var | Model dropdown next to the send button |662| `ANTHROPIC_MODEL` env var | Model dropdown next to the send button |


648The following features are only available in the CLI or VS Code extension:701The following features are only available in the CLI or VS Code extension:

649 702 

650* **Third-party providers**: Desktop connects to Anthropic's API by default. Enterprise deployments can configure Vertex AI and gateway providers via [managed settings](https://support.claude.com/en/articles/12622667-enterprise-configuration). For Bedrock or Foundry, use the [CLI](/en/quickstart).703* **Third-party providers**: Desktop connects to Anthropic's API by default. Enterprise deployments can configure Vertex AI and gateway providers via [managed settings](https://support.claude.com/en/articles/12622667-enterprise-configuration). For Bedrock or Foundry, use the [CLI](/en/quickstart).

651* **Linux**: the desktop app is available on macOS and Windows only.704* **Linux**: the desktop app is available on macOS and Windows only. On Linux, use the [CLI](/en/quickstart).

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

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

654 707 

655## Troubleshooting708## Troubleshooting

656 709 

710The sections below cover issues specific to the desktop app. For runtime API errors that appear in the chat such as `API Error: 500`, `529 Overloaded`, `429`, or `Prompt is too long`, see the [Error reference](/en/errors). Those errors and their fixes are the same across the CLI, desktop, and web.

711 

657### Check your version712### Check your version

658 713 

659To see which version of the desktop app you're running:714To see which version of the desktop app you're running:


707 762 

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

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

710* **ARM64**: Windows ARM64 devices are fully supported.

711 

712### Cowork tab unavailable on Intel Macs

713 

714The Cowork tab requires Apple Silicon (M1 or later) on macOS. On Windows, Cowork is available on all supported hardware. The Chat and Code tabs work normally on Intel Macs.

715 765 

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

717 767 

Details

8 8 

9The desktop app gives you Claude Code with a graphical interface built for running multiple sessions side by side: a sidebar for managing parallel work, a drag-and-drop layout with an integrated terminal and file editor, visual diff review, live app preview, GitHub PR monitoring with auto-merge, and scheduled tasks. No terminal required.9The desktop app gives you Claude Code with a graphical interface built for running multiple sessions side by side: a sidebar for managing parallel work, a drag-and-drop layout with an integrated terminal and file editor, visual diff review, live app preview, GitHub PR monitoring with auto-merge, and scheduled tasks. No terminal required.

10 10 

11Download Claude for your platform:

12 

13<CardGroup cols={2}>11<CardGroup cols={2}>

14 <Card title="macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">12 <Card title="Download for macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

15 Universal build for Intel and Apple Silicon13 Universal build for Intel and Apple Silicon

16 </Card>14 </Card>

17 15 

18 <Card title="Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">16 <Card title="Download for Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">

19 For x64 processors17 For x64 processors

20 </Card>18 </Card>

21</CardGroup>19</CardGroup>

22 20 

23For Windows ARM64, download the [ARM64 installer](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs). Linux is not currently supported.21For Windows ARM64, download the [ARM64 installer](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs). The desktop app is not available on Linux; use the [CLI](/en/quickstart) instead.

24 22 

25<Note>23<Note>

26 Claude Code requires a [Pro, Max, Team, or Enterprise subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_pricing).24 Claude Code requires a [Pro, Max, Team, or Enterprise subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_pricing).


40 38 

41<Steps>39<Steps>

42 <Step title="Install and sign in">40 <Step title="Install and sign in">

43 Download Claude for your platform and run the installer:41 Download the installer for your platform from the links above and run it. Launch Claude from your Applications folder on macOS or the Start menu on Windows, then sign in with your Anthropic account.

44 

45 * [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs): universal build for Intel and Apple Silicon

46 * [Windows x64](https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs): for x64 processors

47 * [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs): for ARM processors

48 

49 Launch Claude from your Applications folder (macOS) or Start menu (Windows). Sign in with your Anthropic account.

50 </Step>42 </Step>

51 43 

52 <Step title="Open the Code tab">44 <Step title="Open the Code tab">


71 You can also select:63 You can also select:

72 64 

73 * **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).65 * **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).

74 * **SSH**: Connect to a remote machine over SSH (your own servers, cloud VMs, or dev containers). Claude Code must be installed on the remote machine.66 * **SSH**: Connect to a remote machine over SSH, such as your own servers, cloud VMs, or dev containers. Desktop installs Claude Code on the remote machine automatically the first time you connect.

75 </Step>67 </Step>

76 68 

77 <Step title="Choose a model">69 <Step title="Choose a model">

Details

6 6 

7> Set up scheduled tasks in Claude Code Desktop to run Claude automatically on a recurring basis for daily code reviews, dependency audits, or morning briefings.7> Set up scheduled tasks in Claude Code Desktop to run Claude automatically on a recurring basis for daily code reviews, dependency audits, or morning briefings.

8 8 

9By default, scheduled tasks start a new session automatically at a time and frequency you choose. Use them for recurring work like daily code reviews, dependency update checks, or morning briefings that pull from your calendar and inbox.9Scheduled tasks start a new session automatically at a time and frequency you choose. Use them for recurring work like daily code reviews, dependency update checks, or morning briefings that pull from your calendar and inbox.

10 

11The Desktop app's **Routines** page lets you create both local scheduled tasks and remote [routines](/en/routines). A local task runs on your machine with direct access to your files and tools, but only fires while the app is open and your computer is awake. A remote routine runs on Anthropic-managed cloud infrastructure even when your computer is off, and can also fire on API calls or GitHub events. This page covers local scheduled tasks; for remote routines and their trigger options, see [Routines](/en/routines).

10 12 

11## Compare scheduling options13## Compare scheduling options

12 14 

13Claude Code offers three ways to schedule recurring work:15Claude Code offers three ways to schedule recurring or one-off work:

14 16 

15| | [Cloud](/en/routines) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |17| | [Cloud](/en/routines) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |

16| :------------------------- | :----------------------------- | :------------------------------------- | :----------------------------- |18| :------------------------- | :----------------------------- | :------------------------------------- | :---------------------------------- |

17| Runs on | Anthropic cloud | Your machine | Your machine |19| Runs on | Anthropic cloud | Your machine | Your machine |

18| Requires machine on | No | Yes | Yes |20| Requires machine on | No | Yes | Yes |

19| Requires open session | No | No | Yes |21| Requires open session | No | No | Yes |

20| Persistent across restarts | Yes | Yes | No (session-scoped) |22| Persistent across restarts | Yes | Yes | Restored on `--resume` if unexpired |

21| Access to local files | No (fresh clone) | Yes | Yes |23| Access to local files | No (fresh clone) | Yes | Yes |

22| MCP servers | Connectors configured per task | [Config files](/en/mcp) and connectors | Inherits from session |24| MCP servers | Connectors configured per task | [Config files](/en/mcp) and connectors | Inherits from session |

23| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |25| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |


28 Use **cloud tasks** for work that should run reliably without your machine. Use **Desktop tasks** when you need access to local files and tools. Use **`/loop`** for quick polling during a session.30 Use **cloud tasks** for work that should run reliably without your machine. Use **Desktop tasks** when you need access to local files and tools. Use **`/loop`** for quick polling during a session.

29</Tip>31</Tip>

30 32 

31The Schedule page supports two kinds of tasks:

32 

33* **Local tasks**: run on your machine. They have direct access to your local files and tools, but the desktop app must be open and your computer awake for them to run.

34* **Remote tasks**: run on Anthropic-managed cloud infrastructure. They keep running even when your computer is off, but work against a fresh clone of your repository rather than your local checkout.

35 

36Both kinds appear in the same task grid. Click **New task** to pick which kind to create. The rest of this page covers local tasks; for remote tasks, see [Routines](/en/routines).

37 

38See [How scheduled tasks run](#how-scheduled-tasks-run) for details on missed runs and catch-up behavior for local tasks.

39 

40<Note>33<Note>

41 By default, local scheduled tasks run against whatever state your working directory is in, including uncommitted changes. Enable the worktree toggle in the prompt input to give each run its own isolated Git worktree, the same way [parallel sessions](/en/desktop#work-in-parallel-with-sessions) work.34 By default, scheduled tasks run against whatever state your working directory is in, including uncommitted changes. Enable the worktree toggle when creating the task to give each run its own isolated Git worktree, the same way [parallel sessions](/en/desktop#work-in-parallel-with-sessions) work.

42</Note>35</Note>

43 36 

44## Create a scheduled task37## Create a scheduled task

45 38 

46To create a local scheduled task, click **Schedule** in the sidebar, click **New task**, and choose **New local task**. Configure these fields:39Click **Routines** in the sidebar, then click **New routine** and choose **Local**. Configure these fields:

47 40 

48| Field | Description |41| Field | Description |

49| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |42| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

50| Name | Identifier for the task. Converted to lowercase kebab-case and used as the folder name on disk. Must be unique across your tasks. |43| Name | Identifier for the task. Converted to lowercase kebab-case and used as the folder name on disk. Must be unique across your tasks. |

51| Description | Short summary shown in the task list. |44| Description | Short summary shown in the task list. |

52| Prompt | The instructions sent to Claude when the task runs. Write this the same way you'd write any message in the prompt box. The prompt input also includes controls for model, permission mode, working folder, and worktree. |45| Instructions | What Claude should do when the task runs. Write this the same way you'd write any message in the prompt box. The instructions input includes pickers for the permission mode and model, and below it you select the working folder and whether to run in an isolated worktree. |

53| Frequency | How often the task runs. See [frequency options](#frequency-options) below. |46| Schedule | How often the task runs. See [schedule options](#schedule-options) below. |

47 

48A folder is required before you can save the task. If you haven't trusted that folder yet, Desktop prompts you to trust it before saving.

54 49 

55You can also create a task by describing what you want in any session. For example, "set up a daily code review that runs every morning at 9am."50You can also create a task by describing what you want in any session. For example, "set up a daily code review that runs every morning at 9am" creates a recurring task, and "remind me at 3pm tomorrow to check the deploy" creates a one-time task that disables itself after it fires.

56 51 

57## Frequency options52## Schedule options

58 53 

59Pick a preset from the frequency dropdown, or ask Claude for anything the picker doesn't cover:54Pick a preset from the Schedule control:

60 55 

61* **Manual**: no schedule, only runs when you click **Run now**. Useful for saving a prompt you trigger on demand56* **Manual**: no schedule, only runs when you click **Run now**. Useful for saving a prompt you trigger on demand

62* **Hourly**: runs every hour. Each task gets a fixed offset of up to 10 minutes from the top of the hour to stagger API traffic57* **Hourly**: runs every hour

63* **Daily**: shows a time picker, defaults to 9:00 AM local time58* **Daily**: shows a time picker, defaults to 9:00 AM local time

64* **Weekdays**: same as Daily but skips Saturday and Sunday59* **Weekdays**: same as Daily but skips Saturday and Sunday

65* **Weekly**: shows a time picker and a day picker60* **Weekly**: shows a time picker and a day picker

66 61 

67For intervals the picker doesn't offer (every 15 minutes, first of each month, etc.), ask Claude in any Desktop session to set the schedule. Use plain language; for example, "schedule a task to run all the tests every 6 hours."62For intervals the picker doesn't offer, such as every 15 minutes, the first of each month, or a single run at a specific future time, ask Claude in any Desktop session to set the schedule. Use plain language; for example, "schedule a task to run all the tests every 6 hours."

68 63 

69## How scheduled tasks run64## How scheduled tasks run

70 65 

71Local scheduled tasks run on your machine. Desktop checks the schedule every minute while the app is open and starts a fresh session when a task is due, independent of any manual sessions you have open. Each task gets a fixed delay of up to 10 minutes after the scheduled time to stagger API traffic. The delay is deterministic: the same task always starts at the same offset.66Scheduled tasks run on your machine. Desktop checks the schedule every minute while the app is open and starts a fresh session when a task is due, independent of any manual sessions you have open. Each task gets a small delay of a few minutes after the scheduled time to stagger API traffic. The delay is deterministic: the same task always starts at the same offset.

72 67 

73When a task fires, you get a desktop notification and a new session appears under a **Scheduled** section in the sidebar. Open it to see what Claude did, review changes, or respond to permission prompts. The session works like any other: Claude can edit files, run commands, create commits, and open pull requests.68When a task fires, you get a desktop notification and a new session appears under a **Scheduled** section in the sidebar. Open it to see what Claude did, review changes, or respond to permission prompts. The session works like any other: Claude can edit files, run commands, create commits, and open pull requests.

74 69 

75Tasks only run while the desktop app is running and your computer is awake. If your computer sleeps through a scheduled time, the run is skipped. To prevent idle-sleep, enable **Keep computer awake** in Settings under **Desktop app → General**. Closing the laptop lid still puts it to sleep. For tasks that need to run even when your computer is off, or that should trigger automatically on an API call or GitHub event, use a [routine](/en/routines) instead.70Tasks only run while the desktop app is running and your computer is awake. If your computer sleeps through a scheduled time, the run is skipped. To prevent idle-sleep, enable **Keep computer awake** in Settings under **Desktop app → General**. Closing the laptop lid still puts it to sleep. For tasks that need to run even when your computer is off, or that should trigger on an API call or GitHub event, create a remote [routine](/en/routines) instead.

76 71 

77## Missed runs72## Missed runs

78 73 


88 83 

89## Manage scheduled tasks84## Manage scheduled tasks

90 85 

91Click a task in the **Schedule** list to open its detail page. From here you can:86Click a task in the **Routines** list to open its detail page. From here you can:

92 87 

93* **Run now**: start the task immediately without waiting for the next scheduled time88* **Run now**: start the task immediately without waiting for the next scheduled time

94* **Toggle repeats**: pause or resume scheduled runs without deleting the task89* **Status**: toggle between Active and Paused to pause or resume scheduled runs without deleting the task

95* **Edit**: change the prompt, frequency, folder, or other settings90* **Edit**: change the instructions, schedule, folder, or other settings

96* **Review history**: see every past run, including ones that were skipped because your computer was asleep91* **Review history**: see every past run, including skipped runs. Hover a skipped entry to see why: your computer was asleep, the previous run was still in progress, or other scheduled tasks were already running. Click **Show more** to load older entries.

97* **Review allowed permissions**: see and revoke saved tool approvals for this task from the **Always allowed** panel92* **Review allowed permissions**: see and revoke saved tool approvals for this task from the **Always allowed** panel

98* **Delete**: remove the task and archive all sessions it created93* **Delete**: remove the task and archive all sessions it created

99 94 

100You can also manage tasks by asking Claude in any Desktop session. For example, "pause my dependency-audit task", "delete the standup-prep task", or "show me my scheduled tasks."95You can also list, create, edit, and pause tasks by asking Claude in any Desktop session. For example, "pause my dependency-audit task" or "show me my scheduled tasks." To delete a task, use the **Delete** button on its detail page.

101 96 

102To edit a task's prompt on disk, open `~/.claude/scheduled-tasks/<task-name>/SKILL.md` (or under [`CLAUDE_CONFIG_DIR`](/en/env-vars) if set). The file uses YAML frontmatter for `name` and `description`, with the prompt as the body. Changes take effect on the next run. Schedule, folder, model, and enabled state are not in this file: change them through the Edit form or ask Claude.97To edit a task's prompt on disk, open `~/.claude/scheduled-tasks/<task-name>/SKILL.md` (or under [`CLAUDE_CONFIG_DIR`](/en/env-vars) if set). The file uses YAML frontmatter for `name` and `description`, with the prompt as the body. Changes take effect on the next run. Schedule, folder, model, and enabled state are not in this file: change them through the Edit form or ask Claude.

103 98 

devcontainer.md +160 −49

Details

4 4 

5# Development containers5# Development containers

6 6 

7> Learn about the Claude Code development container for teams that need consistent, secure environments.7> Run Claude Code inside a dev container for consistent, isolated environments across your team.

8 8 

9The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools.9A [development container](https://containers.dev/), or dev container, lets you define an identical, isolated environment that every engineer on your team can run. With Claude Code installed in that container, commands Claude runs execute inside it rather than on the host machine, while edits to your project files appear in your local repository as you work.

10 10 

11The container's enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation.11This page covers [installing Claude Code in a dev container](#add-claude-code-to-your-dev-container) and the configuration topics that follow. Each topic is self-contained, so jump to the ones that match what you need to set up:

12 

13* [Persist authentication and settings across rebuilds](#persist-authentication-and-settings-across-rebuilds)

14* [Enforce organization policy](#enforce-organization-policy)

15* [Restrict network egress](#restrict-network-egress)

16* [Run without permission prompts](#run-without-permission-prompts)

12 17 

13<Warning>18<Warning>

14 While the devcontainer provides substantial protections, no system is completely immune to all attacks.19 While the dev container provides substantial protections, no system is completely immune to all attacks.

15 When executed with `--dangerously-skip-permissions`, devcontainers don't prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials.20 When executed with `--dangerously-skip-permissions`, dev containers do not prevent a malicious project from exfiltrating anything accessible inside the container, including the Claude Code credentials stored in [`~/.claude`](/en/claude-directory).

16 We recommend only using devcontainers when developing with trusted repositories.21 Only use dev containers when developing with trusted repositories, and monitor Claude's activities.

17 Always maintain good security practices and monitor Claude's activities.22 Avoid mounting host secrets such as `~/.ssh` or cloud credential files into the container; prefer repository-scoped or short-lived tokens.

18</Warning>23</Warning>

19 24 

20## Key features25<Accordion title="How dev containers work with your editor">

26 <img src="https://mintcdn.com/claude-code/YvJyjZfd9yMihr0i/images/devcontainer-architecture.svg?fit=max&auto=format&n=YvJyjZfd9yMihr0i&q=85&s=9017b1d16a446c6cc37ba562f35b9aae" className="dark:hidden" alt="Diagram showing an editor on the host connecting to a Docker dev container. Claude Code, the terminal, and build tools run inside the container. The host repository is bind-mounted into the container as the workspace." width="640" height="300" data-path="images/devcontainer-architecture.svg" />

27 

28 <img src="https://mintcdn.com/claude-code/YvJyjZfd9yMihr0i/images/devcontainer-architecture-dark.svg?fit=max&auto=format&n=YvJyjZfd9yMihr0i&q=85&s=ef00c8e25b1ea7a3a152895f1488831b" className="hidden dark:block" alt="Diagram showing an editor on the host connecting to a Docker dev container. Claude Code, the terminal, and build tools run inside the container. The host repository is bind-mounted into the container as the workspace." width="640" height="300" data-path="images/devcontainer-architecture-dark.svg" />

29 

30 A dev container runs as a Docker container, either on your machine or on a cloud host such as GitHub Codespaces. An editor that supports the Dev Containers spec, such as VS Code, GitHub Codespaces, a JetBrains IDE, or Cursor, connects to that container: you browse and edit files in the editor as usual, but the integrated terminal, language servers, and build tools all run inside the container rather than on your host. Editors without dev container support, such as plain Vim, are not part of this workflow.

31 

32 Claude Code runs inside the container, so it sees the same files, dependencies, and tools as the rest of your project's toolchain. In VS Code you can use either the [Claude Code extension panel](/en/vs-code) or run `claude` in the integrated terminal; both run inside the container and share the same `~/.claude` configuration.

33</Accordion>

34 

35## Add Claude Code to your dev container

36 

37Claude Code installs into any dev container through the [Claude Code Dev Container Feature](https://github.com/anthropics/devcontainer-features/tree/main/src/claude-code).

38 

39The settings work with any tool that supports the Dev Containers spec, such as VS Code, GitHub Codespaces, or JetBrains IDEs. The steps below use VS Code as an example.

40 

41When you open the container in VS Code or Codespaces, the feature also adds the Claude Code VS Code extension; other editors ignore that part.

42 

43<Tip>

44 New to dev containers? The [VS Code Dev Containers tutorial](https://code.visualstudio.com/docs/devcontainers/tutorial) walks through installing Docker, the extension, and opening your first container. For a fuller hardened example with a firewall and persistent volumes, see [Try the reference container](#try-the-reference-container).

45</Tip>

46 

47<Steps>

48 <Step title="Create or update devcontainer.json">

49 Save the following as `.devcontainer/devcontainer.json` in your repository, or add the `features` block to your existing file.

50 

51 The version tag at the end, such as `:1.0`, pins the feature's install script, not the Claude Code release. The feature installs the latest Claude Code, and Claude Code auto-updates itself inside the container by default.

52 

53 To pin the CLI version or disable auto-update, see [Enforce organization policy](#enforce-organization-policy).

54 

55 ```json .devcontainer/devcontainer.json theme={null}

56 {

57 "image": "mcr.microsoft.com/devcontainers/base:ubuntu",

58 "features": {

59 "ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {}

60 }

61 }

62 ```

63 

64 Replace the `image` line with your project's base image or remove it if your existing file uses a Dockerfile.

65 </Step>

66 

67 <Step title="Rebuild the container">

68 Open the VS Code Command Palette with `Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows and Linux, and run **Dev Containers: Rebuild Container**.

69 

70 For other tools, follow that tool's rebuild action: see [rebuilding in GitHub Codespaces](https://docs.github.com/en/codespaces/developing-in-a-codespace/rebuilding-the-container-in-a-codespace), the [Dev Containers CLI](https://github.com/devcontainers/cli), or your IDE's dev container documentation.

71 </Step>

72 

73 <Step title="Sign in to Claude Code">

74 Open a terminal in the rebuilt container and run `claude`, then follow the authentication prompt.

75 </Step>

76</Steps>

77 

78What you see at the authentication prompt depends on your provider:

79 

80* **Anthropic**: sign in through a browser with your Claude or Anthropic Console account

81* **[Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations)**: Claude Code uses your cloud provider credentials, with no browser prompt

82 

83For cloud providers, pass credentials into the container as environment variables through `containerEnv`, a Codespaces secret, or your cloud's workload identity rather than mounting credential files from the host. See [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry) for the credential chain Claude Code reads.

84 

85See [Choose your API provider](/en/admin-setup#choose-your-api-provider) to decide which path fits your organization.

86 

87<Note>

88 If the browser sign-in completes but the callback never reaches the container, copy the code shown in the browser and paste it at the `Paste code here if prompted` prompt in the terminal. This can happen when the editor's port forwarding doesn't route the localhost callback.

89</Note>

90 

91## Persist authentication and settings across rebuilds

92 

93By default, the container's home directory is discarded on rebuild, so engineers must sign in again each time. Claude Code stores its authentication token, user settings, and session history under [`~/.claude`](/en/claude-directory). Mount a named volume at that path to keep this state across rebuilds.

94 

95The following example mounts a volume at the home directory of the `node` user:

96 

97```json devcontainer.json theme={null}

98"mounts": [

99 "source=claude-code-config,target=/home/node/.claude,type=volume"

100]

101```

102 

103Replace `/home/node` with the home directory of your container's `remoteUser`. If you mount the volume somewhere other than `~/.claude`, set [`CLAUDE_CONFIG_DIR`](/en/env-vars) to the mount path so Claude Code reads and writes there.

104 

105To isolate state per project rather than sharing one volume across all repositories, include the `${devcontainerId}` variable in the source name. The [reference configuration](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json) uses `source=claude-code-config-${devcontainerId}` for this purpose.

106 

107In GitHub Codespaces, `~/.claude` persists across stopping and starting a codespace, but is still cleared when you rebuild the container, so the volume mount above applies there too. To carry authentication across codespaces, store `ANTHROPIC_API_KEY` or a `CLAUDE_CODE_OAUTH_TOKEN` from [`claude setup-token`](/en/authentication#generate-a-long-lived-token) as a [Codespaces secret](https://docs.github.com/en/codespaces/managing-your-codespaces/managing-your-account-specific-secrets-for-github-codespaces); Codespaces makes secrets available as environment variables inside the container automatically.

108 

109## Enforce organization policy

110 

111A dev container is a convenient place to apply organization policy, because the same image and configuration run on every engineer's machine.

112 

113Claude Code reads `/etc/claude-code/managed-settings.json` on Linux and applies it at the highest precedence in the [settings hierarchy](/en/settings#how-scopes-interact), so values there override anything an engineer sets in `~/.claude` or the project's `.claude/` directory. Copy the file into place from your Dockerfile:

114 

115```dockerfile Dockerfile theme={null}

116RUN mkdir -p /etc/claude-code

117COPY managed-settings.json /etc/claude-code/managed-settings.json

118```

119 

120Because the Dockerfile lives in the repository, anyone with write access can change or remove this step. For policy that engineers cannot bypass by editing repository files, deliver managed settings through [server-managed settings](/en/server-managed-settings) or your MDM instead. See [managed settings files](/en/settings#settings-files) for the available keys and the other delivery paths.

121 

122To set [environment variables](/en/env-vars) that apply to every Claude Code session in the container, add them to `containerEnv` in your `devcontainer.json`. The following example opts out of telemetry and error reporting and prevents Claude Code from auto-updating after install:

123 

124```json devcontainer.json theme={null}

125"containerEnv": {

126 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",

127 "DISABLE_AUTOUPDATER": "1"

128}

129```

21 130 

22* **Production-ready Node.js**: Built on Node.js 20 with essential development dependencies131The Dev Container Feature always installs the latest Claude Code release. To pin a specific Claude Code version for reproducible builds, install it from your Dockerfile with `npm install -g @anthropic-ai/claude-code@X.Y.Z` instead of using the feature, and set `DISABLE_AUTOUPDATER` as shown above.

23* **Security by design**: Custom firewall restricting network access to only necessary services

24* **Developer-friendly tools**: Includes git, ZSH with productivity enhancements, fzf, and more

25* **Seamless VS Code integration**: Pre-configured extensions and optimized settings

26* **Session persistence**: Preserves command history and configurations between container restarts

27* **Works everywhere**: Compatible with macOS, Windows, and Linux development environments

28 132 

29## Getting started in 4 steps133For the full list of policy controls including permission rules, tool restrictions, and MCP server allowlists, see [Set up Claude Code for your organization](/en/admin-setup).

30 134 

311. Install VS Code and the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)135To make [MCP servers](/en/mcp) available inside the container, define them at [project scope](/en/mcp#mcp-installation-scopes) in a `.mcp.json` file at the repository root so they are checked in alongside your dev container configuration. Install any binaries that local stdio servers depend on in your Dockerfile, and add remote server domains to your network allowlist.

322. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository

333. Open the repository in VS Code

344. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Dev Containers: Reopen in Container")

35 136 

36Once the container finishes building, open a terminal in VS Code with `` Ctrl+` `` and run `claude` to authenticate and start your first session. The container has Claude Code preinstalled, so you can begin working immediately. Your project files are mounted into the container, and any code Claude writes appears in your local repository.137## Restrict network egress

37 138 

38## Configuration breakdown139You can limit the container's outbound traffic to only the domains Claude Code needs. See [Network access requirements](/en/network-config#network-access-requirements) for the inference and authentication domains, and [Telemetry services](/en/data-usage#telemetry-services) for the optional telemetry and error reporting connections and how to disable them.

39 140 

40The devcontainer setup consists of three primary components:141The reference container includes an [`init-firewall.sh`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh) script that blocks all outbound traffic except the domains Claude Code and your development tools need. Running a firewall inside a container requires extra permissions, so the reference adds the `NET_ADMIN` and `NET_RAW` capabilities through `runArgs`. The firewall script and these capabilities are not required for Claude Code itself: you can leave them out and rely on your own network controls instead.

41 142 

42* [**devcontainer.json**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json): Controls container settings, extensions, and volume mounts143## Run without permission prompts

43* [**Dockerfile**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile): Defines the container image and installed tools

44* [**init-firewall.sh**](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh): Establishes network security rules

45 144 

46## Security features145Because the container runs Claude Code as a non-root user and confines command execution to the container, you can pass `--dangerously-skip-permissions` for unattended operation. The CLI rejects this flag when launched as root, so confirm `remoteUser` is set to a non-root account.

47 146 

48The container implements a multi-layered security approach with its firewall configuration:147Skipping permission prompts removes your opportunity to review tool calls before they run. Claude can still modify any file in the bind-mounted workspace, which appears directly on your host, and reach anything the container's network policy allows. Pair this flag with the [network egress restrictions](#restrict-network-egress) above to limit what a bypassed session can reach.

49 148 

50* **Precise access control**: Restricts outbound connections to whitelisted domains only (npm registry, GitHub, Claude API, etc.)149If you want fewer prompts without disabling safety checks, consider [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) instead, which has a classifier review actions before they run. To prevent engineers from using `--dangerously-skip-permissions` at all, set `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](/en/settings#permission-settings).

51* **Allowed outbound connections**: The firewall permits outbound DNS and SSH connections

52* **Default-deny policy**: Blocks all other external network access

53* **Startup verification**: Validates firewall rules when the container initializes

54* **Isolation**: Creates a secure development environment separated from your main system

55 150 

56## Customization options151## Try the reference container

57 152 

58The devcontainer configuration is designed to be adaptable to your needs:153The [`anthropics/claude-code`](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository includes an example dev container that combines the CLI, the egress firewall, persistent volumes, and a Zsh-based shell. It is provided as a working example rather than a maintained base image; use it to see how the pieces fit together before applying them to your own configuration.

59 154 

60* Add or remove VS Code extensions based on your workflow155<Steps>

61* Modify resource allocations for different hardware environments156 <Step title="Install prerequisites">

62* Adjust network access permissions157 Install VS Code and the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers).

63* Customize shell configurations and developer tooling158 </Step>

64 159 

65## Example use cases160 <Step title="Clone the reference">

161 Clone the [Claude Code repository](https://github.com/anthropics/claude-code) and open it in VS Code.

162 </Step>

66 163 

67### Secure client work164 <Step title="Reopen in container">

165 When prompted, click **Reopen in Container**, or run **Dev Containers: Reopen in Container** from the Command Palette.

166 </Step>

68 167 

69Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments.168 <Step title="Start Claude Code">

169 Once the container finishes building, open a terminal with `` Ctrl+` `` and run `claude` to sign in and start your first session.

170 </Step>

171</Steps>

70 172 

71### Team onboarding173To use this configuration with your own project, copy the `.devcontainer/` directory into your repository and adjust the Dockerfile for your toolchain, or return to [Add Claude Code to your dev container](#add-claude-code-to-your-dev-container) to add only the feature to a setup you already have.

72 174 

73New team members can get a fully configured development environment in minutes, with all necessary tools and settings pre-installed.175The reference configuration consists of three files. None of them are required when you add Claude Code to your own dev container through the feature, but they show one way to combine the pieces.

74 176 

75### Consistent CI/CD environments177| File | Purpose |

178| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |

179| [`devcontainer.json`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/devcontainer.json) | Volume mounts, `runArgs` capabilities, VS Code extensions, and `containerEnv` |

180| [`Dockerfile`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) | Base image, development tools, and the Claude Code install |

181| [`init-firewall.sh`](https://github.com/anthropics/claude-code/blob/main/.devcontainer/init-firewall.sh) | Blocks all outbound network traffic except the allowed domains |

76 182 

77Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match.183## Next steps

78 184 

79## Related resources185Once Claude Code is running in your dev container, the pages below cover the rest of an organization rollout: choosing an authentication path, delivering managed policy outside the repository, monitoring usage, and understanding what Claude Code stores and sends.

80 186 

81* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)187* [Set up Claude Code for your organization](/en/admin-setup): choose an authentication provider, decide how policy reaches devices, and plan the rollout

82* [Claude Code security best practices](/en/security)188* [Server-managed settings](/en/server-managed-settings): deliver managed policy from the Claude.ai admin console so engineers cannot bypass it by editing repository files

83* [Enterprise network configuration](/en/network-config)189* [Monitor usage and audit activity](/en/monitoring-usage): export OpenTelemetry metrics and review what your team is running

190* [Network access requirements](/en/network-config#network-access-requirements): the full domain allowlist for proxies and firewalls

191* [Telemetry services and opt-out](/en/data-usage#telemetry-services): what Claude Code sends by default and the environment variables that disable it

192* [Explore the `.claude` directory](/en/claude-directory): what the volume mount holds, including credentials, settings, and session history

193* [Security model](/en/security): how Claude Code's permission system, sandboxing, and prompt-injection protections fit together

194* [Permission modes](/en/permission-modes): the full range from plan mode to auto mode to bypass, and when to use each

Details

197 197 

198### Add from other Git hosts198### Add from other Git hosts

199 199 

200Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers:200Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers. Include the `.git` suffix so Claude Code clones the repository rather than treating the URL as a direct link to a hosted `marketplace.json` file.

201 201 

202Using HTTPS:202Using HTTPS:

203 203 


259 259 

260You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/en/settings#settings-files) and cannot be modified.260You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/en/settings#settings-files) and cannot be modified.

261 261 

262Run `/plugin` and go to the **Installed** tab to see your plugins grouped by scope.

263 

264<Warning>262<Warning>

265 Make sure you trust a plugin before installing it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they work as intended. Check each plugin's homepage for more information.263 Make sure you trust a plugin before installing it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they work as intended. Check each plugin's homepage for more information.

266</Warning>264</Warning>

267 265 

268## Manage installed plugins266## Manage installed plugins

269 267 

270Run `/plugin` and go to the **Installed** tab to view, enable, disable, or uninstall your plugins. Type to filter the list by plugin name or description.268Run `/plugin` and go to the **Installed** tab to view, enable, disable, or uninstall your plugins. The list is grouped by scope and sorted so you see problems first: plugins with load errors or unresolved dependencies appear at the top, followed by your favorites, with disabled plugins folded behind a collapsed header at the bottom.

269 

270From the list you can:

271 

272* press `f` to favorite or unfavorite the selected plugin

273* type to filter by plugin name or description

274* press Enter to open a plugin's detail view and enable, disable, or uninstall it

275 

276When you install a plugin that declares dependencies, the install output lists which dependencies were auto-installed alongside it.

271 277 

272You can also manage plugins with direct commands.278You can also manage plugins with direct commands.

273 279 


4031. **Check your version**: Run `claude --version` to see what's installed.4091. **Check your version**: Run `claude --version` to see what's installed.

4042. **Update Claude Code**:4102. **Update Claude Code**:

405 * **Homebrew**: `brew upgrade claude-code` (or `brew upgrade claude-code@latest` if you installed that cask)411 * **Homebrew**: `brew upgrade claude-code` (or `brew upgrade claude-code@latest` if you installed that cask)

406 * **npm**: `npm update -g @anthropic-ai/claude-code`412 * **npm**: `npm install -g @anthropic-ai/claude-code@latest`

407 * **Native installer**: Re-run the install command from [Setup](/en/setup)413 * **Native installer**: Re-run the install command from [Setup](/en/setup)

4083. **Restart Claude Code**: After updating, restart your terminal and run `claude` again.4143. **Restart Claude Code**: After updating, restart your terminal and run `claude` again.

409 415 

env-vars.md +53 −22

Details

15| `ANTHROPIC_BASE_URL` | Override the API endpoint to route requests through a proxy or gateway. When set to a non-first-party host, [MCP tool search](/en/mcp#scale-with-mcp-tool-search) is disabled by default. Set `ENABLE_TOOL_SEARCH=true` if your proxy forwards `tool_reference` blocks |15| `ANTHROPIC_BASE_URL` | Override the API endpoint to route requests through a proxy or gateway. When set to a non-first-party host, [MCP tool search](/en/mcp#scale-with-mcp-tool-search) is disabled by default. Set `ENABLE_TOOL_SEARCH=true` if your proxy forwards `tool_reference` blocks |

16| `ANTHROPIC_BEDROCK_BASE_URL` | Override the Bedrock endpoint URL. Use for custom Bedrock endpoints or when routing through an [LLM gateway](/en/llm-gateway). See [Amazon Bedrock](/en/amazon-bedrock) |16| `ANTHROPIC_BEDROCK_BASE_URL` | Override the Bedrock endpoint URL. Use for custom Bedrock endpoints or when routing through an [LLM gateway](/en/llm-gateway). See [Amazon Bedrock](/en/amazon-bedrock) |

17| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` | Override the Bedrock Mantle endpoint URL. See [Mantle endpoint](/en/amazon-bedrock#use-the-mantle-endpoint) |17| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` | Override the Bedrock Mantle endpoint URL. See [Mantle endpoint](/en/amazon-bedrock#use-the-mantle-endpoint) |

18| `ANTHROPIC_BEDROCK_SERVICE_TIER` | Bedrock [service tier](https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html) (`default`, `flex`, or `priority`). Sent as the `X-Amzn-Bedrock-Service-Tier` header. See [Amazon Bedrock](/en/amazon-bedrock#service-tiers) |

18| `ANTHROPIC_BETAS` | Comma-separated list of additional `anthropic-beta` header values to include in API requests. Claude Code already sends the beta headers it needs; use this to opt into an [Anthropic API beta](https://platform.claude.com/docs/en/api/beta-headers) before Claude Code adds native support. Unlike the [`--betas` flag](/en/cli-reference#cli-flags), which requires API key authentication, this variable works with all auth methods including Claude.ai subscription |19| `ANTHROPIC_BETAS` | Comma-separated list of additional `anthropic-beta` header values to include in API requests. Claude Code already sends the beta headers it needs; use this to opt into an [Anthropic API beta](https://platform.claude.com/docs/en/api/beta-headers) before Claude Code adds native support. Unlike the [`--betas` flag](/en/cli-reference#cli-flags), which requires API key authentication, this variable works with all auth methods including Claude.ai subscription |

19| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) |20| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) |

20| `ANTHROPIC_CUSTOM_MODEL_OPTION` | Model ID to add as a custom entry in the `/model` picker. Use this to make a non-standard or gateway-specific model selectable without replacing built-in aliases. See [Model configuration](/en/model-config#add-a-custom-model-option) |21| `ANTHROPIC_CUSTOM_MODEL_OPTION` | Model ID to add as a custom entry in the `/model` picker. Use this to make a non-standard or gateway-specific model selectable without replacing built-in aliases. See [Model configuration](/en/model-config#add-a-custom-model-option) |


40| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |41| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |

41| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock or Bedrock Mantle |42| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock or Bedrock Mantle |

42| `ANTHROPIC_VERTEX_BASE_URL` | Override the Vertex AI endpoint URL. Use for custom Vertex endpoints or when routing through an [LLM gateway](/en/llm-gateway). See [Google Vertex AI](/en/google-vertex-ai) |43| `ANTHROPIC_VERTEX_BASE_URL` | Override the Vertex AI endpoint URL. Use for custom Vertex endpoints or when routing through an [LLM gateway](/en/llm-gateway). See [Google Vertex AI](/en/google-vertex-ai) |

43| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI. Required when using [Google Vertex AI](/en/google-vertex-ai) |44| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI requests. Overridden by `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or the project in your `GOOGLE_APPLICATION_CREDENTIALS` credential file. See [Google Vertex AI](/en/google-vertex-ai) |

44| `API_TIMEOUT_MS` | Timeout for API requests in milliseconds (default: 600000, or 10 minutes; maximum: 2147483647). Increase this when requests time out on slow networks or when routing through a proxy. Values above the maximum overflow the underlying timer and cause requests to fail immediately |45| `API_TIMEOUT_MS` | Timeout for API requests in milliseconds (default: 600000, or 10 minutes; maximum: 2147483647). Increase this when requests time out on slow networks or when routing through a proxy. Values above the maximum overflow the underlying timer and cause requests to fail immediately |

45| `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/)) |46| `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/)) |

46| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands (default: 120000, or 2 minutes) |47| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands (default: 120000, or 2 minutes) |


50| `CLAUDECODE` | Set to `1` in shell environments Claude Code spawns (Bash tool, tmux sessions). Not set in [hooks](/en/hooks) or [status line](/en/statusline) commands. Use to detect when a script is running inside a shell spawned by Claude Code |51| `CLAUDECODE` | Set to `1` in shell environments Claude Code spawns (Bash tool, tmux sessions). Not set in [hooks](/en/hooks) or [status line](/en/statusline) commands. Use to detect when a script is running inside a shell spawned by Claude Code |

51| `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` | Set to `1` to disable all built-in [subagent](/en/sub-agents) types such as Explore and Plan. Only applies in non-interactive mode (the `-p` flag). Useful for SDK users who want a blank slate |52| `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` | Set to `1` to disable all built-in [subagent](/en/sub-agents) types such as Explore and Plan. Only applies in non-interactive mode (the `-p` flag). Useful for SDK users who want a blank slate |

52| `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` | Set to `1` to skip the `mcp__<server>__` prefix on tool names from SDK-created MCP servers. Tools use their original names. SDK usage only |53| `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` | Set to `1` to skip the `mcp__<server>__` prefix on tool names from SDK-created MCP servers. Tools use their original names. SDK usage only |

54| `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` | Stall timeout in milliseconds for background subagents. Default `600000` (10 minutes). The timer resets on each streaming progress event; if no progress arrives within the window, the subagent is aborted and the task is marked failed, surfacing any partial result to the parent |

53| `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) |55| `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) |

54| `CLAUDE_AUTO_BACKGROUND_TASKS` | Set to `1` to force-enable automatic backgrounding of long-running agent tasks. When enabled, subagents are moved to the background after running for approximately two minutes |56| `CLAUDE_AUTO_BACKGROUND_TASKS` | Set to `1` to force-enable automatic backgrounding of long-running agent tasks. When enabled, subagents are moved to the background after running for approximately two minutes |

55| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash or PowerShell command in the main session |57| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash or PowerShell command in the main session |

56| `CLAUDE_CODE_ACCESSIBILITY` | Set to `1` to keep the native terminal cursor visible and disable the inverted-text cursor indicator. Allows screen magnifiers like macOS Zoom to track cursor position |58| `CLAUDE_CODE_ACCESSIBILITY` | Set to `1` to keep the native terminal cursor visible and disable the inverted-text cursor indicator. Allows screen magnifiers like macOS Zoom to track cursor position |

57| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load memory files from directories specified with `--add-dir`. Loads `CLAUDE.md`, `.claude/CLAUDE.md`, `.claude/rules/*.md`, and `CLAUDE.local.md`. By default, additional directories do not load memory files |59| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load memory files from directories specified with `--add-dir`. Loads `CLAUDE.md`, `.claude/CLAUDE.md`, `.claude/rules/*.md`, and `CLAUDE.local.md`. By default, additional directories do not load memory files |

58| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](/en/settings#available-settings)) |60| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](/en/settings#available-settings)) |

61| `CLAUDE_CODE_ATTRIBUTION_HEADER` | Set to `0` to omit the attribution block (client version and prompt fingerprint) from the start of the system prompt. Disabling it improves prompt-cache hit rates when routing through an [LLM gateway](/en/llm-gateway). Anthropic API caching is unaffected |

59| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model's context window: 200K for standard models or 1M for [extended context](/en/model-config#extended-context) models. Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model's actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line's `used_percentage`, which always uses the model's full context window |62| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | Set the context capacity in tokens used for auto-compaction calculations. Defaults to the model's context window: 200K for standard models or 1M for [extended context](/en/model-config#extended-context) models. Use a lower value like `500000` on a 1M model to treat the window as 500K for compaction purposes. The value is capped at the model's actual context window. `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` is applied as a percentage of this value. Setting this variable decouples the compaction threshold from the status line's `used_percentage`, which always uses the model's full context window |

60| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic [IDE connection](/en/vs-code). By default, Claude Code connects automatically when launched inside a supported IDE's integrated terminal. Set to `false` to prevent this. Set to `true` to force a connection attempt when auto-detection fails, such as when tmux obscures the parent terminal |63| `CLAUDE_CODE_AUTO_CONNECT_IDE` | Override automatic [IDE connection](/en/vs-code). By default, Claude Code connects automatically when launched inside a supported IDE's integrated terminal. Set to `false` to prevent this. Set to `true` to force a connection attempt when auto-detection fails, such as when tmux obscures the parent terminal. Takes precedence over the [`autoConnectIde`](/en/settings#global-config-settings) global config setting |

61| `CLAUDE_CODE_CERT_STORE` | Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store. Default is `bundled,system`. The native binary distribution is required for system store integration. On the Node.js runtime, only the bundled set is used regardless of this value |64| `CLAUDE_CODE_CERT_STORE` | Comma-separated list of CA certificate sources for TLS connections. `bundled` is the Mozilla CA set shipped with Claude Code. `system` is the operating system trust store. Default is `bundled,system` |

62| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |65| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |

63| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |66| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |

64| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |67| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |

65| `CLAUDE_CODE_DEBUG_LOGS_DIR` | Override the debug log file path. Despite the name, this is a file path, not a directory. Requires debug mode to be enabled separately via `--debug` or `/debug`: setting this variable alone does not enable logging. The [`--debug-file`](/en/cli-reference#cli-flags) flag does both at once. Defaults to `~/.claude/debug/<session-id>.txt` |68| `CLAUDE_CODE_DEBUG_LOGS_DIR` | Override the debug log file path. Despite the name, this is a file path, not a directory. Requires debug mode to be enabled separately via `--debug` or `/debug`: setting this variable alone does not enable logging. The [`--debug-file`](/en/cli-reference#cli-flags) flag does both at once. Defaults to `~/.claude/debug/<session-id>.txt` |

66| `CLAUDE_CODE_DEBUG_LOG_LEVEL` | Minimum log level written to the debug log file. Values: `verbose`, `debug` (default), `info`, `warn`, `error`. Set to `verbose` to include high-volume diagnostics like full status line command output, or raise to `error` to reduce noise |69| `CLAUDE_CODE_DEBUG_LOG_LEVEL` | Minimum log level written to the debug log file. Values: `verbose`, `debug` (default), `info`, `warn`, `error`. Set to `verbose` to include high-volume diagnostics like full status line command output, or raise to `error` to reduce noise |

67| `CLAUDE_CODE_DISABLE_1M_CONTEXT` | Set to `1` to disable [1M context window](/en/model-config#extended-context) support. When set, 1M model variants are unavailable in the model picker. Useful for enterprise environments with compliance requirements |70| `CLAUDE_CODE_DISABLE_1M_CONTEXT` | Set to `1` to disable [1M context window](/en/model-config#extended-context) support. When set, 1M model variants are unavailable in the model picker. Useful for enterprise environments with compliance requirements |

68| `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | Set to `1` to disable [adaptive reasoning](/en/model-config#adjust-effort-level) for Opus 4.6 and Sonnet 4.6. When disabled, these models fall back to the fixed thinking budget controlled by `MAX_THINKING_TOKENS` |71| `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` | Set to `1` to disable [adaptive reasoning](/en/model-config#adjust-effort-level) on Opus 4.6 and Sonnet 4.6 and fall back to the fixed thinking budget controlled by `MAX_THINKING_TOKENS`. {/* min-version: 2.1.111 */}Has no effect on Opus 4.7, which always uses adaptive reasoning |

72| `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN` | Set to `1` to disable [fullscreen rendering](/en/fullscreen) and use the classic main-screen renderer. The conversation stays in your terminal's native scrollback so `Cmd+f` and tmux copy mode work as usual. Takes precedence over `CLAUDE_CODE_NO_FLICKER` and the [`tui`](/en/settings#available-settings) setting. You can also switch with `/tui default` |

69| `CLAUDE_CODE_DISABLE_ATTACHMENTS` | Set to `1` to disable attachment processing. File mentions with `@` syntax are sent as plain text instead of being expanded into file content |73| `CLAUDE_CODE_DISABLE_ATTACHMENTS` | Set to `1` to disable attachment processing. File mentions with `@` syntax are sent as plain text instead of being expanded into file content |

70| `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 |74| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | Set to `1` to disable [auto memory](/en/memory#auto-memory). Set to `0` to force auto memory on even when `--bare` mode or [`autoMemoryEnabled: false`](/en/settings#available-settings) would otherwise disable it. When disabled, Claude does not create or load auto memory files |

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

72| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files |76| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | Set to `1` to prevent loading any CLAUDE.md memory files into context, including user, project, and auto-memory files |

73| `CLAUDE_CODE_DISABLE_CRON` | Set to `1` to disable [scheduled tasks](/en/scheduled-tasks). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session |77| `CLAUDE_CODE_DISABLE_CRON` | Set to `1` to disable [scheduled tasks](/en/scheduled-tasks). The `/loop` skill and cron tools become unavailable and any already-scheduled tasks stop firing, including tasks that are already running mid-session |

74| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like "Unexpected value(s) for the `anthropic-beta` header" or "Extra inputs are not permitted". Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved. |78| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to strip Anthropic-specific `anthropic-beta` request headers and beta tool-schema fields (such as `defer_loading` and `eager_input_streaming`) from API requests. Use this when a proxy gateway rejects requests with errors like "Unexpected value(s) for the `anthropic-beta` header" or "Extra inputs are not permitted". Standard fields (`name`, `description`, `input_schema`, `cache_control`) are preserved. |

75| `CLAUDE_CODE_DISABLE_FAST_MODE` | Set to `1` to disable [fast mode](/en/fast-mode) |79| `CLAUDE_CODE_DISABLE_FAST_MODE` | Set to `1` to disable [fast mode](/en/fast-mode) |

76| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. See [Session quality surveys](/en/data-usage#session-quality-surveys) |80| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Surveys are also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. To set a sample rate instead of disabling outright, use the [`feedbackSurveyRate`](/en/settings#available-settings) setting. See [Session quality surveys](/en/data-usage#session-quality-surveys) |

77| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | Set to `1` to disable file [checkpointing](/en/checkpointing). The `/rewind` command will not be able to restore code changes |81| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | Set to `1` to disable file [checkpointing](/en/checkpointing). The `/rewind` command will not be able to restore code changes |

78| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | Set to `1` to remove built-in commit and PR workflow instructions and the git status snapshot from Claude's system prompt. Useful when using your own git workflow skills. Takes precedence over the [`includeGitInstructions`](/en/settings#available-settings) setting when set |82| `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` | Set to `1` to remove built-in commit and PR workflow instructions and the git status snapshot from Claude's system prompt. Useful when using your own git workflow skills. Takes precedence over the [`includeGitInstructions`](/en/settings#available-settings) setting when set |

79| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | Set to `1` to prevent automatic remapping of Opus 4.0 and 4.1 to the current Opus version on the Anthropic API. Use when you intentionally want to pin an older model. The remap does not run on Bedrock, Vertex, or Foundry |83| `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` | Set to `1` to prevent automatic remapping of Opus 4.0 and 4.1 to the current Opus version on the Anthropic API. Use when you intentionally want to pin an older model. The remap does not run on Bedrock, Vertex, or Foundry |


81| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_FEEDBACK_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |85| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_FEEDBACK_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |

82| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Set to `1` to disable the non-streaming fallback when a streaming request fails mid-stream. Streaming errors propagate to the retry layer instead. Useful when a proxy or gateway causes the fallback to produce duplicate tool execution |86| `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` | Set to `1` to disable the non-streaming fallback when a streaming request fails mid-stream. Streaming errors propagate to the retry layer instead. Useful when a proxy or gateway causes the fallback to produce duplicate tool execution |

83| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |87| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |

88| `CLAUDE_CODE_DISABLE_POLICY_SKILLS` | Set to `1` to skip loading skills from the system-wide managed skills directory. Useful for container or CI sessions that should not load operator-provisioned skills |

84| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |89| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |

85| `CLAUDE_CODE_DISABLE_THINKING` | Set to `1` to force-disable [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) regardless of model support or other settings. More direct than `MAX_THINKING_TOKENS=0` |90| `CLAUDE_CODE_DISABLE_THINKING` | Set to `1` to force-disable [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) regardless of model support or other settings. More direct than `MAX_THINKING_TOKENS=0` |

86| `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL` | Set to `1` to disable virtual scrolling in [fullscreen rendering](/en/fullscreen) and render every message in the transcript. Use this if scrolling in fullscreen mode shows blank regions where messages should appear |91| `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL` | Set to `1` to disable virtual scrolling in [fullscreen rendering](/en/fullscreen) and render every message in the transcript. Use this if scrolling in fullscreen mode shows blank regions where messages should appear |

87| `CLAUDE_CODE_EFFORT_LEVEL` | Set the effort level for supported models. Values: `low`, `medium`, `high`, `max` (Opus 4.6 only), or `auto` to use the model default. Takes precedence over `/effort` and the `effortLevel` setting. See [Adjust effort level](/en/model-config#adjust-effort-level) |92| `CLAUDE_CODE_EFFORT_LEVEL` | Set the effort level for supported models. Values: `low`, `medium`, `high`, `xhigh`, `max`, or `auto` to use the model default. Available levels depend on the model. Takes precedence over `/effort` and the `effortLevel` setting. See [Adjust effort level](/en/model-config#adjust-effort-level) |

88| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | Set to `1` to force-enable fine-grained tool input streaming. Without this, the API buffers tool input parameters fully before sending delta events, which can delay display on large tool inputs. Anthropic API only: has no effect on Bedrock, Vertex, or Foundry |93| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | Override [session recap](/en/interactive-mode#session-recap) availability. Set to `0` to force recaps off regardless of the `/config` toggle. Set to `1` to force recaps on when [`awaySummaryEnabled`](/en/settings#available-settings) is `false`. Takes precedence over the setting and `/config` toggle |

94| `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH` | Set to `1` to refresh plugin state at turn boundaries in [non-interactive mode](/en/headless) after a background install completes. Off by default because the refresh changes the system prompt mid-session, which invalidates [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for that turn |

95| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | Controls whether tool call inputs stream from the API as Claude generates them. With this off, a large tool input such as a long file write arrives only after Claude finishes generating it, which can look like it's hanging. Enabled by default on the Anthropic API. On Bedrock and Vertex, enabled per model where the deployed container supports it. Set to `0` to opt out. Set to `1` to force on when routing through a proxy via `ANTHROPIC_BASE_URL`, `ANTHROPIC_VERTEX_BASE_URL`, or `ANTHROPIC_BEDROCK_BASE_URL`. Off by default on Foundry and [gateway](/en/llm-gateway) connections |

96| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | Set to `1` to populate the `/model` picker from your gateway's `/v1/models` endpoint when `ANTHROPIC_BASE_URL` points at an Anthropic-compatible gateway such as LiteLLM, Kong, or an internal proxy. Off by default because gateways backed by a shared API key would otherwise show every user every model the key can access. Discovered models are still filtered by the [`availableModels`](/en/settings#available-settings) allowlist |

89| `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) |97| `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) |

90| `CLAUDE_CODE_ENABLE_TASKS` | Set to `1` to enable the task tracking system in non-interactive mode (the `-p` flag). Tasks are on by default in interactive mode. See [Task list](/en/interactive-mode#task-list) |98| `CLAUDE_CODE_ENABLE_TASKS` | Set to `1` to enable the task tracking system in non-interactive mode (the `-p` flag). Tasks are on by default in interactive mode. See [Task list](/en/interactive-mode#task-list) |

91| `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) |99| `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) |

92| `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 |100| `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 |

93| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Set to `1` to enable [agent teams](/en/agent-teams). Agent teams are experimental and disabled by default |101| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Set to `1` to enable [agent teams](/en/agent-teams). Agent teams are experimental and disabled by default |

102| `CLAUDE_CODE_EXTRA_BODY` | JSON object to merge into the top level of every API request body. Useful for passing provider-specific parameters that Claude Code does not expose directly |

94| `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 |103| `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 |

104| `CLAUDE_CODE_FORCE_SYNC_OUTPUT` | Set to `1` to force-enable DEC private mode 2026 [synchronized output](https://gist.github.com/christianparpart/d8a62cc1ab659194337d73e399004036) when your terminal supports it but is not auto-detected. Useful for emulators such as Emacs `eat` that implement BSU/ESU but do not reply to the capability probe. Has no effect under tmux |

105| `CLAUDE_CODE_FORK_SUBAGENT` | Set to `1` to enable [forked subagents](/en/sub-agents#fork-the-current-conversation). A forked subagent inherits the full conversation context from the main session instead of starting fresh. When enabled, `/fork` spawns a forked subagent rather than acting as an alias for [`/branch`](/en/commands), and all subagent spawns run in the background. Works in interactive mode and via the SDK or `claude -p` |

95| `CLAUDE_CODE_GIT_BASH_PATH` | Windows only: path to the Git Bash executable (`bash.exe`). Use when Git Bash is installed but not in your PATH. See [Windows setup](/en/setup#set-up-on-windows) |106| `CLAUDE_CODE_GIT_BASH_PATH` | Windows only: path to the Git Bash executable (`bash.exe`). Use when Git Bash is installed but not in your PATH. See [Windows setup](/en/setup#set-up-on-windows) |

96| `CLAUDE_CODE_GLOB_HIDDEN` | Set to `false` to exclude dotfiles from results when Claude invokes the [Glob tool](/en/tools-reference). Included by default. Does not affect `@` file autocomplete, `ls`, Grep, or Read |107| `CLAUDE_CODE_GLOB_HIDDEN` | Set to `false` to exclude dotfiles from results when Claude invokes the [Glob tool](/en/tools-reference). Included by default. Does not affect `@` file autocomplete, `ls`, Grep, or Read |

97| `CLAUDE_CODE_GLOB_NO_IGNORE` | Set to `false` to make the [Glob tool](/en/tools-reference) respect `.gitignore` patterns. By default, Glob returns all matching files including gitignored ones. Does not affect `@` file autocomplete, which has its own [`respectGitignore` setting](/en/settings#available-settings) |108| `CLAUDE_CODE_GLOB_NO_IGNORE` | Set to `false` to make the [Glob tool](/en/tools-reference) respect `.gitignore` patterns. By default, Glob returns all matching files including gitignored ones. Does not affect `@` file autocomplete, which has its own [`respectGitignore` setting](/en/settings#available-settings) |

98| `CLAUDE_CODE_GLOB_TIMEOUT_SECONDS` | Timeout in seconds for Glob tool file discovery. Defaults to 20 seconds on most platforms and 60 seconds on WSL |109| `CLAUDE_CODE_GLOB_TIMEOUT_SECONDS` | Timeout in seconds for Glob tool file discovery. Defaults to 20 seconds on most platforms and 60 seconds on WSL |

110| `CLAUDE_CODE_HIDE_CWD` | Set to `1` to hide the working directory in the startup logo. Useful for screenshares or recordings where the path exposes your OS username |

99| `CLAUDE_CODE_IDE_HOST_OVERRIDE` | Override the host address used to connect to the IDE extension. By default Claude Code auto-detects the correct address, including WSL-to-Windows routing |111| `CLAUDE_CODE_IDE_HOST_OVERRIDE` | Override the host address used to connect to the IDE extension. By default Claude Code auto-detects the correct address, including WSL-to-Windows routing |

100| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions. Equivalent to setting [`autoInstallIdeExtension`](/en/settings#global-config-settings) to `false` |112| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions. Equivalent to setting [`autoInstallIdeExtension`](/en/settings#global-config-settings) to `false` |

101| `CLAUDE_CODE_IDE_SKIP_VALID_CHECK` | Set to `1` to skip validation of IDE lockfile entries during connection. Use when auto-connect fails to find your IDE despite it running |113| `CLAUDE_CODE_IDE_SKIP_VALID_CHECK` | Set to `1` to skip validation of IDE lockfile entries during connection. Use when auto-connect fails to find your IDE despite it running |


103| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Defaults and caps vary by model; see [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison). Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers. |115| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Defaults and caps vary by model; see [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison). Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers. |

104| `CLAUDE_CODE_MAX_RETRIES` | Override the number of times to retry failed API requests (default: 10) |116| `CLAUDE_CODE_MAX_RETRIES` | Override the number of times to retry failed API requests (default: 10) |

105| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | Maximum number of read-only tools and subagents that can execute in parallel (default: 10). Higher values increase parallelism but consume more resources |117| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | Maximum number of read-only tools and subagents that can execute in parallel (default: 10). Higher values increase parallelism but consume more resources |

118| `CLAUDE_CODE_MCP_ALLOWLIST_ENV` | Set to `1` to spawn stdio MCP servers with only a safe baseline environment plus the server's configured `env`, instead of inheriting your shell environment |

119| `CLAUDE_CODE_NATIVE_CURSOR` | Set to `1` to show the terminal's own cursor at the input caret instead of a drawn block. The cursor respects the terminal's blink, shape, and focus settings |

106| `CLAUDE_CODE_NEW_INIT` | Set to `1` to make `/init` run an interactive setup flow. The flow asks which files to generate, including CLAUDE.md, skills, and hooks, before exploring the codebase and writing them. Without this variable, `/init` generates a CLAUDE.md automatically without prompting. |120| `CLAUDE_CODE_NEW_INIT` | Set to `1` to make `/init` run an interactive setup flow. The flow asks which files to generate, including CLAUDE.md, skills, and hooks, before exploring the codebase and writing them. Without this variable, `/init` generates a CLAUDE.md automatically without prompting. |

107| `CLAUDE_CODE_NO_FLICKER` | Set to `1` to enable [fullscreen rendering](/en/fullscreen), a research preview that reduces flicker and keeps memory flat in long conversations |121| `CLAUDE_CODE_NO_FLICKER` | Set to `1` to enable [fullscreen rendering](/en/fullscreen), a research preview that reduces flicker and keeps memory flat in long conversations. Equivalent to the [`tui`](/en/settings#available-settings) setting; you can also switch with `/tui fullscreen` |

108| `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` | OAuth refresh token for Claude.ai authentication. When set, `claude auth login` exchanges this token directly instead of opening a browser. Requires `CLAUDE_CODE_OAUTH_SCOPES`. Useful for provisioning authentication in automated environments |122| `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` | OAuth refresh token for Claude.ai authentication. When set, `claude auth login` exchanges this token directly instead of opening a browser. Requires `CLAUDE_CODE_OAUTH_SCOPES`. Useful for provisioning authentication in automated environments |

109| `CLAUDE_CODE_OAUTH_SCOPES` | Space-separated OAuth scopes the refresh token was issued with, such as `"user:profile user:inference user:sessions:claude_code"`. Required when `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` is set |123| `CLAUDE_CODE_OAUTH_SCOPES` | Space-separated OAuth scopes the refresh token was issued with, such as `"user:profile user:inference user:sessions:claude_code"`. Required when `CLAUDE_CODE_OAUTH_REFRESH_TOKEN` is set |

110| `CLAUDE_CODE_OAUTH_TOKEN` | OAuth access token for Claude.ai authentication. Alternative to `/login` for SDK and automated environments. Takes precedence over keychain-stored credentials. Generate one with [`claude setup-token`](/en/authentication#generate-a-long-lived-token) |124| `CLAUDE_CODE_OAUTH_TOKEN` | OAuth access token for Claude.ai authentication. Alternative to `/login` for SDK and automated environments. Takes precedence over keychain-stored credentials. Generate one with [`claude setup-token`](/en/authentication#generate-a-long-lived-token) |

111| `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS` | Timeout in milliseconds for flushing pending OpenTelemetry spans (default: 5000). See [Monitoring](/en/monitoring-usage) |125| `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS` | Timeout in milliseconds for flushing pending OpenTelemetry spans (default: 5000). See [Monitoring](/en/monitoring-usage) |

112| `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) |126| `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) |

113| `CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS` | Timeout in milliseconds for the OpenTelemetry exporter to finish on shutdown (default: 2000). Increase if metrics are dropped at exit. See [Monitoring](/en/monitoring-usage) |127| `CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS` | Timeout in milliseconds for the OpenTelemetry exporter to finish on shutdown (default: 2000). Increase if metrics are dropped at exit. See [Monitoring](/en/monitoring-usage) |

128| `CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE` | Set to `1` to let Claude Code run your package manager's upgrade command in the background when a new version is available. Applies to Homebrew and WinGet installations. Other package managers continue to show the upgrade command without running it. See [Auto updates](/en/setup#auto-updates) |

114| `CLAUDE_CODE_PERFORCE_MODE` | Set to `1` to enable Perforce-aware write protection. When set, Edit, Write, and NotebookEdit fail with a `p4 edit <file>` hint if the target file lacks the owner-write bit, which Perforce clears on synced files until `p4 edit` opens them. This prevents Claude Code from bypassing Perforce change tracking |129| `CLAUDE_CODE_PERFORCE_MODE` | Set to `1` to enable Perforce-aware write protection. When set, Edit, Write, and NotebookEdit fail with a `p4 edit <file>` hint if the target file lacks the owner-write bit, which Perforce clears on synced files until `p4 edit` opens them. This prevents Claude Code from bypassing Perforce change tracking |

115| `CLAUDE_CODE_PLUGIN_CACHE_DIR` | Override the plugins root directory. Despite the name, this sets the parent directory, not the cache itself: marketplaces and the plugin cache live in subdirectories under this path. Defaults to `~/.claude/plugins` |130| `CLAUDE_CODE_PLUGIN_CACHE_DIR` | Override the plugins root directory. Despite the name, this sets the parent directory, not the cache itself: marketplaces and the plugin cache live in subdirectories under this path. Defaults to `~/.claude/plugins` |

116| `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` | Timeout in milliseconds for git operations when installing or updating plugins (default: 120000). Increase this value for large repositories or slow network connections. See [Git operations time out](/en/plugin-marketplaces#git-operations-time-out) |131| `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` | Timeout in milliseconds for git operations when installing or updating plugins (default: 120000). Increase this value for large repositories or slow network connections. See [Git operations time out](/en/plugin-marketplaces#git-operations-time-out) |

117| `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE` | Set to `1` to keep the existing marketplace cache when a `git pull` fails instead of wiping and re-cloning. Useful in offline or airgapped environments where re-cloning would fail the same way. See [Marketplace updates fail in offline environments](/en/plugin-marketplaces#marketplace-updates-fail-in-offline-environments) |132| `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE` | Set to `1` to keep the existing marketplace cache when a `git pull` fails instead of wiping and re-cloning. Useful in offline or airgapped environments where re-cloning would fail the same way. See [Marketplace updates fail in offline environments](/en/plugin-marketplaces#marketplace-updates-fail-in-offline-environments) |

118| `CLAUDE_CODE_PLUGIN_SEED_DIR` | Path to one or more read-only plugin seed directories, separated by `:` on Unix or `;` on Windows. Use this to bundle a pre-populated plugins directory into a container image. Claude Code registers marketplaces from these directories at startup and uses pre-cached plugins without re-cloning. See [Pre-populate plugins for containers](/en/plugin-marketplaces#pre-populate-plugins-for-containers) |133| `CLAUDE_CODE_PLUGIN_SEED_DIR` | Path to one or more read-only plugin seed directories, separated by `:` on Unix or `;` on Windows. Use this to bundle a pre-populated plugins directory into a container image. Claude Code registers marketplaces from these directories at startup and uses pre-cached plugins without re-cloning. See [Pre-populate plugins for containers](/en/plugin-marketplaces#pre-populate-plugins-for-containers) |

134| `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` | Set by host platforms that embed Claude Code and manage model provider routing on its behalf. When set, provider-selection, endpoint, and authentication variables such as `CLAUDE_CODE_USE_BEDROCK`, `ANTHROPIC_BASE_URL`, and `ANTHROPIC_API_KEY` in settings files are ignored so user settings cannot override the host's routing. The automatic telemetry opt-out for Bedrock, Vertex, and Foundry is also skipped, so telemetry follows the standard `DISABLE_TELEMETRY` opt-out. See [Default behaviors by API provider](/en/data-usage#default-behaviors-by-api-provider) |

119| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `1` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |135| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `1` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |

136| `CLAUDE_CODE_REMOTE` | Set automatically to `true` when Claude Code is running as a [cloud session](/en/claude-code-on-the-web). Read this from a hook or setup script to detect whether you are in a cloud environment |

137| `CLAUDE_CODE_REMOTE_SESSION_ID` | Set automatically in [cloud sessions](/en/claude-code-on-the-web) to the current session's ID. Read this to construct a link back to the session transcript. See [Link artifacts back to the session](/en/claude-code-on-the-web#link-artifacts-back-to-the-session) |

120| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` | Set to `1` to automatically resume if the previous session ended mid-turn. Used in SDK mode so the model continues without requiring the SDK to re-send the prompt |138| `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` | Set to `1` to automatically resume if the previous session ended mid-turn. Used in SDK mode so the model continues without requiring the SDK to re-send the prompt |

121| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control |139| `CLAUDE_CODE_SCRIPT_CAPS` | JSON object limiting how many times specific scripts may be invoked per session when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is set. Keys are substrings matched against the command text; values are integer call limits. For example, `{"deploy.sh": 2}` allows `deploy.sh` to be called at most twice. Matching is substring-based so shell-expansion tricks like `./scripts/deploy.sh $(evil)` still count against the cap. Runtime fan-out via `xargs` or `find -exec` is not detected; this is a defense-in-depth control |

122| `CLAUDE_CODE_SCROLL_SPEED` | Set the mouse wheel scroll multiplier in [fullscreen rendering](/en/fullscreen#adjust-wheel-scroll-speed). Accepts values from 1 to 20. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification |140| `CLAUDE_CODE_SCROLL_SPEED` | Set the mouse wheel scroll multiplier in [fullscreen rendering](/en/fullscreen#mouse-wheel-scrolling). Accepts values from 1 to 20. Set to `3` to match `vim` if your terminal sends one wheel event per notch without amplification. Ignored in the JetBrains IDE terminal, where Claude Code uses its own scroll handling |

123| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Override the time budget in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks. Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. By default the budget is 1.5 seconds, automatically raised to the highest per-hook `timeout` configured in settings files, up to 60 seconds. Timeouts on plugin-provided hooks do not raise the budget |141| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Override the time budget in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks. Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. By default the budget is 1.5 seconds, automatically raised to the highest per-hook `timeout` configured in settings files, up to 60 seconds. Timeouts on plugin-provided hooks do not raise the budget |

142| `CLAUDE_CODE_SESSION_ID` | Set automatically in Bash and PowerShell tool subprocesses to the current session ID. Matches the `session_id` field passed to [hooks](/en/hooks). Updated on `/clear`. Use to correlate scripts and external tools with the Claude Code session that launched them |

124| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |143| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |

125| `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>` |144| `CLAUDE_CODE_SHELL_PREFIX` | Command prefix that wraps shell commands Claude Code spawns: Bash tool calls, [hook](/en/hooks) commands, and stdio [MCP server](/en/mcp) startup commands. Useful for logging or auditing. Example: setting `/path/to/logger.sh` runs each command as `/path/to/logger.sh <command>` |

126| `CLAUDE_CODE_SIMPLE` | Set to `1` to run with a minimal system prompt and only the Bash, file read, and file edit tools. MCP tools from `--mcp-config` are still available. Disables auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. The [`--bare`](/en/headless#start-faster-with-bare-mode) CLI flag sets this |145| `CLAUDE_CODE_SIMPLE` | Set to `1` to run with a minimal system prompt and only the Bash, file read, and file edit tools. MCP tools from `--mcp-config` are still available. Disables auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. The [`--bare`](/en/headless#start-faster-with-bare-mode) CLI flag sets this |

146| `CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT` | Set to `1` to use a shorter system prompt and abbreviated tool descriptions on Opus 4.7. Has no effect on other models. The full tool set, hooks, MCP servers, and CLAUDE.md discovery remain enabled |

127| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |147| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |

128| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |148| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |

129| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | Skip AWS authentication for Bedrock Mantle (for example, when using an LLM gateway) |149| `CLAUDE_CODE_SKIP_MANTLE_AUTH` | Skip AWS authentication for Bedrock Mantle (for example, when using an LLM gateway) |


133| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | Set to `1` to strip Anthropic and cloud provider credentials from subprocess environments (Bash tool, hooks, MCP stdio servers). The parent Claude process keeps these credentials for API calls, but child processes cannot read them, reducing exposure to prompt injection attacks that attempt to exfiltrate secrets via shell expansion. On Linux, this also runs Bash subprocesses in an isolated PID namespace so they cannot read host process environments via `/proc`; as a side effect, `ps`, `pgrep`, and `kill` cannot see or signal host processes. `claude-code-action` sets this automatically when `allowed_non_write_users` is configured |153| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | Set to `1` to strip Anthropic and cloud provider credentials from subprocess environments (Bash tool, hooks, MCP stdio servers). The parent Claude process keeps these credentials for API calls, but child processes cannot read them, reducing exposure to prompt injection attacks that attempt to exfiltrate secrets via shell expansion. On Linux, this also runs Bash subprocesses in an isolated PID namespace so they cannot read host process environments via `/proc`; as a side effect, `ps`, `pgrep`, and `kill` cannot see or signal host processes. `claude-code-action` sets this automatically when `allowed_non_write_users` is configured |

134| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | Set to `1` in non-interactive mode (the `-p` flag) to wait for plugin installation to complete before the first query. Without this, plugins install in the background and may not be available on the first turn. Combine with `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` to bound the wait |154| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | Set to `1` in non-interactive mode (the `-p` flag) to wait for plugin installation to complete before the first query. Without this, plugins install in the background and may not be available on the first turn. Combine with `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` to bound the wait |

135| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` | Timeout in milliseconds for synchronous plugin installation. When exceeded, Claude Code proceeds without plugins and logs an error. No default: without this variable, synchronous installation waits until complete |155| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS` | Timeout in milliseconds for synchronous plugin installation. When exceeded, Claude Code proceeds without plugins and logs an error. No default: without this variable, synchronous installation waits until complete |

136| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | Set to `false` to disable syntax highlighting in diff output. Useful when colors interfere with your terminal setup |156| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | Set to `false` to disable syntax highlighting in diff output. Useful when colors interfere with your terminal setup. To also disable highlighting in code blocks and file previews, use the [`syntaxHighlightingDisabled`](/en/settings) setting |

137| `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) |157| `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) |

138| `CLAUDE_CODE_TEAM_NAME` | Name of the agent team this teammate belongs to. Set automatically on [agent team](/en/agent-teams) members |158| `CLAUDE_CODE_TEAM_NAME` | Name of the agent team this teammate belongs to. Set automatically on [agent team](/en/agent-teams) members |

139| `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude-{uid}/` (Unix) or `/claude/` (Windows) to this path. Default: `/tmp` on macOS, `os.tmpdir()` on Linux/Windows |159| `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude-{uid}/` (Unix) or `/claude/` (Windows) to this path. Default: `/tmp` on macOS, `os.tmpdir()` on Linux/Windows |

160| `CLAUDE_CODE_TMUX_TRUECOLOR` | Set to `1` to allow 24-bit truecolor output inside tmux. By default, Claude Code clamps to 256 colors when `$TMUX` is set because tmux does not pass through truecolor escape sequences unless configured to. Set this after adding `set -ga terminal-overrides ',*:Tc'` to your `~/.tmux.conf`. See [Terminal configuration](/en/terminal-config) for other tmux settings |

140| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |161| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |

141| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) |162| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) |

142| `CLAUDE_CODE_USE_MANTLE` | Use the Bedrock [Mantle endpoint](/en/amazon-bedrock#use-the-mantle-endpoint) |163| `CLAUDE_CODE_USE_MANTLE` | Use the Bedrock [Mantle endpoint](/en/amazon-bedrock#use-the-mantle-endpoint) |

143| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | Set to `1` to enable the PowerShell tool on Windows (opt-in preview). When enabled, Claude can run PowerShell commands natively instead of routing through Git Bash. Only supported on native Windows, not WSL. See [PowerShell tool](/en/tools-reference#powershell-tool) |164| `CLAUDE_CODE_USE_NATIVE_FILE_SEARCH` | Set to `1` to discover custom commands, subagents, and output styles using Node.js file APIs instead of ripgrep. Set this if the bundled ripgrep binary is unavailable or blocked in your environment. Does not affect the Grep or file search tools |

165| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | Controls the PowerShell tool. On Windows without Git Bash, the tool is enabled automatically; set to `0` to disable it. On Windows with Git Bash installed, the tool is rolling out progressively: set to `1` to opt in or `0` to opt out. On Linux, macOS, and WSL, set to `1` to enable it, which requires `pwsh` on your `PATH`. When enabled on Windows, Claude can run PowerShell commands natively instead of routing through Git Bash. See [PowerShell tool](/en/tools-reference#powershell-tool) |

144| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |166| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |

145| `CLAUDE_CONFIG_DIR` | Override the configuration directory (default: `~/.claude`). All settings, credentials, session history, and plugins are stored under this path. Useful for running multiple accounts side by side: for example, `alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |167| `CLAUDE_CONFIG_DIR` | Override the configuration directory (default: `~/.claude`). All settings, credentials, session history, and plugins are stored under this path. Useful for running multiple accounts side by side: for example, `alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |

168| `CLAUDE_EFFORT` | Set automatically in Bash tool subprocesses and hook commands to the active [effort level](/en/model-config#adjust-effort-level) for the turn: `low`, `medium`, `high`, `xhigh`, or `max`. Matches the `effort.level` field passed to [hooks](/en/hooks). Only set when the current model supports the effort parameter |

146| `CLAUDE_ENABLE_BYTE_WATCHDOG` | Set to `1` to force-enable the byte-level streaming idle watchdog, or set to `0` to force-disable it. When unset, the watchdog is enabled by default for Anthropic API connections. The byte watchdog aborts a connection when no bytes arrive on the wire for the duration set by `CLAUDE_STREAM_IDLE_TIMEOUT_MS`, with a minimum of 5 minutes, independent of the event-level watchdog |169| `CLAUDE_ENABLE_BYTE_WATCHDOG` | Set to `1` to force-enable the byte-level streaming idle watchdog, or set to `0` to force-disable it. When unset, the watchdog is enabled by default for Anthropic API connections. The byte watchdog aborts a connection when no bytes arrive on the wire for the duration set by `CLAUDE_STREAM_IDLE_TIMEOUT_MS`, with a minimum of 5 minutes, independent of the event-level watchdog |

147| `CLAUDE_ENABLE_STREAM_WATCHDOG` | Set to `1` to enable the event-level streaming idle watchdog. Off by default. For Bedrock, Vertex, and Foundry, this is the only idle watchdog available. Configure the timeout with `CLAUDE_STREAM_IDLE_TIMEOUT_MS` |170| `CLAUDE_ENABLE_STREAM_WATCHDOG` | Set to `1` to enable the event-level streaming idle watchdog. Off by default. For Bedrock, Vertex, and Foundry, this is the only idle watchdog available. Configure the timeout with `CLAUDE_STREAM_IDLE_TIMEOUT_MS` |

148| `CLAUDE_ENV_FILE` | Path to a shell script that Claude Code sources before each Bash command. Use to persist virtualenv or conda activation across commands. Also populated dynamically by [SessionStart](/en/hooks#persist-environment-variables), [CwdChanged](/en/hooks#cwdchanged), and [FileChanged](/en/hooks#filechanged) hooks |171| `CLAUDE_ENV_FILE` | Path to a shell script whose contents Claude Code runs before each Bash command in the same shell process, so exports in the file are visible to the command. Use to persist virtualenv or conda activation across commands. Also populated dynamically by [SessionStart](/en/hooks#persist-environment-variables), [Setup](/en/hooks#setup), [CwdChanged](/en/hooks#cwdchanged), and [FileChanged](/en/hooks#filechanged) hooks |

149| `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` | Prefix for auto-generated [Remote Control](/en/remote-control) session names when no explicit name is provided. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. The `--remote-control-session-name-prefix` CLI flag sets the same value for a single invocation |172| `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` | Prefix for auto-generated [Remote Control](/en/remote-control) session names when no explicit name is provided. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. The `--remote-control-session-name-prefix` CLI flag sets the same value for a single invocation |

150| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. For the byte-level watchdog on the Anthropic API: default and minimum `300000` (5 minutes); lower values are silently clamped to absorb extended thinking pauses and proxy buffering. For the event-level watchdog: default `90000` (90 seconds), no minimum. For third-party providers, requires `CLAUDE_ENABLE_STREAM_WATCHDOG=1` |173| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. Default and minimum `300000` (5 minutes) for both the byte-level and event-level watchdogs; lower values are silently clamped to absorb extended thinking pauses and proxy buffering. For third-party providers, requires `CLAUDE_ENABLE_STREAM_WATCHDOG=1` |

151| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates |174| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic background updates. Manual `claude update` still works. Use `DISABLE_UPDATES` to block both |

152| `DISABLE_AUTO_COMPACT` | Set to `1` to disable automatic compaction when approaching the context limit. The manual `/compact` command remains available. Use when you want explicit control over when compaction occurs |175| `DISABLE_AUTO_COMPACT` | Set to `1` to disable automatic compaction when approaching the context limit. The manual `/compact` command remains available. Use when you want explicit control over when compaction occurs |

153| `DISABLE_COMPACT` | Set to `1` to disable all compaction: both automatic compaction and the manual `/compact` command |176| `DISABLE_COMPACT` | Set to `1` to disable all compaction: both automatic compaction and the manual `/compact` command |

154| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |177| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |


156| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |179| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |

157| `DISABLE_EXTRA_USAGE_COMMAND` | Set to `1` to hide the `/extra-usage` command that lets users purchase additional usage beyond rate limits |180| `DISABLE_EXTRA_USAGE_COMMAND` | Set to `1` to hide the `/extra-usage` command that lets users purchase additional usage beyond rate limits |

158| `DISABLE_FEEDBACK_COMMAND` | Set to `1` to disable the `/feedback` command. The older name `DISABLE_BUG_COMMAND` is also accepted |181| `DISABLE_FEEDBACK_COMMAND` | Set to `1` to disable the `/feedback` command. The older name `DISABLE_BUG_COMMAND` is also accepted |

182| `DISABLE_GROWTHBOOK` | Set to `1` to disable GrowthBook feature-flag fetching and use code defaults for every flag. Telemetry event logging stays on unless `DISABLE_TELEMETRY` is also set |

159| `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 |183| `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 |

160| `DISABLE_INSTALL_GITHUB_APP_COMMAND` | Set to `1` to hide the `/install-github-app` command. Already hidden when using third-party providers (Bedrock, Vertex, or Foundry) |184| `DISABLE_INSTALL_GITHUB_APP_COMMAND` | Set to `1` to hide the `/install-github-app` command. Already hidden when using third-party providers (Bedrock, Vertex, or Foundry) |

161| `DISABLE_INTERLEAVED_THINKING` | Set to `1` to prevent sending the interleaved-thinking beta header. Useful when your LLM gateway or provider does not support [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) |185| `DISABLE_INTERLEAVED_THINKING` | Set to `1` to prevent sending the interleaved-thinking beta header. Useful when your LLM gateway or provider does not support [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking) |


165| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |189| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

166| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |190| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

167| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |191| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

168| `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) |192| `DISABLE_TELEMETRY` | Set to `1` to opt out of telemetry. Telemetry events do not include user data like code, file paths, or bash commands |

193| `DISABLE_UPDATES` | Set to `1` to block all updates including manual `claude update` and `claude install`. Stricter than `DISABLE_AUTOUPDATER`. Use when distributing Claude Code through your own channels and users should not self-update |

169| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |194| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |

195| `DO_NOT_TRACK` | Set to `1` to opt out of telemetry. Equivalent to setting `DISABLE_TELEMETRY`. Honored as the [standard cross-tool convention](https://consoledonottrack.com/) |

170| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/en/mcp#use-mcp-servers-from-claude-ai) in Claude Code. Enabled by default for logged-in users |196| `ENABLE_CLAUDEAI_MCP_SERVERS` | Set to `false` to disable [claude.ai MCP servers](/en/mcp#use-mcp-servers-from-claude-ai) in Claude Code. Enabled by default for logged-in users |

171| `ENABLE_PROMPT_CACHING_1H_BEDROCK` | Set to `1` when using [Bedrock](/en/amazon-bedrock) to request a 1-hour prompt cache TTL instead of the default 5 minutes. Bedrock only |197| `ENABLE_PROMPT_CACHING_1H` | Set to `1` to request a 1-hour prompt cache TTL instead of the default 5 minutes. Intended for API key, [Bedrock](/en/amazon-bedrock), [Vertex](/en/google-vertex-ai), and [Foundry](/en/microsoft-foundry) users. Subscription users receive 1-hour TTL automatically. 1-hour cache writes are billed at a higher rate |

172| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/en/mcp#scale-with-mcp-tool-search). Unset: all MCP tools deferred by default, but loaded upfront when `ANTHROPIC_BASE_URL` points to a non-first-party host. Values: `true` (always defer including proxies), `auto` (threshold mode: load upfront if tools fit within 10% of context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `false` (load all upfront) |198| `ENABLE_PROMPT_CACHING_1H_BEDROCK` | Deprecated. Use `ENABLE_PROMPT_CACHING_1H` instead |

199| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/en/mcp#scale-with-mcp-tool-search). Unset: all MCP tools deferred by default, but loaded upfront on Vertex AI or when `ANTHROPIC_BASE_URL` points to a non-first-party host. Values: `true` (always defer including proxies and Vertex AI), `auto` (threshold mode: load upfront if tools fit within 10% of context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `false` (load all upfront) |

173| `FALLBACK_FOR_ALL_PRIMARY_MODELS` | Set to any non-empty value to trigger fallback to [`--fallback-model`](/en/cli-reference#cli-flags) after repeated overload errors on any primary model. By default, only Opus models trigger the fallback |200| `FALLBACK_FOR_ALL_PRIMARY_MODELS` | Set to any non-empty value to trigger fallback to [`--fallback-model`](/en/cli-reference#cli-flags) after repeated overload errors on any primary model. By default, only Opus models trigger the fallback |

174| `FORCE_AUTOUPDATE_PLUGINS` | Set to `1` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |201| `FORCE_AUTOUPDATE_PLUGINS` | Set to `1` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |

202| `FORCE_PROMPT_CACHING_5M` | Set to `1` to force the 5-minute prompt cache TTL even when 1-hour TTL would otherwise apply. Overrides `ENABLE_PROMPT_CACHING_1H` |

175| `HTTP_PROXY` | Specify HTTP proxy server for network connections |203| `HTTP_PROXY` | Specify HTTP proxy server for network connections |

176| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |204| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |

177| `IS_DEMO` | Set to `1` to enable demo mode: hides your email and organization name from the header and `/status` output, and skips onboarding. Useful when streaming or recording a session |205| `IS_DEMO` | Set to `1` to enable demo mode: hides your email and organization name from the header and `/status` output, and skips onboarding. Useful when streaming or recording a session |

178| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens. Tools that declare [`anthropic/maxResultSizeChars`](/en/mcp#raise-the-limit-for-a-specific-tool) use that character limit for text content instead, but image content from those tools is still subject to this variable (default: 25000) |206| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens. Tools that declare [`anthropic/maxResultSizeChars`](/en/mcp#raise-the-limit-for-a-specific-tool) use that character limit for text content instead, but image content from those tools is still subject to this variable (default: 25000) |

179| `MAX_STRUCTURED_OUTPUT_RETRIES` | Number of times to retry when the model's response fails validation against the [`--json-schema`](/en/cli-reference#cli-flags) in non-interactive mode (the `-p` flag). Defaults to 5 |207| `MAX_STRUCTURED_OUTPUT_RETRIES` | Number of times to retry when the model's response fails validation against the [`--json-schema`](/en/cli-reference#cli-flags) in non-interactive mode (the `-p` flag). Defaults to 5 |

180| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token budget. The ceiling is the model's [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison) minus one. Set to `0` to disable thinking entirely. On models with adaptive reasoning (Opus 4.6, Sonnet 4.6), the budget is ignored unless adaptive reasoning is disabled via `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` |208| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token budget. The ceiling is the model's [max output tokens](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison) minus one. Set to `0` to disable thinking entirely. On models with [adaptive reasoning](/en/model-config#adjust-effort-level), the budget is ignored unless adaptive reasoning is disabled via `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` |

181| `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` |209| `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` |

182| `MCP_CONNECTION_NONBLOCKING` | Set to `true` in non-interactive mode (`-p`) to skip the MCP connection wait entirely. Useful for scripted pipelines where MCP tools are not needed. Without this variable, the first query waits up to 5 seconds for `--mcp-config` server connections |210| `MCP_CONNECTION_NONBLOCKING` | Set to `true` in non-interactive mode (`-p`) to skip the MCP connection wait entirely. Useful for scripted pipelines where MCP tools are not needed. Without this variable, the first query waits up to 5 seconds for `--mcp-config` server connections. Servers configured with [`alwaysLoad: true`](/en/mcp#exempt-a-server-from-deferral) always block startup regardless of this variable, since their tools must be present when the first prompt is built |

211| `MCP_CONNECT_TIMEOUT_MS` | How long the first query waits, in milliseconds, for the MCP connection batch before snapshotting the tool list (default: 5000). Servers still pending at the deadline keep connecting in the background but won't appear until the next query. Distinct from `MCP_TIMEOUT`, which bounds an individual server's connect attempt. Most relevant to non-interactive sessions that issue a single query and need slow-connecting servers to be visible |

183| `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) |212| `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) |

184| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20) |213| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20) |

185| `MCP_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3) |214| `MCP_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3) |

186| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup (default: 30000, or 30 seconds) |215| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup (default: 30000, or 30 seconds) |

187| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution (default: 100000000, about 28 hours) |216| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution (default: 100000000, about 28 hours) |

188| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |217| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |

218| `OTEL_LOG_RAW_API_BODIES` | Emit Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events. Set to `1` for inline bodies truncated at 60 KB, or `file:<dir>` to write untruncated bodies to disk and emit a `body_ref` path instead. Disabled by default; bodies include the entire conversation history. See [Monitoring](/en/monitoring-usage#api-request-body-event) |

189| `OTEL_LOG_TOOL_CONTENT` | Set to `1` to include tool input and output content in OpenTelemetry span events. Disabled by default to protect sensitive data. See [Monitoring](/en/monitoring-usage) |219| `OTEL_LOG_TOOL_CONTENT` | Set to `1` to include tool input and output content in OpenTelemetry span events. Disabled by default to protect sensitive data. See [Monitoring](/en/monitoring-usage) |

190| `OTEL_LOG_TOOL_DETAILS` | Set to `1` to include tool input arguments, MCP server names, and tool details in OpenTelemetry traces and logs. Disabled by default to protect PII. See [Monitoring](/en/monitoring-usage) |220| `OTEL_LOG_TOOL_DETAILS` | Set to `1` to include tool input arguments, MCP server names, raw error strings on tool failures, and other tool details in OpenTelemetry traces and logs. Disabled by default to protect PII. See [Monitoring](/en/monitoring-usage) |

191| `OTEL_LOG_USER_PROMPTS` | Set to `1` to include user prompt text in OpenTelemetry traces and logs. Disabled by default (prompts are redacted). See [Monitoring](/en/monitoring-usage) |221| `OTEL_LOG_USER_PROMPTS` | Set to `1` to include user prompt text in OpenTelemetry traces and logs. Disabled by default (prompts are redacted). See [Monitoring](/en/monitoring-usage) |

192| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Set to `false` to exclude account UUID from metrics attributes (default: included). See [Monitoring](/en/monitoring-usage) |222| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Set to `false` to exclude account UUID from metrics attributes (default: included). See [Monitoring](/en/monitoring-usage) |

193| `OTEL_METRICS_INCLUDE_SESSION_ID` | Set to `false` to exclude session ID from metrics attributes (default: included). See [Monitoring](/en/monitoring-usage) |223| `OTEL_METRICS_INCLUDE_SESSION_ID` | Set to `false` to exclude session ID from metrics attributes (default: included). See [Monitoring](/en/monitoring-usage) |


205| `VERTEX_REGION_CLAUDE_4_5_SONNET` | Override region for Claude Sonnet 4.5 when using Vertex AI |235| `VERTEX_REGION_CLAUDE_4_5_SONNET` | Override region for Claude Sonnet 4.5 when using Vertex AI |

206| `VERTEX_REGION_CLAUDE_4_6_OPUS` | Override region for Claude Opus 4.6 when using Vertex AI |236| `VERTEX_REGION_CLAUDE_4_6_OPUS` | Override region for Claude Opus 4.6 when using Vertex AI |

207| `VERTEX_REGION_CLAUDE_4_6_SONNET` | Override region for Claude Sonnet 4.6 when using Vertex AI |237| `VERTEX_REGION_CLAUDE_4_6_SONNET` | Override region for Claude Sonnet 4.6 when using Vertex AI |

238| `VERTEX_REGION_CLAUDE_4_7_OPUS` | {/* min-version: 2.1.111 */}Override region for Claude Opus 4.7 when using Vertex AI |

208| `VERTEX_REGION_CLAUDE_HAIKU_4_5` | Override region for Claude Haiku 4.5 when using Vertex AI |239| `VERTEX_REGION_CLAUDE_HAIKU_4_5` | Override region for Claude Haiku 4.5 when using Vertex AI |

209 240 

210Standard OpenTelemetry exporter variables (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_RESOURCE_ATTRIBUTES`, and signal-specific variants) are also supported. See [Monitoring](/en/monitoring-usage) for configuration details.241Standard OpenTelemetry exporter variables (`OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_RESOURCE_ATTRIBUTES`, and signal-specific variants) are also supported. See [Monitoring](/en/monitoring-usage) for configuration details.

errors.md +574 −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# Error reference

6 

7> Look up Claude Code runtime error messages with what each one means and how to fix it.

8 

9This page lists runtime errors Claude Code displays and how to recover from each one, plus what to check when responses seem off without an error. For installation errors such as `command not found` or TLS failures during setup, see [Troubleshoot installation and login](/en/troubleshoot-install).

10 

11These errors and recovery commands apply across the CLI, the [Desktop app](/en/desktop), and [Claude Code on the web](/en/claude-code-on-the-web), since all three wrap the same Claude Code CLI. For surface-specific issues, see the troubleshooting section on that surface's page.

12 

13<Note>

14 Claude Code calls the Claude API for model responses, so most runtime errors map to an underlying API error code. This page covers what each error means inside Claude Code and how to recover. For the raw HTTP status code definitions, see the [Claude Platform error reference](https://platform.claude.com/docs/en/api/errors).

15</Note>

16 

17## Find your error

18 

19Match the message you see in your terminal to a section below.

20 

21| Message | Section |

22| :----------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------- |

23| `API Error: 500 ... Internal server error` | [Server errors](#api-error-500-internal-server-error) |

24| `API Error: Repeated 529 Overloaded errors` | [Server errors](#api-error-repeated-529-overloaded-errors) |

25| `Request timed out` | [Server errors](#request-timed-out), or [Network](#unable-to-connect-to-api) if the message mentions your internet connection |

26| `<model> is temporarily unavailable, so auto mode cannot determine the safety of...` | [Server errors](#auto-mode-cannot-determine-the-safety-of-an-action) |

27| `You've hit your session limit` / `You've hit your weekly limit` | [Usage limits](#youve-hit-your-session-limit) |

28| `Server is temporarily limiting requests` | [Usage limits](#server-is-temporarily-limiting-requests) |

29| `Request rejected (429)` | [Usage limits](#request-rejected-429) |

30| `Credit balance is too low` | [Usage limits](#credit-balance-is-too-low) |

31| `Not logged in · Please run /login` | [Authentication](#not-logged-in) |

32| `Invalid API key` | [Authentication](#invalid-api-key) |

33| `This organization has been disabled` | [Authentication](#this-organization-has-been-disabled) |

34| `Routines are disabled by your organization's policy` | [Authentication](#routines-are-disabled-by-your-organizations-policy) |

35| `OAuth token revoked` / `OAuth token has expired` | [Authentication](#oauth-token-revoked-or-expired) |

36| `does not meet scope requirement user:profile` | [Authentication](#oauth-scope-requirement) |

37| `Unable to connect to API` | [Network](#unable-to-connect-to-api) |

38| `SSL certificate verification failed` | [Network](#ssl-certificate-errors) |

39| `403` with `x-deny-reason: host_not_allowed` in a cloud or routine session | [Network](#host-not-allowed-in-a-cloud-session) |

40| `Prompt is too long` | [Request errors](#prompt-is-too-long) |

41| `Error during compaction: Conversation too long` | [Request errors](#error-during-compaction-conversation-too-long) |

42| `Request too large` | [Request errors](#request-too-large) |

43| `Image was too large` | [Request errors](#image-was-too-large) |

44| `PDF too large` / `PDF is password protected` | [Request errors](#pdf-errors) |

45| `Extra inputs are not permitted` | [Request errors](#extra-inputs-are-not-permitted) |

46| `There's an issue with the selected model` | [Request errors](#theres-an-issue-with-the-selected-model) |

47| `Claude Opus is not available with the Claude Pro plan` | [Request errors](#claude-opus-is-not-available-with-the-claude-pro-plan) |

48| `thinking.type.enabled is not supported for this model` | [Request errors](#thinking-type-enabled-is-not-supported-for-this-model) |

49| `max_tokens must be greater than thinking.budget_tokens` | [Request errors](#thinking-budget-exceeds-output-limit) |

50| `API Error: 400 due to tool use concurrency issues` | [Request errors](#tool-use-or-thinking-block-mismatch) |

51| Responses seem lower quality than usual | [Response quality](#responses-seem-lower-quality-than-usual) |

52 

53## Automatic retries

54 

55Claude Code retries transient failures before showing you an error. Server errors, overloaded responses, request timeouts, temporary 429 throttles, and dropped connections are all retried up to 10 times with exponential backoff. While retrying, the spinner shows a `Retrying in Ns · attempt x/y` countdown.

56 

57When you see one of the errors on this page, those retries have already been exhausted. You can tune the behavior with two environment variables:

58 

59| Variable | Default | Effect |

60| :---------------------------------------- | :------ | :------------------------------------------------------------------------------------------------------------------- |

61| [`CLAUDE_CODE_MAX_RETRIES`](/en/env-vars) | 10 | Number of retry attempts. Lower it to surface failures faster in scripts; raise it to wait through longer incidents. |

62| [`API_TIMEOUT_MS`](/en/env-vars) | 600000 | Per-request timeout in milliseconds. Raise it for slow networks or proxies. |

63 

64## Server errors

65 

66These errors come from Anthropic infrastructure rather than your account or request.

67 

68### API Error: 500 Internal server error

69 

70Claude Code shows the raw API response body for any 5xx status. The example below shows a 500 response:

71 

72```text theme={null}

73API Error: 500 {"type":"error","error":{"type":"api_error","message":"Internal server error"}} · check status.claude.com

74```

75 

76This indicates an unexpected failure inside the API. It is not caused by your prompt, settings, or account.

77 

78**What to do:**

79 

80* Check [status.claude.com](https://status.claude.com) for active incidents

81* Wait a minute, then send your message again. Your original message is still in the conversation, so for a long prompt you can type `try again` instead of pasting the whole thing.

82* If the error persists with no posted incident, run `/feedback` so Anthropic can investigate with your request details. See [Report an error](#report-an-error) if `/feedback` is unavailable on your provider.

83 

84### API Error: Repeated 529 Overloaded errors

85 

86The API is temporarily at capacity across all users. Claude Code has already retried several times before showing this message:

87 

88```text theme={null}

89API Error: Repeated 529 Overloaded errors · check status.claude.com

90```

91 

92A 529 is not your usage limit and does not count against your quota.

93 

94**What to do:**

95 

96* Check [status.claude.com](https://status.claude.com) for capacity notices

97* Try again in a few minutes

98* Run `/model` and switch to a different model to keep working, since capacity is tracked per model. Claude Code prompts you to do this when one model is under particularly high load, for example `Opus is experiencing high load, please use /model to switch to Sonnet`.

99 

100### Request timed out

101 

102The API did not respond before the connection deadline.

103 

104```text theme={null}

105Request timed out

106```

107 

108This can happen during periods of high load or when a very large response is being generated. The default request timeout is 10 minutes.

109 

110**What to do:**

111 

112* Retry the request

113* For long-running tasks, break the work into smaller prompts

114* If a slow network or proxy is the cause, raise `API_TIMEOUT_MS` as described in [Automatic retries](#automatic-retries)

115* If timeouts are frequent and your network is otherwise healthy, see [Network and connection errors](#network-and-connection-errors) below

116 

117### Auto mode cannot determine the safety of an action

118 

119The model that [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) uses to classify actions is overloaded, so auto mode blocked the action instead of approving it unchecked.

120 

121```text theme={null}

122<model> is temporarily unavailable, so auto mode cannot determine the safety of <tool> right now. Wait briefly and then try this action again.

123```

124 

125Reads, searches, and edits inside your working directory skip the classifier, so they keep working during the outage.

126 

127**What to do:**

128 

129* Retry after a few seconds; Claude sees the same message and usually retries on its own

130* If retries keep failing, continue with read-only tasks and come back to the blocked action later

131* This is transient and unrelated to [auto mode eligibility](/en/permission-modes#eliminate-prompts-with-auto-mode); you do not need to change settings

132 

133## Usage limits

134 

135These errors mean a quota tied to your account or plan has been reached. They are distinct from [server errors](#server-errors), which affect everyone.

136 

137### You've hit your session limit

138 

139Subscription plans include a rolling usage allowance. When it runs out you see one of these messages:

140 

141```text theme={null}

142You've hit your session limit · resets 3:45pm

143You've hit your weekly limit · resets Mon 12:00am

144You've hit your Opus limit · resets 3:45pm

145```

146 

147Claude Code blocks further requests until the reset time shown in the message.

148 

149**What to do:**

150 

151* Wait for the reset time shown in the error

152* Run `/usage` to see your plan limits and when they reset

153* Run `/extra-usage` to buy additional usage on Pro and Max, or to request it from your admin on Team and Enterprise. See [Extra usage for paid plans](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) for how this is billed.

154* To upgrade your plan for higher base limits, see [claude.com/pricing](https://claude.com/pricing)

155 

156To watch your remaining allowance before you hit the limit, add the `rate_limits` fields to a [custom status line](/en/statusline#rate-limit-usage), or in the Desktop app click the [usage ring](/en/desktop#check-usage) next to the model picker.

157 

158### Server is temporarily limiting requests

159 

160The API applied a short-lived throttle that is unrelated to your plan quota.

161 

162```text theme={null}

163API Error: Server is temporarily limiting requests (not your usage limit)

164```

165 

166This is [retried automatically](#automatic-retries) before being shown.

167 

168**What to do:**

169 

170* Wait briefly and try again

171* Check [status.claude.com](https://status.claude.com) if it persists

172 

173### Request rejected (429)

174 

175You have hit the rate limit configured for your API key, Amazon Bedrock project, or Google Vertex AI project.

176 

177```text theme={null}

178API Error: Request rejected (429) · this may be a temporary capacity issue

179```

180 

181**What to do:**

182 

183* Run `/status` and confirm the active credential is the one you expect. A stray `ANTHROPIC_API_KEY` in your environment can route requests through a low-tier key instead of your subscription.

184* Check your provider console for the active limits and request a higher tier if needed

185* For Anthropic API keys, see the [rate limits reference](https://platform.claude.com/docs/en/api/rate-limits) for how tiers work and how to set per-workspace caps

186* Reduce concurrency: lower [`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`](/en/env-vars), avoid running many parallel subagents, or switch to a smaller model with `/model` for high-volume scripted runs

187 

188### Credit balance is too low

189 

190Your Console organization has run out of prepaid credits.

191 

192```text theme={null}

193Credit balance is too low

194```

195 

196**What to do:**

197 

198* Add credits at [platform.claude.com/settings/billing](https://platform.claude.com/settings/billing), and consider enabling auto-reload there so the balance refills before it hits zero

199* Switch to subscription authentication with `/login` if you have a Pro, Max, Team, or Enterprise plan

200* Set per-workspace spend caps in the Console to prevent a single project from draining the org balance. See [Manage costs effectively](/en/costs).

201 

202## Authentication errors

203 

204These errors mean Claude Code cannot prove who you are to the API. Run `/status` at any time to see which credential is currently active.

205 

206### Not logged in

207 

208No valid credential is available for this session.

209 

210```text theme={null}

211Not logged in · Please run /login

212```

213 

214**What to do:**

215 

216* Run `/login` to authenticate with your Claude subscription or Console account

217* If you expected an environment variable to authenticate you, confirm `ANTHROPIC_API_KEY` is set and exported in the shell where you launched `claude`

218* For CI or automation where interactive login is not possible, configure an [`apiKeyHelper`](/en/settings#available-settings) script that fetches a key at startup

219* See [Authentication precedence](/en/authentication#authentication-precedence) to understand which credential wins when several are present

220 

221If you are prompted to log in repeatedly, see [Not logged in or token expired](/en/troubleshoot-install#not-logged-in-or-token-expired) for system clock and macOS Keychain fixes.

222 

223### Invalid API key

224 

225The `ANTHROPIC_API_KEY` environment variable or `apiKeyHelper` script returned a key the API rejected.

226 

227```text theme={null}

228Invalid API key · Fix external API key

229```

230 

231**What to do:**

232 

233* Check for typos and confirm the key has not been revoked in the [Console](https://platform.claude.com/settings/keys)

234* Run `env | grep ANTHROPIC` in the same shell. Tools like direnv, dotenv shell plugins, and IDE terminals can load a stale key from a `.env` file in your project without you setting it explicitly.

235* Unset `ANTHROPIC_API_KEY` and run `/login` to use subscription auth instead

236* If the key comes from an [`apiKeyHelper`](/en/settings#available-settings) script, run the script directly to confirm it prints a valid key on stdout

237* Run `/status` to confirm which credential source Claude Code is actually using

238 

239### This organization has been disabled

240 

241A stale `ANTHROPIC_API_KEY` from a disabled Console organization is overriding your subscription login.

242 

243```text theme={null}

244Your ANTHROPIC_API_KEY belongs to a disabled organization · Unset the environment variable to use your other credentials

245API Error: 400 ... This organization has been disabled.

246```

247 

248Environment variables take precedence over `/login`, so a key exported in your shell profile or loaded from a `.env` file is used even when you have a working Pro or Max subscription. In non-interactive mode (`-p`), the key is always used when present.

249 

250**What to do:**

251 

252* Unset `ANTHROPIC_API_KEY` in the current shell and remove it from your shell profile, then relaunch `claude`

253* Run `/status` afterward to confirm the active credential is your subscription

254* If no environment variable is set and the error persists, the disabled organization is the one tied to your `/login`. Contact support or sign in with a different account.

255 

256### Routines are disabled by your organization's policy

257 

258Your Team or Enterprise admin has turned off routines at the organization level. The error appears when you try to create or run a routine, including from `/schedule` and the [Routines](/en/routines) UI on claude.ai/code.

259 

260```text theme={null}

261Routines are disabled by your organization's policy.

262```

263 

264This is a server-side setting, so it cannot be overridden from local settings, environment variables, or CLI flags.

265 

266**What to do:**

267 

268* Ask your admin to enable the **Routines** toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code)

269* For one-off scheduled work that does not require organization-level routines, see [scheduled tasks](/en/scheduled-tasks)

270 

271### OAuth token revoked or expired

272 

273Your saved login is no longer valid. A revoked token means you signed out everywhere or an admin removed access; an expired token means the automatic refresh failed mid-session.

274 

275```text theme={null}

276OAuth token revoked · Please run /login

277OAuth token has expired · Please run /login

278API Error: 401 ... authentication_error

279```

280 

281**What to do:**

282 

283* Run `/login` to sign in again

284* If the error returns within the same session after re-authenticating, run `/logout` first to fully clear the stored token, then `/login`

285* For repeated prompts to log in across launches, see the system clock and macOS Keychain checks in [Troubleshooting](/en/troubleshoot-install#not-logged-in-or-token-expired)

286* For other failures including `403 Forbidden` and OAuth browser issues, see [Login and authentication](/en/troubleshoot-install#login-and-authentication)

287 

288### OAuth scope requirement

289 

290The stored token predates a permission scope that a newer feature needs. You see this most often from `/usage` and the status line usage indicator:

291 

292```text theme={null}

293OAuth token does not meet scope requirement: user:profile

294```

295 

296**What to do:**

297 

298* Run `/login` to mint a new token with the current scopes. You do not need to log out first.

299 

300## Network and connection errors

301 

302These errors mean a network request from Claude Code failed to reach its destination. They usually originate in your local network, proxy, or firewall, or in the cloud environment's network policy.

303 

304### Unable to connect to API

305 

306The TCP connection to the API failed or never completed.

307 

308```text theme={null}

309Unable to connect to API. Check your internet connection

310Unable to connect to API (ECONNREFUSED)

311Unable to connect to API (ECONNRESET)

312Unable to connect to API (ETIMEDOUT)

313fetch failed

314Request timed out. Check your internet connection and proxy settings

315```

316 

317Common causes include no internet access, a VPN that blocks `api.anthropic.com`, or a required corporate proxy that is not configured.

318 

319**What to do:**

320 

321* Confirm you can reach the API host from the same shell by running `curl -I https://api.anthropic.com`. On Windows PowerShell use `curl.exe -I https://api.anthropic.com` so the built-in `Invoke-WebRequest` alias is not used.

322* If you are behind a corporate proxy, set `HTTPS_PROXY` before launching Claude Code and see [Network configuration](/en/network-config)

323* If you route through an LLM gateway or relay, set [`ANTHROPIC_BASE_URL`](/en/env-vars) to its address. See [LLM gateway configuration](/en/llm-gateway) for setup.

324* Ensure your firewall allows the hosts listed in [Network access requirements](/en/network-config#network-access-requirements)

325* Intermittent failures are [retried automatically](#automatic-retries); persistent failures point to a local network issue

326 

327If `curl` succeeds but Claude Code still fails, the cause is usually something between the runtime and the network rather than the network itself:

328 

329* On Linux and WSL, check `/etc/resolv.conf` for an unreachable nameserver. WSL in particular can inherit a broken resolver from the host.

330* On macOS, a VPN client that was disconnected or uninstalled can leave a tunnel interface or routing rule behind. Check `ifconfig` for stale `utun` interfaces and remove the VPN's network extension in System Settings.

331* Docker Desktop and similar container runtimes can intercept outbound traffic. Quit them and retry to rule this out.

332 

333### SSL certificate errors

334 

335A proxy or security appliance on your network is intercepting TLS traffic with its own certificate, and Claude Code does not trust it.

336 

337```text theme={null}

338Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates

339Unable to connect to API: Self-signed certificate detected

340```

341 

342**What to do:**

343 

344* Export your organization's CA bundle and point Claude Code at it with `NODE_EXTRA_CA_CERTS=/path/to/ca-bundle.pem`

345* See [Network configuration](/en/network-config#custom-ca-certificates) for full setup instructions

346* Do not set `NODE_TLS_REJECT_UNAUTHORIZED=0`, which disables certificate validation entirely

347 

348### Host not allowed in a cloud session

349 

350An outbound HTTP request from a cloud session or routine was blocked by the environment's network policy.

351 

352```text theme={null}

353HTTP 403

354x-deny-reason: host_not_allowed

355```

356 

357You may also see a TLS certificate that doesn't match the destination's real certificate. The cloud environment routes outbound traffic through a proxy that enforces the network policy, so a mismatched certificate means the proxy terminated the connection, not the destination.

358 

359This is not a client-side network problem. Cloud sessions and [routines](/en/routines) run inside a sandboxed environment whose outbound traffic is filtered to the environment's allowlist. The **Default** environment uses **Trusted** access, which permits the [default allowlist](/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains but blocks everything else.

360 

361**What to do:**

362 

363* Open the routine for editing, or start a cloud session. Select the cloud icon showing your environment's name, such as **Default**, to open the selector. Hover over your environment and click the settings icon.

364* In the **Update cloud environment** dialog, change **Network access** from **Trusted** to **Custom**, then add the blocked domain to **Allowed domains**. Enter one domain per line. Check **Also include default list of common package managers** to keep the [default allowlist](/en/claude-code-on-the-web#default-allowed-domains) alongside your custom domains. Select **Full** instead if you want unrestricted access.

365* Click **Save changes**. The next run uses the updated allowlist.

366 

367See [Network access](/en/claude-code-on-the-web#network-access) for access levels and the default allowlist. Local CLI sessions are not affected by this policy.

368 

369## Request errors

370 

371These errors mean the API received your request but rejected its content.

372 

373### Prompt is too long

374 

375The conversation plus attached files exceeds the model's context window.

376 

377```text theme={null}

378Prompt is too long

379```

380 

381**What to do:**

382 

383* Run `/compact` to summarize earlier turns and free space, or `/clear` to start fresh

384* Run `/context` to see a breakdown of what is consuming the window: system prompt, tools, memory files, and messages

385* Disable MCP servers you are not using with `/mcp disable <name>` to remove their tool definitions from context

386* Trim large `CLAUDE.md` memory files, or move instructions into [path-scoped rules](/en/memory#path-specific-rules) that load only when relevant

387* Subagents inherit every MCP tool definition from the parent session, which can fill their context window before the first turn. Disable MCP servers you are not using before spawning subagents.

388* Auto-compact is on by default and normally prevents this error. If you have set [`DISABLE_AUTO_COMPACT`](/en/env-vars), re-enable it or run `/compact` manually before the window fills.

389 

390See [Explore the context window](/en/context-window) for an interactive view of how context fills up.

391 

392### Error during compaction: Conversation too long

393 

394`/compact` itself failed because there is not enough free context to hold the summary it produces.

395 

396```text theme={null}

397Error during compaction: Conversation too long. Press esc twice to go up a few messages and try again.

398```

399 

400This can happen when the window is already full at the moment auto-compact triggers, or when you run `/compact` after seeing `Prompt is too long`.

401 

402**What to do:**

403 

404* Press Esc twice to open the message list and step back several turns. This drops the most recent messages from context. Then run `/compact` again.

405* If stepping back does not free enough space, run `/clear` to start a fresh session. Your previous conversation is preserved and can be reopened with `/resume`.

406 

407### Request too large

408 

409The raw request body exceeded the API's byte limit before tokenization, usually because of a large pasted file or attachment.

410 

411```text theme={null}

412Request too large (max 30 MB). Double press esc to go back and remove or shrink the attached content.

413```

414 

415This is a size limit on the HTTP request, separate from the [context window limit](#prompt-is-too-long).

416 

417**What to do:**

418 

419* Press Esc twice and step back past the turn that added the oversized content

420* Reference large files by path instead of pasting their contents, so Claude can read them in chunks

421* For images, see [Image was too large](#image-was-too-large) below

422 

423### Image was too large

424 

425A pasted or attached image exceeds the API's size or dimension limits.

426 

427```text theme={null}

428Image was too large. Double press esc to go back and try again with a smaller image.

429API Error: 400 ... image dimensions exceed max allowed size

430```

431 

432The image stays in conversation history after the error, so every subsequent message fails with the same error until you remove it.

433 

434**What to do:**

435 

436* Press Esc twice and step back past the turn where the image was added

437* Resize the image before pasting. The API accepts images up to 8000 pixels on the longest edge for a single image, or 2000 pixels when many images are in context.

438* Take a tighter screenshot of the relevant region instead of the full screen

439 

440### PDF errors

441 

442The PDF you attached could not be processed.

443 

444```text theme={null}

445PDF too large (max 100 pages, 32 MB). Try splitting it or extracting text first.

446PDF is password protected. Try removing protection or extracting text first.

447The PDF file was not valid. Try converting to a different format first.

448```

449 

450**What to do:**

451 

452* For oversized PDFs, ask Claude to read a page range with the Read tool instead of attaching the whole file, or extract text with a tool like `pdftotext` and reference the output file by path

453* For protected or invalid PDFs, remove the password or re-export the file from its source application, then try again

454 

455### Extra inputs are not permitted

456 

457A proxy or LLM gateway between Claude Code and the API stripped the `anthropic-beta` request header, so the API rejected fields that depend on it.

458 

459```text theme={null}

460API Error: 400 ... Extra inputs are not permitted ... context_management

461API Error: 400 ... Extra inputs are not permitted ... tools.0.custom.input_examples

462API Error: 400 ... Unexpected value(s) for the `anthropic-beta` header

463```

464 

465Claude Code sends beta-only fields such as `context_management`, `effort`, and tool `input_examples` alongside an `anthropic-beta` header that enables them. When a gateway forwards the body but drops the header, the API sees fields it does not recognize.

466 

467**What to do:**

468 

469* Configure your gateway to forward the `anthropic-beta` header. See [LLM gateway configuration](/en/llm-gateway).

470* As a fallback, set [`CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`](/en/env-vars) before launching. This disables features that require the beta header so requests succeed through a gateway that cannot forward it.

471 

472### There's an issue with the selected model

473 

474The configured model name was not recognized or your account lacks access to it.

475 

476```text theme={null}

477There's an issue with the selected model (claude-...). It may not exist or you may not have access to it. Run /model to select a different one.

478```

479 

480**What to do:**

481 

482* Run `/model` to pick from models available to your account

483* Use an alias such as `sonnet` or `opus` instead of a full versioned ID. Aliases track the latest release so they do not go stale. See [Model configuration](/en/model-config).

484* If the wrong model keeps coming back, a stale ID is set somewhere. Check in [priority order](/en/model-config#setting-your-model): the `--model` flag, the `ANTHROPIC_MODEL` environment variable, then the `model` field in `.claude/settings.local.json`, your project's `.claude/settings.json`, and `~/.claude/settings.json`. Remove the stale value and Claude Code falls back to your account default.

485* For Vertex AI deployments, see [Vertex AI troubleshooting](/en/google-vertex-ai#troubleshooting).

486 

487### Claude Opus is not available with the Claude Pro plan

488 

489Your active subscription plan does not include the model you selected.

490 

491```text theme={null}

492Claude Opus is not available with the Claude Pro plan · Select a different model in /model

493```

494 

495**What to do:**

496 

497* Run `/model` and select a model your plan includes

498* If you upgraded your plan recently and still see this, run `/logout` then `/login`. The stored token reflects your plan at the time you signed in, so upgrading on the web does not take effect in an existing session until you re-authenticate.

499* See [claude.com/pricing](https://claude.com/pricing) for which models each plan includes

500 

501### thinking.type.enabled is not supported for this model

502 

503Your Claude Code version is older than the minimum for Opus 4.7. The CLI sent a thinking configuration the model no longer accepts.

504 

505```text theme={null}

506API Error: 400 ... "thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.

507```

508 

509**What to do:**

510 

511* Run `claude update` to upgrade to v2.1.111 or later, then restart Claude Code

512* If you cannot upgrade, run `/model` and select Opus 4.6 or Sonnet instead

513* If you hit this in the Agent SDK, see [SDK troubleshooting](/en/agent-sdk/quickstart#troubleshooting)

514 

515### Thinking budget exceeds output limit

516 

517The configured extended thinking budget exceeds the maximum response length, so there is no room left for the actual answer.

518 

519```text theme={null}

520API Error: 400 ... max_tokens must be greater than thinking.budget_tokens

521```

522 

523Claude Code adjusts these values automatically on the Anthropic API. You typically see this error on Amazon Bedrock or Google Vertex AI when [`MAX_THINKING_TOKENS`](/en/env-vars) is set higher than the provider's output limit, or when plan mode raises the thinking budget.

524 

525**What to do:**

526 

527* Lower `MAX_THINKING_TOKENS`, or raise [`CLAUDE_CODE_MAX_OUTPUT_TOKENS`](/en/env-vars) above the thinking budget

528* See [Extended thinking](/en/model-config#extended-thinking) for how the budget interacts with output length

529 

530### Tool use or thinking block mismatch

531 

532The conversation history reached the API in an inconsistent state, usually after a tool call was interrupted or a turn was edited mid-stream.

533 

534```text theme={null}

535API Error: 400 due to tool use concurrency issues. Run /rewind to recover the conversation.

536API Error: 400 ... unexpected `tool_use_id` found in `tool_result` blocks

537API Error: 400 ... thinking blocks ... cannot be modified

538```

539 

540All three variants mean the same thing: the sequence of `tool_use`, `tool_result`, and `thinking` blocks in history no longer matches what the API expects.

541 

542**What to do:**

543 

544* Run `/rewind`, or press Esc twice, to step back to a checkpoint before the corrupted turn and continue from there. See [Checkpointing](/en/checkpointing) for how checkpoints are created and restored.

545 

546## Responses seem lower quality than usual

547 

548If Claude's answers seem less capable than you expect but no error is shown, the cause is usually conversation state rather than the model itself. Claude Code does not silently change model versions. It can switch to a fallback model in specific cases such as an Opus quota being reached or a Bedrock or Vertex AI region lacking your model; the Model selection check below catches both, and [Model configuration](/en/model-config) explains when fallback applies.

549 

550Check these first:

551 

552* **Model selection**: run `/model` to confirm you are on the model you expect. A previous `/model` choice or an `ANTHROPIC_MODEL` environment variable may have you on a smaller model than you intended.

553* **Effort level**: run `/effort` to check the current reasoning level and raise it for hard debugging or design work. Defaults vary by model, so check before assuming you are below the maximum. See [Adjust effort level](/en/model-config#adjust-effort-level) for per-model defaults and the `ultrathink` shortcut.

554* **Context pressure**: run `/context` to see how full the window is. If it is near capacity, run `/compact` at a natural breakpoint or `/clear` to start fresh. See [Explore the context window](/en/context-window) for how auto-compact affects earlier turns.

555* **Stale instructions**: large or outdated `CLAUDE.md` files and MCP tool definitions consume context and can steer responses. `/doctor` flags oversized memory files and subagent definitions; `/context` shows MCP tool token usage.

556 

557When a response goes wrong, rewinding usually works better than replying with corrections. Press Esc twice or run `/rewind` to step back to before the bad turn, then rephrase the prompt with more specifics. Correcting in-thread keeps the wrong attempt in context, which can anchor later answers to it. See [Checkpointing](/en/checkpointing).

558 

559If quality still seems off after checking the above, run `/feedback` and describe what you expected versus what you got. Feedback submitted this way includes the conversation transcript, which is the fastest way for Anthropic to diagnose a real regression. See [Report an error](#report-an-error) if `/feedback` is unavailable on your provider.

560 

561## Report an error

562 

563This page covers errors from the Claude API. For errors from other Claude Code components, see the relevant guide:

564 

565* MCP server failed to connect or authenticate: [MCP](/en/mcp)

566* Hook script failed or blocked a tool: [Debug hooks](/en/hooks#debug-hooks)

567* Permission denied or filesystem errors during install: [Troubleshoot installation and login](/en/troubleshoot-install)

568 

569If an error is not listed here or the suggested fix does not help:

570 

571* Run `/feedback` inside Claude Code to send the transcript and a description to Anthropic. The command also offers to open a prefilled GitHub issue. Feedback is unavailable on Bedrock, Vertex AI, and Foundry deployments.

572* Run `/doctor` to check for local configuration problems

573* Check [status.claude.com](https://status.claude.com) for active incidents

574* Search [existing issues](https://github.com/anthropics/claude-code/issues) on GitHub

fast-mode.md +1 −1

Details

12 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.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 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.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. Fast mode is not available on Opus 4.7 or other models.

16 16 

17<Note>17<Note>

18 Fast mode requires Claude Code v2.1.36 or later. Check your version with `claude --version`.18 Fast mode requires Claude Code v2.1.36 or later. Check your version with `claude --version`.

Details

23* **[MCP](/en/mcp)** connects Claude to external services and tools23* **[MCP](/en/mcp)** connects Claude to external services and tools

24* **[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 messaging25* **[Agent teams](/en/agent-teams)** coordinate multiple independent sessions with shared tasks and peer-to-peer messaging

26* **[Hooks](/en/hooks)** run outside the loop entirely as deterministic scripts26* **[Hooks](/en/hooks-guide)** fire on lifecycle events and can run a script, HTTP request, prompt, or subagent

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

28 28 

29[Skills](/en/skills) are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents.29[Skills](/en/skills) are the most flexible extension. A skill is a markdown file containing knowledge, workflows, or instructions. You can invoke skills with a command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents.


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

34 34 

35| Feature | What it does | When to use it | Example |35| Feature | What it does | When to use it | Example |

36| ---------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |36| ---------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |

37| **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." |

38| **Skill** | Instructions, knowledge, and workflows Claude can use | Reusable content, reference docs, repeatable tasks | `/deploy` runs your deployment checklist; API docs skill with endpoint patterns |38| **Skill** | Instructions, knowledge, and workflows Claude can use | Reusable content, reference docs, repeatable tasks | `/deploy` runs your deployment checklist; API docs skill with endpoint patterns |

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

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

42| **Hook** | Deterministic script that runs on events | Predictable automation, no LLM involved | Run ESLint after every file edit |42| **Hook** | Script, HTTP request, prompt, or subagent triggered by events | Automation that must run on every matching event | Run ESLint after every file edit |

43 43 

44**[Plugins](/en/plugins)** are the packaging layer. A plugin bundles skills, hooks, subagents, and MCP servers into a single installable unit. Plugin skills are namespaced (like `/my-plugin:review`) so multiple plugins can coexist. Use plugins when you want to reuse the same setup across multiple repositories or distribute to others via a **[marketplace](/en/plugin-marketplaces)**.44**[Plugins](/en/plugins)** are the packaging layer. A plugin bundles skills, hooks, subagents, and MCP servers into a single installable unit. Plugin skills are namespaced (like `/my-plugin:review`) so multiple plugins can coexist. Use plugins when you want to reuse the same setup across multiple repositories or distribute to others via a **[marketplace](/en/plugin-marketplaces)**.

45 45 


71 * **Subagents** are isolated workers that run separately from your main conversation71 * **Subagents** are isolated workers that run separately from your main conversation

72 72 

73 | Aspect | Skill | Subagent |73 | Aspect | Skill | Subagent |

74 | --------------- | ---------------------------------------------- | ---------------------------------------------------------------- |74 | ----------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------- |

75 | **What it is** | Reusable instructions, knowledge, or workflows | Isolated worker with its own context |75 | **What it is** | Reusable instructions, knowledge, or workflows | Isolated worker with its own context |

76 | **Key benefit** | Share content across contexts | Context isolation. Work happens separately, only summary returns |76 | **Key benefit** | Share content across contexts | Context isolation. Work happens separately, only summary returns |

77 | **[Context window](/en/context-window) impact** | Adds to your main window | Uses a separate window with its own input and output tokens |

77 | **Best for** | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers |78 | **Best for** | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers |

78 79 

79 **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).80 **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).


158 159 

159 Example: An MCP server connects Claude to your database. A skill teaches Claude your data model, common query patterns, and which tables to use for different tasks.160 Example: An MCP server connects Claude to your database. A skill teaches Claude your data model, common query patterns, and which tables to use for different tasks.

160 </Tab>161 </Tab>

162 

163 <Tab title="Hook vs Skill">

164 A hook fires on a lifecycle event; a skill is loaded into context for Claude to apply.

165 

166 | Aspect | Hook | Skill |

167 | ---------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------- |

168 | **Runs** | A shell command, HTTP request, LLM prompt, or subagent | Instructions Claude reads and follows |

169 | **Triggered by** | [Lifecycle events](/en/hooks#hook-events) such as `PostToolUse` or `SessionStart` | You typing `/<name>`, or Claude matching the description to your task |

170 | **Determinism** | Always fires on its event; the trigger is guaranteed | Claude interprets the instructions; outcome can vary |

171 | **Context cost** | Zero unless the hook returns output | Description loads each session; full content loads when used |

172 | **Best for** | Linting after edits, blocking unsafe commands, logging, notifications | Workflows that need reasoning, reference material, multi-step tasks |

173 

174 **Use a hook** when the action must happen the same way every time and doesn't need Claude to think. For example: format on save, reject `rm -rf /`, post a Slack message when a session ends.

175 

176 **Use a skill** when Claude should decide how to apply the steps, or when the content is knowledge rather than a script. For example: a `/release` checklist, your API style guide, a debugging playbook.

177 

178 **Put guardrails in hooks.** An instruction like "never edit `.env`" in CLAUDE.md or a skill is a request, not a guarantee. A `PreToolUse` hook that blocks the edit is enforcement. If a rule must hold every time, make it a hook rather than a prompt instruction.

179 

180 **Hook output lands in context.** A `PostToolUse` hook that runs your linter feeds results back as text Claude reads; a `/fix-lint` skill tells Claude how to resolve them.

181 </Tab>

161</Tabs>182</Tabs>

162 183 

163### Understand how features layer184### Understand how features layer


198| **Subagents** | When spawned | Fresh context with specified skills | Isolated from main session |219| **Subagents** | When spawned | Fresh context with specified skills | Isolated from main session |

199| **Hooks** | On trigger | Nothing (runs externally) | Zero, unless hook returns additional context |220| **Hooks** | On trigger | Nothing (runs externally) | Zero, unless hook returns additional context |

200 221 

201\*By default, skill descriptions load at session start so Claude can decide when to use them. Set `disable-model-invocation: true` in a skill's frontmatter to hide it from Claude entirely until you invoke it manually. This reduces context cost to zero for skills you only trigger yourself.222\*By default, skill descriptions load at session start so Claude can decide when to use them. Set `disable-model-invocation: true` in a skill's frontmatter to hide it from Claude entirely until you invoke it manually. This reduces context cost to zero for skills you only trigger yourself. For a skill you didn't write, set [`skillOverrides`](/en/skills#override-skill-visibility-from-settings) in settings to do the same without editing its file.

202 223 

203### Understand how features load224### Understand how features load

204 225 


228 249 

229 **Context cost:** Low until used. User-only skills have zero cost until invoked.250 **Context cost:** Low until used. User-only skills have zero cost until invoked.

230 251 

231 **In subagents:** Skills work differently in subagents. Instead of on-demand loading, skills passed to a subagent are fully preloaded into its context at launch. Subagents don't inherit skills from the main session; you must specify them explicitly.252 **In subagents:** Skills work differently in subagents. Instead of on-demand loading, skills listed in the subagent's `skills` field are fully preloaded into its context at launch. Subagents can still discover and invoke unlisted project, user, and plugin skills through the Skill tool.

232 253 

233 <Tip>Use `disable-model-invocation: true` for skills with side effects. This saves context and ensures only you trigger them.</Tip>254 <Tip>Use `disable-model-invocation: true` for skills with side effects. This saves context and ensures only you trigger them.</Tip>

234 </Tab>255 </Tab>


263 <Tab title="Hooks">284 <Tab title="Hooks">

264 **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.285 **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.

265 286 

266 **What loads:** Nothing by default. Hooks run as external scripts.287 **What loads:** Nothing by default. Hooks execute outside the main conversation.

267 288 

268 **Context cost:** Zero, unless the hook returns output that gets added as messages to your conversation.289 **Context cost:** Zero, unless the hook returns output that gets added as messages to your conversation.

269 290 

fullscreen.md +36 −19

Details

7> Enable a smoother, flicker-free rendering mode with mouse support and stable memory usage in long conversations.7> Enable a smoother, flicker-free rendering mode with mouse support and stable memory usage in long conversations.

8 8 

9<Note>9<Note>

10 Fullscreen rendering is an opt-in [research preview](#research-preview) and requires Claude Code v2.1.89 or later. Enable it with `CLAUDE_CODE_NO_FLICKER=1`. Behavior may change based on feedback.10 Fullscreen rendering is an opt-in [research preview](#research-preview) and requires Claude Code v2.1.89 or later. Run `/tui fullscreen` to switch in your current conversation, or set `CLAUDE_CODE_NO_FLICKER=1` on versions before v2.1.110. Behavior may change based on feedback.

11</Note>11</Note>

12 12 

13Fullscreen rendering is an alternative rendering path for the Claude Code CLI that eliminates flicker, keeps memory usage flat in long conversations, and adds mouse support. It draws the interface on the terminal's alternate screen buffer, like `vim` or `htop`, and only renders messages that are currently visible. This reduces the amount of data sent to your terminal on each update.13Fullscreen rendering is an alternative rendering path for the Claude Code CLI that eliminates flicker, keeps memory usage flat in long conversations, and adds mouse support. It draws the interface on the terminal's alternate screen buffer, like `vim` or `htop`, and only renders messages that are currently visible. This reduces the amount of data sent to your terminal on each update.


20 20 

21## Enable fullscreen rendering21## Enable fullscreen rendering

22 22 

23Set the `CLAUDE_CODE_NO_FLICKER` environment variable when starting Claude Code:23Run `/tui fullscreen` inside any Claude Code conversation. The CLI saves the [`tui` setting](/en/settings#available-settings) and relaunches into fullscreen with your conversation intact, so you can switch mid-session without losing context. Run `/tui` with no argument to print which renderer is active.

24 

25You can also set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code:

24 26 

25```bash theme={null}27```bash theme={null}

26CLAUDE_CODE_NO_FLICKER=1 claude28CLAUDE_CODE_NO_FLICKER=1 claude

27```29```

28 30 

29To enable it for every session, export the variable in your shell profile such as `~/.zshrc` or `~/.bashrc`:31The `tui` setting and the environment variable are equivalent. The `/tui` command clears `CLAUDE_CODE_NO_FLICKER` from the relaunched process so the setting it writes takes effect.

30 

31```bash theme={null}

32export CLAUDE_CODE_NO_FLICKER=1

33```

34 32 

35## What changes33## What changes

36 34 


39Because the conversation lives in the alternate screen buffer instead of your terminal's scrollback, a few things work differently:37Because the conversation lives in the alternate screen buffer instead of your terminal's scrollback, a few things work differently:

40 38 

41| Before | Now | Details |39| Before | Now | Details |

42| :-------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |40| :-------------------------------------------------- | :----------------------------------------------------------------------------- | :------------------------------------------------------------------------ |

43| `Cmd+f` or tmux search to find text | `Ctrl+o` once for transcript mode (then `/` to search or `[` to write to scrollback), or `Ctrl+o` twice for focus view (last prompt + tool summary + response) | [Search and review the conversation](#search-and-review-the-conversation) |41| `Cmd+f` or tmux search to find text | `Ctrl+o` for transcript mode, then `/` to search or `[` to write to scrollback | [Search and review the conversation](#search-and-review-the-conversation) |

44| Terminal's native click-and-drag to select and copy | In-app selection, copies automatically on mouse release | [Use the mouse](#use-the-mouse) |42| Terminal's native click-and-drag to select and copy | In-app selection, copies automatically on mouse release | [Use the mouse](#use-the-mouse) |

45| `Cmd`-click to open a URL | Click the URL | [Use the mouse](#use-the-mouse) |43| `Cmd`-click to open a URL | Click the URL | [Use the mouse](#use-the-mouse) |

46 44 


58 56 

59Selected text copies to your clipboard automatically on mouse release. To turn this off, toggle Copy on select in `/config`. With it off, press `Ctrl+Shift+c` to copy manually. On terminals that support the kitty keyboard protocol, such as kitty, WezTerm, Ghostty, and iTerm2, `Cmd+c` also works. If you have a selection active, `Ctrl+c` copies instead of cancelling.57Selected text copies to your clipboard automatically on mouse release. To turn this off, toggle Copy on select in `/config`. With it off, press `Ctrl+Shift+c` to copy manually. On terminals that support the kitty keyboard protocol, such as kitty, WezTerm, Ghostty, and iTerm2, `Cmd+c` also works. If you have a selection active, `Ctrl+c` copies instead of cancelling.

60 58 

59With a selection active, hold `Shift` and press the arrow keys to extend it from the keyboard. `Shift+↑` and `Shift+↓` scroll the viewport when the selection reaches the top or bottom edge. `Shift+Home` and `Shift+End` extend to the start or end of the current line.

60 

61## Scroll the conversation61## Scroll the conversation

62 62 

63Fullscreen rendering handles scrolling inside the app. Use these shortcuts to navigate:63Fullscreen rendering handles scrolling inside the app. Use these shortcuts to navigate:


71 71 

72On keyboards without dedicated `PgUp`, `PgDn`, `Home`, or `End` keys, like MacBook keyboards, hold `Fn` with the arrow keys: `Fn+↑` sends `PgUp`, `Fn+↓` sends `PgDn`, `Fn+←` sends `Home`, and `Fn+→` sends `End`. That makes `Ctrl+Fn+→` the jump-to-bottom shortcut. If that feels awkward, scroll to the bottom with the mouse wheel to resume following, or rebind `scroll:bottom` to something reachable.72On keyboards without dedicated `PgUp`, `PgDn`, `Home`, or `End` keys, like MacBook keyboards, hold `Fn` with the arrow keys: `Fn+↑` sends `PgUp`, `Fn+↓` sends `PgDn`, `Fn+←` sends `Home`, and `Fn+→` sends `End`. That makes `Ctrl+Fn+→` the jump-to-bottom shortcut. If that feels awkward, scroll to the bottom with the mouse wheel to resume following, or rebind `scroll:bottom` to something reachable.

73 73 

74These actions are rebindable. See [Scroll actions](/en/keybindings#scroll-actions) for the full list of action names, including half-page and full-page variants that have no default binding.

75 

76### Auto-follow

77 

74Scrolling up pauses auto-follow so new output does not pull you back to the bottom. Press `Ctrl+End` or scroll to the bottom to resume following.78Scrolling up pauses auto-follow so new output does not pull you back to the bottom. Press `Ctrl+End` or scroll to the bottom to resume following.

75 79 

76These actions are rebindable. See [Scroll actions](/en/keybindings#scroll-actions) for the full list of action names, including half-page and full-page variants that have no default binding.80To turn auto-follow off entirely so the view stays where you leave it, open `/config` and set Auto-scroll to off. With auto-scroll disabled, the view never jumps to the bottom on its own. Permission prompts and other dialogs that need a response still scroll into view regardless of this setting.

77 81 

78Mouse wheel scrolling requires your terminal to forward mouse events to Claude Code. Most terminals do this whenever an application requests it. iTerm2 makes it a per-profile setting: if the wheel does nothing but `PgUp` and `PgDn` work, open Settings → Profiles → Terminal and turn on Enable mouse reporting. The same setting is also required for click-to-expand and text selection to work.82### Mouse wheel scrolling

79 83 

80### Adjust wheel scroll speed84Mouse wheel scrolling requires your terminal to forward mouse events to Claude Code. Most terminals do this whenever an application requests it. iTerm2 makes it a per-profile setting: if the wheel does nothing but `PgUp` and `PgDn` work, open Settings → Profiles → Terminal and turn on Enable mouse reporting. The same setting is also required for click-to-expand and text selection to work.

81 85 

82If mouse wheel scrolling feels slow, your terminal may be sending one scroll event per physical notch with no multiplier. Some terminals, like Ghostty and iTerm2 with faster scrolling enabled, already amplify wheel events. Others, including the VS Code integrated terminal, send exactly one event per notch. Claude Code cannot detect which.86If mouse wheel scrolling feels slow, your terminal may be sending one scroll event per physical notch with no multiplier. Some terminals, like Ghostty and iTerm2 with faster scrolling enabled, already amplify wheel events. Others, including the VS Code integrated terminal, send exactly one event per notch. Claude Code cannot detect which.

83 87 


89 93 

90A value of `3` matches the default in `vim` and similar applications. The setting accepts values from 1 to 20.94A value of `3` matches the default in `vim` and similar applications. The setting accepts values from 1 to 20.

91 95 

96### Scroll in the JetBrains IDE terminal

97 

98In the JetBrains IDE terminal, Claude Code applies its own scroll handling and ignores `CLAUDE_CODE_SCROLL_SPEED`. The terminal sends scroll events at a much higher rate than other emulators, so a multiplier tuned elsewhere overshoots here.

99 

100In 2025.2, the terminal also has scroll-wheel bugs that produce spurious arrow keys and wrong-direction events. Claude Code detects these at runtime and mitigates them automatically, so trackpad and mouse wheel scrolling work without configuration. For the best scroll experience, upgrade to 2025.3 or later. Claude Code shows a hint the first time you scroll if it detects the bug.

101 

92## Search and review the conversation102## Search and review the conversation

93 103 

94In fullscreen rendering, `Ctrl+o` cycles through three states: normal prompt, transcript mode, and focus view. Press it once to enter transcript mode, press it again to return to a focus view showing just your last prompt, a one-line summary of tool calls with edit diffstats, and the final response. Press it a third time to return to the normal prompt screen.104`Ctrl+o` toggles between the normal prompt and transcript mode. For a quieter view that shows only your last prompt, a one-line summary of tool calls with edit diffstats, and the final response, run `/focus`. The setting persists across sessions. Run `/focus` again to turn it off.

95 105 

96Transcript mode gains `less`-style navigation and search:106Transcript mode gains `less`-style navigation and search:

97 107 


103| `g` / `G` or `Home` / `End` | Jump to top or bottom |113| `g` / `G` or `Home` / `End` | Jump to top or bottom |

104| `Ctrl+u` / `Ctrl+d` | Scroll half a page |114| `Ctrl+u` / `Ctrl+d` | Scroll half a page |

105| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |115| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |

106| `Ctrl+o` | Advance to focus view |116| `Ctrl+o`, `Esc`, or `q` | Exit transcript mode and return to the prompt |

107| `Esc` or `q` | Exit transcript mode and return to the prompt |

108 117 

109Your terminal's `Cmd+f` and tmux search don't see the conversation because it lives in the alternate screen buffer, not the native scrollback. To hand the content back to your terminal, press `Ctrl+o` to enter transcript mode first, then:118Your terminal's `Cmd+f` and tmux search don't see the conversation because it lives in the alternate screen buffer, not the native scrollback. To hand the content back to your terminal, press `Ctrl+o` to enter transcript mode first, then:

110 119 


113 122 

114Press `Esc` or `q` to return to the prompt.123Press `Esc` or `q` to return to the prompt.

115 124 

125## Clear the conversation

126 

127Press `Ctrl+L` twice within two seconds to run `/clear` and start a new conversation. The first press redraws the screen and shows a hint; the second press clears the conversation. On macOS, double-pressing `Cmd+K` also runs `/clear`.

128 

116## Use with tmux129## Use with tmux

117 130 

118Fullscreen rendering works inside tmux, with two caveats.131Fullscreen rendering works inside tmux, with three caveats.

119 132 

120Mouse wheel scrolling requires tmux's mouse mode. If your `~/.tmux.conf` does not already enable it, add this line and reload your config:133Mouse wheel scrolling requires tmux's mouse mode. If your `~/.tmux.conf` does not already enable it, add this line and reload your config:

121 134 


127 140 

128Fullscreen rendering is incompatible with iTerm2's tmux integration mode, which is the mode you enter with `tmux -CC`. In integration mode, iTerm2 renders each tmux pane as a native split rather than letting tmux draw to the terminal. The alternate screen buffer and mouse tracking do not work correctly there: the mouse wheel does nothing, and double-click can corrupt the terminal state. Don't enable fullscreen rendering in `tmux -CC` sessions. Regular tmux inside iTerm2, without `-CC`, works fine.141Fullscreen rendering is incompatible with iTerm2's tmux integration mode, which is the mode you enter with `tmux -CC`. In integration mode, iTerm2 renders each tmux pane as a native split rather than letting tmux draw to the terminal. The alternate screen buffer and mouse tracking do not work correctly there: the mouse wheel does nothing, and double-click can corrupt the terminal state. Don't enable fullscreen rendering in `tmux -CC` sessions. Regular tmux inside iTerm2, without `-CC`, works fine.

129 142 

143tmux does not support synchronized output, so you may see more flicker during redraws than when running Claude Code directly in your terminal. If the flicker is noticeable, especially over SSH, run Claude Code in its own terminal tab outside tmux.

144 

130## Keep native text selection145## Keep native text selection

131 146 

132Mouse capture is the most common friction point, especially over SSH or inside tmux. When Claude Code captures mouse events, your terminal's native copy-on-select stops working. The selection you make with click-and-drag exists inside Claude Code, not in your terminal's selection buffer, so tmux copy mode, Kitty hints, and similar tools don't see it.147Mouse capture is the most common friction point, especially over SSH or inside tmux. When Claude Code captures mouse events, your terminal's native copy-on-select stops working. The selection you make with click-and-drag exists inside Claude Code, not in your terminal's selection buffer, so tmux copy mode, Kitty hints, and similar tools don't see it.

133 148 

134Claude Code tries to write the selection to your clipboard, but the path it uses depends on your setup. Inside tmux it writes to the tmux paste buffer. Over SSH it falls back to OSC 52 escape sequences, which some terminals block by default. Claude Code prints a toast after each copy telling you which path it used.149Claude Code tries to write the selection to your clipboard, but the path it uses depends on your setup. Inside tmux it writes to the tmux paste buffer. Over SSH it falls back to OSC 52 escape sequences, which some terminals block by default. iTerm2 blocks them until you turn on Settings → General → Selection → Applications in terminal may access clipboard. Running [`/terminal-setup`](/en/terminal-config) in iTerm2 enables this for you. Claude Code prints a toast after each copy telling you which path it used.

150 

151For a one-off native selection, hold your terminal's bypass modifier while you click and drag: `Option` in iTerm2, or `Shift` in most Linux and Windows terminals. The modifier tells your terminal to handle the selection itself instead of forwarding mouse events to Claude Code, so `Cmd+C` and your terminal's other copy shortcuts work on it.

135 152 

136If you rely on your terminal's native selection, set `CLAUDE_CODE_DISABLE_MOUSE=1` to opt out of mouse capture while keeping the flicker-free rendering and flat memory:153If you rely on native selection all the time, set `CLAUDE_CODE_DISABLE_MOUSE=1` to opt out of mouse capture while keeping the flicker-free rendering and flat memory:

137 154 

138```bash theme={null}155```bash theme={null}

139CLAUDE_CODE_NO_FLICKER=1 CLAUDE_CODE_DISABLE_MOUSE=1 claude156CLAUDE_CODE_NO_FLICKER=1 CLAUDE_CODE_DISABLE_MOUSE=1 claude


147 164 

148If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](https://github.com/anthropics/claude-code/issues). Include your terminal emulator name and version.165If you encounter a problem, run `/feedback` inside Claude Code to report it, or open an issue on the [claude-code GitHub repo](https://github.com/anthropics/claude-code/issues). Include your terminal emulator name and version.

149 166 

150To turn fullscreen rendering off, unset the environment variable or set `CLAUDE_CODE_NO_FLICKER=0`.167To turn fullscreen rendering off, run `/tui default`, or unset `CLAUDE_CODE_NO_FLICKER` if you enabled it that way. To force the classic renderer regardless of the saved `tui` setting, set `CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1`. The classic renderer keeps the conversation in your terminal's native scrollback so `Cmd+f` and tmux copy mode work as usual.

github-actions.md +11 −11

Details

13</Note>13</Note>

14 14 

15<Info>15<Info>

16 **Claude Opus 4.6 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.6, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-6`.16 **Claude Opus 4.7 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.7, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-7`.

17</Info>17</Info>

18 18 

19## Why use Claude Code GitHub Actions?19## Why use Claude Code GitHub Actions?


46 * You must be a repository admin to install the GitHub app and add secrets46 * You must be a repository admin to install the GitHub app and add secrets

47 * The GitHub app will request read & write permissions for Contents, Issues, and Pull requests47 * The GitHub app will request read & write permissions for Contents, Issues, and Pull requests

48 * This quickstart method is only available for direct Claude API users. If48 * This quickstart method is only available for direct Claude API users. If

49 you're using AWS Bedrock or Google Vertex AI, please see the [Using with AWS49 you're using Amazon Bedrock or Google Vertex AI, see the [Using with Amazon

50 Bedrock & Google Vertex AI](#using-with-aws-bedrock-%26-google-vertex-ai)50 Bedrock & Google Vertex AI](#using-with-amazon-bedrock-%26-google-vertex-ai)

51 section.51 section.

52</Note>52</Note>

53 53 


277 When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the `prompt` parameter to provide instructions.277 When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the `prompt` parameter to provide instructions.

278</Tip>278</Tip>

279 279 

280## Using with AWS Bedrock & Google Vertex AI280## Using with Amazon Bedrock & Google Vertex AI

281 281 

282For enterprise environments, you can use Claude Code GitHub Actions with your own cloud infrastructure. This approach gives you control over data residency and billing while maintaining the same functionality.282For enterprise environments, you can use Claude Code GitHub Actions with your own cloud infrastructure. This approach gives you control over data residency and billing while maintaining the same functionality.

283 283 


2923. A service account with the required permissions2923. A service account with the required permissions

2934. A GitHub App (recommended) or use the default GITHUB\_TOKEN2934. A GitHub App (recommended) or use the default GITHUB\_TOKEN

294 294 

295#### For AWS Bedrock:295#### For Amazon Bedrock:

296 296 

2971. An AWS account with Amazon Bedrock enabled2971. An AWS account with Amazon Bedrock enabled

2982. GitHub OIDC Identity Provider configured in AWS2982. GitHub OIDC Identity Provider configured in AWS


343 Choose your cloud provider and set up secure authentication:343 Choose your cloud provider and set up secure authentication:

344 344 

345 <AccordionGroup>345 <AccordionGroup>

346 <Accordion title="AWS Bedrock">346 <Accordion title="Amazon Bedrock">

347 **Configure AWS to allow GitHub Actions to authenticate securely without storing credentials.**347 **Configure AWS to allow GitHub Actions to authenticate securely without storing credentials.**

348 348 

349 > **Security Note**: Use repository-specific configurations and grant only the minimum required permissions.349 > **Security Note**: Use repository-specific configurations and grant only the minimum required permissions.


442 * `APP_ID`: Your GitHub App's ID442 * `APP_ID`: Your GitHub App's ID

443 * `APP_PRIVATE_KEY`: The private key (.pem) content443 * `APP_PRIVATE_KEY`: The private key (.pem) content

444 444 

445 #### For AWS Bedrock445 #### For Amazon Bedrock

446 446 

447 1. **For AWS Authentication**:447 1. **For AWS Authentication**:

448 * `AWS_ROLE_TO_ASSUME`448 * `AWS_ROLE_TO_ASSUME`


453 </Step>453 </Step>

454 454 

455 <Step title="Create workflow files">455 <Step title="Create workflow files">

456 Create GitHub Actions workflow files that integrate with your cloud provider. The examples below show complete configurations for both AWS Bedrock and Google Vertex AI:456 Create GitHub Actions workflow files that integrate with your cloud provider. The examples below show complete configurations for both Amazon Bedrock and Google Vertex AI:

457 457 

458 <AccordionGroup>458 <AccordionGroup>

459 <Accordion title="AWS Bedrock workflow">459 <Accordion title="Amazon Bedrock workflow">

460 **Prerequisites:**460 **Prerequisites:**

461 461 

462 * AWS Bedrock access enabled with Claude model permissions462 * Amazon Bedrock access enabled with Claude model permissions

463 * GitHub configured as an OIDC identity provider in AWS463 * GitHub configured as an OIDC identity provider in AWS

464 * IAM role with Bedrock permissions that trusts GitHub Actions464 * IAM role with Bedrock permissions that trusts GitHub Actions

465 465 


631| `anthropic_api_key` | Claude API key | Yes\*\* |631| `anthropic_api_key` | Claude API key | Yes\*\* |

632| `github_token` | GitHub token for API access | No |632| `github_token` | GitHub token for API access | No |

633| `trigger_phrase` | Custom trigger phrase (default: "@claude") | No |633| `trigger_phrase` | Custom trigger phrase (default: "@claude") | No |

634| `use_bedrock` | Use AWS Bedrock instead of Claude API | No |634| `use_bedrock` | Use Amazon Bedrock instead of Claude API | No |

635| `use_vertex` | Use Google Vertex AI instead of Claude API | No |635| `use_vertex` | Use Google Vertex AI instead of Claude API | No |

636 636 

637\*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\637\*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\

gitlab-ci-cd.md +10 −10

Details

22* **Automated implementation**: Turn issues into working code with a single command or mention22* **Automated implementation**: Turn issues into working code with a single command or mention

23* **Project-aware**: Claude follows your `CLAUDE.md` guidelines and existing code patterns23* **Project-aware**: Claude follows your `CLAUDE.md` guidelines and existing code patterns

24* **Simple setup**: Add one job to `.gitlab-ci.yml` and a masked CI/CD variable24* **Simple setup**: Add one job to `.gitlab-ci.yml` and a masked CI/CD variable

25* **Enterprise-ready**: Choose Claude API, AWS Bedrock, or Google Vertex AI to meet data residency and procurement needs25* **Enterprise-ready**: Choose Claude API, Amazon Bedrock, or Google Vertex AI to meet data residency and procurement needs

26* **Secure by default**: Runs in your GitLab runners with your branch protection and approvals26* **Secure by default**: Runs in your GitLab runners with your branch protection and approvals

27 27 

28## How it works28## How it works


33 33 

342. **Provider abstraction**: Use the provider that fits your environment:342. **Provider abstraction**: Use the provider that fits your environment:

35 * Claude API (SaaS)35 * Claude API (SaaS)

36 * AWS Bedrock (IAM-based access, cross-region options)36 * Amazon Bedrock (IAM-based access, cross-region options)

37 * Google Vertex AI (GCP-native, Workload Identity Federation)37 * Google Vertex AI (GCP-native, Workload Identity Federation)

38 38 

393. **Sandboxed execution**: Each interaction runs in a container with strict network and filesystem rules. Claude Code enforces workspace-scoped permissions to constrain writes. Every change flows through an MR so reviewers see the diff and approvals still apply.393. **Sandboxed execution**: Each interaction runs in a container with strict network and filesystem rules. Claude Code enforces workspace-scoped permissions to constrain writes. Every change flows through an MR so reviewers see the diff and approvals still apply.


98After adding the job and your `ANTHROPIC_API_KEY` variable, test by running the job manually from **CI/CD** → **Pipelines**, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed.98After adding the job and your `ANTHROPIC_API_KEY` variable, test by running the job manually from **CI/CD** → **Pipelines**, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed.

99 99 

100<Note>100<Note>

101 To run on AWS Bedrock or Google Vertex AI instead of the Claude API, see the [Using with AWS Bedrock & Google Vertex AI](#using-with-aws-bedrock--google-vertex-ai) section below for authentication and environment setup.101 To run on Amazon Bedrock or Google Vertex AI instead of the Claude API, see the [Using with Amazon Bedrock & Google Vertex AI](#using-with-amazon-bedrock--google-vertex-ai) section below for authentication and environment setup.

102</Note>102</Note>

103 103 

104### Manual setup (recommended for production)104### Manual setup (recommended for production)


107 107 

1081. **Configure provider access**:1081. **Configure provider access**:

109 * **Claude API**: Create and store `ANTHROPIC_API_KEY` as a masked CI/CD variable109 * **Claude API**: Create and store `ANTHROPIC_API_KEY` as a masked CI/CD variable

110 * **AWS Bedrock**: **Configure GitLab** → **AWS OIDC** and create an IAM role for Bedrock110 * **Amazon Bedrock**: **Configure GitLab** → **AWS OIDC** and create an IAM role for Bedrock

111 * **Google Vertex AI**: **Configure Workload Identity Federation for GitLab** → **GCP**111 * **Google Vertex AI**: **Configure Workload Identity Federation for GitLab** → **GCP**

112 112 

1132. **Add project credentials for GitLab API operations**:1132. **Add project credentials for GitLab API operations**:


152 152 

153Claude locates the bug, implements a fix, and updates the branch or opens a new MR.153Claude locates the bug, implements a fix, and updates the branch or opens a new MR.

154 154 

155## Using with AWS Bedrock & Google Vertex AI155## Using with Amazon Bedrock & Google Vertex AI

156 156 

157For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience.157For enterprise environments, you can run Claude Code entirely on your cloud infrastructure with the same developer experience.

158 158 

159<Tabs>159<Tabs>

160 <Tab title="AWS Bedrock">160 <Tab title="Amazon Bedrock">

161 ### Prerequisites161 ### Prerequisites

162 162 

163 Before setting up Claude Code with AWS Bedrock, you need:163 Before setting up Claude Code with Amazon Bedrock, you need:

164 164 

165 1. An AWS account with Amazon Bedrock access to the desired Claude models165 1. An AWS account with Amazon Bedrock access to the desired Claude models

166 2. GitLab configured as an OIDC identity provider in AWS IAM166 2. GitLab configured as an OIDC identity provider in AWS IAM


188 Add variables in Settings → CI/CD → Variables:188 Add variables in Settings → CI/CD → Variables:

189 189 

190 ```yaml theme={null}190 ```yaml theme={null}

191 # For AWS Bedrock:191 # For Amazon Bedrock:

192 - AWS_ROLE_TO_ASSUME192 - AWS_ROLE_TO_ASSUME

193 - AWS_REGION193 - AWS_REGION

194 ```194 ```

195 195 

196 Use the AWS Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime.196 Use the Amazon Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime.

197 </Tab>197 </Tab>

198 198 

199 <Tab title="Google Vertex AI">199 <Tab title="Google Vertex AI">


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

272```272```

273 273 

274### AWS Bedrock job example (OIDC)274### Amazon Bedrock job example (OIDC)

275 275 

276**Prerequisites:**276**Prerequisites:**

277 277 

glossary.md +307 −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# Glossary

6 

7> Definitions for Claude Code terminology. Learn what agentic loop, compaction, CLAUDE.md, hooks, subagents, MCP, and other core concepts mean.

8 

9This glossary defines Claude Code terminology. Each entry links to the page where the concept is covered in depth. For model-level concepts like tokens, temperature, and RAG, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary).

10 

11## A

12 

13### Agent teams

14 

15Multiple independent Claude Code sessions coordinated by a team lead, with a shared task list and peer-to-peer messaging. Unlike [subagents](#subagent), which run within a single session and report only to the parent, teammates each have their own context window and you can interact with any of them directly. Agent teams are experimental and must be enabled by setting `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`.

16 

17Learn more: [Run agent teams](/en/agent-teams)

18 

19### Agentic coding

20 

21A workflow where the AI can read files, run commands, and make changes autonomously while you watch, redirect, or step away, as opposed to chat-based assistants that only respond with text you must apply yourself. Claude Code is agentic because it has [tools](#tool) that let it act, not just advise.

22 

23Learn more: [How Claude Code works](/en/how-claude-code-works)

24 

25### Agentic harness

26 

27The tools, context management, and execution environment that turn a language model into a capable coding agent. Claude Code is the harness; Claude is the model inside it. The harness supplies file access, shell execution, permission gating, memory loading, and the loop that chains actions together.

28 

29Learn more: [How Claude Code works](/en/how-claude-code-works)

30 

31### Agentic loop

32 

33The cycle Claude works through for every task: gather context, take action, verify results, and repeat until done. Each tool use returns information that informs the next step. You can interrupt the loop at any point to redirect. Most extension points, including [hooks](#hook), [skills](#skill), and [MCP](#mcp-model-context-protocol), plug into specific phases of this loop.

34 

35Learn more: [How Claude Code works](/en/how-claude-code-works#the-agentic-loop)

36 

37### Auto memory

38 

39Notes Claude writes for itself based on your corrections and preferences, stored per git repository under `~/.claude/projects/`. All worktrees of the same repository share one auto memory directory. The first 200 lines or 25 KB of the `MEMORY.md` index loads at the start of every session. Auto memory is the Claude-written counterpart to [CLAUDE.md](#claude-md), which you write.

40 

41Learn more: [Auto memory](/en/memory#auto-memory)

42 

43### Auto mode

44 

45A [permission mode](#permission-mode) where a separate classifier model reviews each action in the background instead of showing you approval prompts. The classifier blocks scope escalation, untrusted infrastructure, and [prompt injection](#prompt-injection). It never sees tool results, so injected instructions cannot influence its decisions. Auto mode is a research preview available on Max, Team, Enterprise, and API plans.

46 

47Learn more: [Eliminate prompts with auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode)

48 

49## B

50 

51### Bare mode

52 

53A startup flag, `--bare`, that skips auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Only flags you pass explicitly take effect. Recommended for CI and scripted calls where you need identical behavior across machines regardless of local configuration.

54 

55Learn more: [Start faster with bare mode](/en/headless#start-faster-with-bare-mode)

56 

57### Bundled skills

58 

59Prompt-based playbooks included with Claude Code, such as `/batch`, `/simplify`, `/debug`, and `/loop`. Unlike built-in commands, which execute fixed logic, bundled skills give Claude a detailed prompt and let it orchestrate the work, so they can spawn agents, read files, and adapt to your codebase.

60 

61Learn more: [Bundled skills](/en/skills#bundled-skills)

62 

63## C

64 

65### Channel

66 

67An [MCP server](#mcp-model-context-protocol) that pushes events into your running session so Claude can react to things that happen while you're away from the terminal. Channels can be two-way: Claude reads an inbound event and replies back through the same channel. Telegram, Discord, and iMessage are included in the research preview.

68 

69Learn more: [Channels](/en/channels)

70 

71### Checkpoint

72 

73An automatic snapshot of your code captured before each edit Claude makes. Press `Esc` twice or run `/rewind` to restore code, conversation, or both to an earlier point. Checkpoints are local to the session, separate from git, and don't track changes made through the Bash tool.

74 

75Learn more: [Checkpointing](/en/checkpointing)

76 

77### `.claude` directory

78 

79The directory where Claude Code reads project-scoped configuration: settings, hooks, skills, subagents, rules, and auto memory. A project has `.claude/` at its root; your user-level defaults are at `~/.claude/`.

80 

81Learn more: [The `.claude` directory](/en/claude-directory)

82 

83### CLAUDE.md

84 

85A markdown file of persistent instructions you write for Claude, loaded at the start of every session as a user message after the system prompt. Put project conventions, architecture notes, and "always do X" rules here. CLAUDE.md survives [compaction](#compaction) and is re-read fresh from disk afterward.

86 

87You can place CLAUDE.md at project scope in `./CLAUDE.md` or `./.claude/CLAUDE.md`, at user scope in `~/.claude/CLAUDE.md`, or as [managed policy](#managed-settings) for your organization. More specific locations take precedence.

88 

89Learn more: [CLAUDE.md files](/en/memory#claude-md-files)

90 

91### Command

92 

93A reusable instruction you invoke by typing `/name` in the prompt. Built-in commands such as `/clear`, `/model`, and `/compact` control the session. You can define your own commands as files in `.claude/commands/`, or install them from a [plugin](#plugin). [Skills](#skill) are the recommended way to package multi-step commands.

94 

95Learn more: [Commands](/en/commands) · [Skills](/en/skills)

96 

97### Compaction

98 

99Automatic summarization of your conversation when the [context window](#context-window) approaches its limit. Older tool outputs are cleared first, then the conversation is summarized. Project-root CLAUDE.md and auto memory survive compaction and reload from disk; instructions given only in conversation may be lost. Run `/compact` to trigger manually, optionally with a focus like `/compact focus on the API changes`.

100 

101Learn more: [What survives compaction](/en/context-window#what-survives-compaction) · [When context fills up](/en/how-claude-code-works#when-context-fills-up)

102 

103### Context window

104 

105The working memory for a session, holding conversation history, file contents, command outputs, CLAUDE.md, auto memory, loaded skills, and system instructions. As you work, context fills up until [compaction](#compaction) summarizes it. Run `/context` to see what's using space. For the underlying model concept, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary#context-window).

106 

107Learn more: [Explore the context window](/en/context-window)

108 

109## D

110 

111### Dispatch

112 

113A phone-initiated task router that spawns a Claude Code session in the Desktop app when you send a coding task from the Claude mobile app. Your prompt routes to the right tool automatically. Available on Pro and Max plans.

114 

115Learn more: [Sessions from Dispatch](/en/desktop#sessions-from-dispatch)

116 

117## E

118 

119### Effort level

120 

121A setting that controls how much of the adaptive-reasoning thinking budget Claude uses on each turn. Higher effort means more thinking tokens and deeper reasoning; lower effort is faster and cheaper. Effort is supported on Opus 4.7, Opus 4.6, and Sonnet 4.6.

122 

123Learn more: [Adjust effort level](/en/model-config#adjust-effort-level)

124 

125### Extended thinking

126 

127Visible step-by-step reasoning the model performs before responding. You can cap thinking tokens with `MAX_THINKING_TOKENS` or adjust the [effort level](#effort-level). Thinking appears in gray italic text in the terminal.

128 

129Learn more: [Use extended thinking](/en/model-config#extended-thinking)

130 

131## H

132 

133### Hook

134 

135A user-defined handler that executes automatically at a specific point in Claude Code's lifecycle, such as before a tool runs, after a file edit, or at session start. Handlers can be a shell command, HTTP endpoint, MCP tool, LLM prompt, or subagent. Hooks are deterministic: they fire at fixed lifecycle points rather than at the model's discretion.

136 

137A hook configuration has three levels:

138 

139* **Hook event**: the lifecycle point

140* **Matcher**: filters which events fire it

141* **Hook handler**: what runs

142 

143Learn more: [Get started with hooks](/en/hooks-guide) · [Hooks reference](/en/hooks)

144 

145## M

146 

147### Managed settings

148 

149A settings file enforced org-wide by IT or DevOps, placed at an OS-level path outside `~/.claude`. Users cannot override or exclude managed settings. Use this for security policies, compliance requirements, or standardized tooling across a fleet.

150 

151Learn more: [Server-managed settings](/en/server-managed-settings)

152 

153### MCP (Model Context Protocol)

154 

155An open standard for connecting AI tools to external data sources and services. MCP servers give Claude new tools for Slack, Jira, databases, browsers, and hundreds of other integrations. You connect servers via `/mcp` or by adding them to `.mcp.json`. For the protocol itself, see the [platform glossary](https://platform.claude.com/docs/en/about-claude/glossary#mcp-model-context-protocol).

156 

157Learn more: [Model Context Protocol](/en/mcp)

158 

159### MCP Tool Search

160 

161A context-saving mechanism that defers MCP tool schemas until needed. Only tool names load at startup; Claude fetches the full schema on demand when it decides to use a specific tool. This keeps idle MCP servers from consuming much context.

162 

163Learn more: [Scale with MCP Tool Search](/en/mcp#scale-with-mcp-tool-search)

164 

165## N

166 

167### Non-interactive mode

168 

169A mode that executes a single prompt and exits without a conversational session, invoked with `-p` or `--print`. Used for CI, scripts, and piping. The [Agent SDK](/en/agent-sdk/overview) is the Python and TypeScript equivalent. Formerly called headless mode.

170 

171Learn more: [Run Claude Code programmatically](/en/headless)

172 

173## O

174 

175### Output style

176 

177A configuration that modifies Claude's system prompt to change response behavior, tone, or format. Output styles turn off the software-engineering-specific parts of the default system prompt, unlike [CLAUDE.md](#claude-md) which is delivered as a user message following the system prompt. Built-in styles include Default, Explanatory, and Learning.

178 

179Learn more: [Output styles](/en/output-styles)

180 

181## P

182 

183### Permission mode

184 

185The baseline approval behavior for the session. Cycle with `Shift+Tab` in the CLI or use the mode selector in VS Code, Desktop, and claude.ai. Available modes are `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, and `bypassPermissions`.

186 

187Learn more: [Choose a permission mode](/en/permission-modes)

188 

189### Permission rule

190 

191A settings entry that allows, asks about, or denies a tool invocation based on the tool name and argument pattern. Rules are evaluated deny→ask→allow, first match wins. Permission rules are fine-grained controls layered on top of the broader [permission mode](#permission-mode).

192 

193Learn more: [Configure permissions](/en/permissions)

194 

195### Plan mode

196 

197A [permission mode](#permission-mode) where Claude researches and proposes changes without editing your source files. It can read, search, and run exploration commands, then presents a plan for approval before touching anything. Enter plan mode with `/plan` or by pressing `Shift+Tab`.

198 

199Learn more: [Analyze before you edit with plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode)

200 

201### Plugin

202 

203A bundle of skills, hooks, subagents, and MCP servers packaged as a single installable unit. Plugin skills are namespaced as `plugin-name:skill-name` so multiple plugins coexist. Distribute plugins across teams via a [marketplace](/en/plugin-marketplaces).

204 

205Learn more: [Plugins](/en/plugins)

206 

207### Project trust

208 

209A one-time dialog accepting a directory before Claude Code loads its configuration. Trust gates auto-installation of marketplace plugins and execution of project-defined hooks. Trusting a directory means its `.claude/settings.json`, `.mcp.json`, and other config files take effect.

210 

211Learn more: [The `.claude` directory](/en/claude-directory)

212 

213### Prompt injection

214 

215Hostile instructions embedded in a file, web page, or tool result that attempt to redirect Claude toward actions you never asked for. Claude Code's defenses include the permission system, command blocklists, and trust verification. [Auto mode](#auto-mode) adds a server-side probe that scans tool results for suspicious content and a classifier that never sees tool results, so injected text cannot influence its approval decisions.

216 

217Learn more: [Protect against prompt injection](/en/security#protect-against-prompt-injection)

218 

219## R

220 

221### Remote Control

222 

223A way to continue a local Claude Code session from your phone or browser via claude.ai. Your code stays on your machine; only the UI is remote. Different from Claude Code on the web, which runs in a cloud sandbox.

224 

225Learn more: [Remote Control](/en/remote-control)

226 

227### Rules

228 

229Modular instruction files in `.claude/rules/` that load alongside CLAUDE.md. A rule can be path-scoped with YAML `paths:` frontmatter so it only loads when Claude reads a matching file, keeping context lean until it's relevant.

230 

231Learn more: [Organize rules with `.claude/rules/`](/en/memory#organize-rules-with-claude/rules/)

232 

233## S

234 

235### Sandboxing

236 

237OS-level filesystem and network isolation for the Bash tool. Commands run inside a boundary you define upfront, so Claude can work freely within it without per-command approval prompts. Sandboxing is a separate layer from [permission rules](#permission-rule).

238 

239Learn more: [Sandboxing](/en/sandboxing)

240 

241### Session

242 

243A conversation tied to your current directory, with its own independent [context window](#context-window). Sessions can be resumed with `claude -c`, forked with `--fork-session` to preserve history under a new session ID, or run in parallel across terminals. Running `/clear` starts a new session; the previous one stays stored and is available via `/resume`. Each session's transcript is stored under `~/.claude/projects/`.

244 

245Learn more: [Work with sessions](/en/how-claude-code-works#work-with-sessions)

246 

247### Settings layers

248 

249The hierarchy Claude Code reads configuration from, in precedence order from highest to lowest: [managed policy](#managed-settings), command-line arguments, local settings at `.claude/settings.local.json`, project settings at `.claude/settings.json`, then user settings at `~/.claude/settings.json`. Arrays merge across layers; scalars at a higher layer override lower ones.

250 

251Learn more: [Settings files](/en/settings#settings-files)

252 

253### Skill

254 

255A `SKILL.md` file containing instructions, knowledge, or a workflow that Claude adds to its toolkit. Claude loads a skill automatically when relevant, or you invoke it directly with `/skill-name`. Skills follow the Agent Skills open standard; Claude Code extends it with invocation control and subagent execution.

256 

257Skills are the recommended successor to custom commands. A file at `.claude/commands/deploy.md` and one at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way; existing command files continue to work.

258 

259Learn more: [Extend Claude with skills](/en/skills)

260 

261### Subagent

262 

263A specialized AI assistant that runs in its own context window with a custom system prompt, specific tool access, and independent permissions. It works on a delegated task and returns a summary to the main conversation. Use subagents to keep large explorations out of your primary context or to run parallel research. Different from [agent teams](#agent-teams), where each agent is a full independent session you can talk to directly.

264 

265Built-in subagents include Explore, Plan, and general-purpose.

266 

267Learn more: [Create custom subagents](/en/sub-agents)

268 

269### Surface

270 

271Any place you access Claude Code: the CLI, VS Code, JetBrains, Desktop, or claude.ai. All surfaces share the same engine, so your CLAUDE.md, settings, and skills work the same way across them. Slack and the Chrome extension are integrations that connect to a surface rather than surfaces themselves.

272 

273Learn more: [Platforms and integrations](/en/platforms)

274 

275## T

276 

277### Teleport

278 

279A command, `/teleport`, that pulls a cloud Claude Code session into your local terminal. Claude fetches the branch, loads the conversation history, and resumes from the web session's last state. The reverse direction is `--remote`, which sends a local task to run on the web.

280 

281Learn more: [From web to terminal](/en/claude-code-on-the-web#from-web-to-terminal)

282 

283### Tool

284 

285An action Claude can take: read a file, edit code, run a shell command, search the web, spawn a subagent. Tools are what make Claude Code agentic. Without them, Claude can only respond with text. Each tool use returns a result that informs Claude's next decision in the [agentic loop](#agentic-loop).

286 

287Learn more: [Tools available to Claude](/en/tools-reference)

288 

289## W

290 

291### Worktree isolation

292 

293An isolation mode that runs Claude in a separate git worktree under `.claude/worktrees/`, enabled with the `-w` flag or `isolation: worktree` in subagent config. Changes stay on a separate branch in a separate directory, so parallel agents don't overwrite each other's files.

294 

295Learn more: [Run parallel sessions with git worktrees](/en/worktrees)

296 

297***

298 

299## Deprecated and renamed terms

300 

301These terms appear in older docs, blog posts, and community content. Use the current name when searching this site.

302 

303| Old term | Now called | Notes |

304| --------------- | --------------------------------------------- | ------------------------------------ |

305| Headless mode | [Non-interactive mode](#non-interactive-mode) | Same `-p` flag, same behavior |

306| Custom commands | [Skills](#skill) | `.claude/commands/` files still work |

307| Slash commands | Commands | "Slash" dropped from product copy |

Details

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

9 9 

10 10<ContactSalesCard surface="vertex" />

11<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="vertex" />} />

12 11 

13## Prerequisites12## Prerequisites

14 13 


48 47 

49## Region configuration48## Region configuration

50 49 

51Claude 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.50Claude Code supports Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai), multi-region, and regional endpoints. Set `CLOUD_ML_REGION` to `global`, a multi-region location such as `eu` or `us`, or a specific region such as `us-east5`. Claude Code selects the correct Vertex AI hostname for each form, including the `aiplatform.eu.rep.googleapis.com` and `aiplatform.us.rep.googleapis.com` hosts for multi-region locations.

52 51 

53<Note>52<Note>

54 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.53 Vertex AI may not support the Claude Code default models on every endpoint type. Model availability varies across [specific regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models), multi-region locations, and [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 location or specify a supported model.

55</Note>54</Note>

56 55 

57## Set up manually56## Set up manually


85 84 

86For more information, see [Google Cloud authentication documentation](https://cloud.google.com/docs/authentication).85For more information, see [Google Cloud authentication documentation](https://cloud.google.com/docs/authentication).

87 86 

87Claude Code v2.1.121 or later supports [X.509 certificate-based Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation-with-x509-certificates) through the same Application Default Credentials chain. Set `GOOGLE_APPLICATION_CREDENTIALS` to the path of your credential configuration file.

88 

88<Note>89<Note>

89 When authenticating, Claude Code will automatically use the project ID from the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable. To override this, set one of these environment variables: `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or `GOOGLE_APPLICATION_CREDENTIALS`.90 Claude Code uses `ANTHROPIC_VERTEX_PROJECT_ID` as the project ID for Vertex AI requests. The `GCLOUD_PROJECT` and `GOOGLE_CLOUD_PROJECT` environment variables and the credential file referenced by `GOOGLE_APPLICATION_CREDENTIALS` take precedence over it. If none of these are set, the project ID is resolved from your `gcloud` configuration or the attached service account.

90</Note>91</Note>

91 92 

93#### Advanced credential configuration

94 

95Claude Code supports automatic credential refresh for GCP through the `gcpAuthRefresh` setting. When Claude Code detects that your GCP credentials are expired or cannot be loaded, it runs the configured command to obtain new credentials before retrying the request.

96 

97```json theme={null}

98{

99 "gcpAuthRefresh": "gcloud auth application-default login",

100 "env": {

101 "ANTHROPIC_VERTEX_PROJECT_ID": "your-project-id"

102 }

103}

104```

105 

106The command's output is displayed to the user, but interactive input isn't supported. This works well for browser-based authentication flows where the CLI shows a URL and you complete authentication in the browser. The refresh command times out after three minutes if authentication does not complete. If you set `gcpAuthRefresh` in project settings such as `.claude/settings.json`, the command runs only after you accept the workspace trust prompt.

107 

92### 4. Configure Claude Code108### 4. Configure Claude Code

93 109 

94Set the following environment variables:110Set the following environment variables:


105# Optional: Disable prompt caching if needed121# Optional: Disable prompt caching if needed

106export DISABLE_PROMPT_CACHING=1122export DISABLE_PROMPT_CACHING=1

107 123 

124# Optional: Request 1-hour prompt cache TTL instead of the 5-minute default

125export ENABLE_PROMPT_CACHING_1H=1

126 

108# When CLOUD_ML_REGION=global, override region for models that don't support global endpoints127# When CLOUD_ML_REGION=global, override region for models that don't support global endpoints

109export VERTEX_REGION_CLAUDE_HAIKU_4_5=us-east5128export VERTEX_REGION_CLAUDE_HAIKU_4_5=us-east5

110export VERTEX_REGION_CLAUDE_4_6_SONNET=europe-west1129export VERTEX_REGION_CLAUDE_4_6_SONNET=europe-west1


112 131 

113Most model versions have a corresponding `VERTEX_REGION_CLAUDE_*` variable. See the [Environment variables reference](/en/env-vars) for the full list. Check [Vertex Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) to determine which models support global endpoints versus regional only.132Most model versions have a corresponding `VERTEX_REGION_CLAUDE_*` variable. See the [Environment variables reference](/en/env-vars) for the full list. Check [Vertex Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) to determine which models support global endpoints versus regional only.

114 133 

115[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.134[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) is enabled automatically. To disable it, set `DISABLE_PROMPT_CACHING=1`. To request a 1-hour cache TTL instead of the 5-minute default, set `ENABLE_PROMPT_CACHING_1H=1`; cache writes with a 1-hour TTL are billed at a higher rate. 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.

135 

136[MCP tool search](/en/mcp#scale-with-mcp-tool-search) is disabled by default on Vertex AI because the endpoint does not accept the required beta header. All MCP tool definitions load upfront instead. To opt in, set `ENABLE_TOOL_SEARCH=true`.

116 137 

117### 5. Pin model versions138### 5. Pin model versions

118 139 


120 Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to the latest version, which may not yet be enabled in your Vertex AI project when Anthropic releases an update. Claude Code [falls back](#startup-model-checks) to the previous version at startup when the latest is unavailable, but pinning lets you control when your users move to a new model.141 Pin specific model versions when deploying to multiple users. Without pinning, model aliases such as `sonnet` and `opus` resolve to the latest version, which may not yet be enabled in your Vertex AI project when Anthropic releases an update. Claude Code [falls back](#startup-model-checks) to the previous version at startup when the latest is unavailable, but pinning lets you control when your users move to a new model.

121</Warning>142</Warning>

122 143 

123Set these environment variables to specific Vertex AI model IDs:144Set these environment variables to specific Vertex AI model IDs.

145 

146Without `ANTHROPIC_DEFAULT_OPUS_MODEL`, the `opus` alias on Vertex resolves to Opus 4.6. Set it to the Opus 4.7 ID to use the latest model:

124 147 

125```bash theme={null}148```bash theme={null}

126export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'149export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'

127export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'150export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

128export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'151export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

129```152```


140To customize models further:163To customize models further:

141 164 

142```bash theme={null}165```bash theme={null}

143export ANTHROPIC_MODEL='claude-opus-4-6'166export ANTHROPIC_MODEL='claude-opus-4-7'

144export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'167export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

145```168```

146 169 


170 193 

171## 1M token context window194## 1M token context window

172 195 

173Claude Opus 4.6, Sonnet 4.6, Sonnet 4.5, and Sonnet 4 support the [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) on Vertex AI. Claude Code automatically enables the extended context window when you select a 1M model variant.196Claude Opus 4.7, Opus 4.6, 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. Claude Code automatically enables the extended context window when you select a 1M model variant.

174 197 

175To enable the 1M context window for your pinned model, append `[1m]` to the model ID. See [Pin models for third-party deployments](/en/model-config#pin-models-for-third-party-deployments) for details.198The [setup wizard](#sign-in-with-vertex-ai) offers a 1M context option when it pins models. To enable it for a manually pinned model instead, append `[1m]` to the model ID. See [Pin models for third-party deployments](/en/model-config#pin-models-for-third-party-deployments) for details.

176 199 

177## Troubleshooting200## Troubleshooting

178 201 

202If you encounter "Could not load the default credentials" errors:

203 

204* Run `gcloud auth application-default login` to set up Application Default Credentials

205* Set `GOOGLE_APPLICATION_CREDENTIALS` to a service account key file path

206* See [Configure GCP credentials](#3-configure-gcp-credentials) for all options

207 

179If you encounter quota issues:208If you encounter quota issues:

180 209 

181* Check current quotas or request quota increase through [Cloud Console](https://cloud.google.com/docs/quotas/view-manage)210* Check current quotas or request quota increase through [Cloud Console](https://cloud.google.com/docs/quotas/view-manage)


183If you encounter "model not found" 404 errors:212If you encounter "model not found" 404 errors:

184 213 

185* Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)214* Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)

186* Verify you have access to the specified region215* Verify the model is available in the location you specified. Some models are offered only on `global` or multi-region locations such as `eu` and `us`, not in specific regions

187* If using `CLOUD_ML_REGION=global`, check that your models support global endpoints in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) under "Supported features". For models that don't support global endpoints, either:216* If using `CLOUD_ML_REGION=global`, check that your models support global endpoints in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden) under "Supported features". For models that don't support global endpoints, either:

188 * Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_DEFAULT_HAIKU_MODEL`, or217 * Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_DEFAULT_HAIKU_MODEL`, or

189 * Set a regional endpoint using `VERTEX_REGION_<MODEL_NAME>` environment variables218 * Set a region or multi-region location using `VERTEX_REGION_<MODEL_NAME>` environment variables

190 219 

191If you encounter 429 errors:220If you encounter 429 errors:

192 221 

headless.md +53 −4

Details

54| Settings | `--settings <file-or-json>` |54| Settings | `--settings <file-or-json>` |

55| MCP servers | `--mcp-config <file-or-json>` |55| MCP servers | `--mcp-config <file-or-json>` |

56| Custom agents | `--agents <json>` |56| Custom agents | `--agents <json>` |

57| A plugin directory | `--plugin-dir <path>` |57| A plugin | `--plugin-dir <path>`, `--plugin-url <url>` |

58 58 

59Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Bedrock, Vertex, and Foundry use their usual provider credentials.59Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Bedrock, Vertex, and Foundry use their usual provider credentials.

60 60 


66 66 

67These examples highlight common CLI patterns. For CI and other scripted calls, add [`--bare`](#start-faster-with-bare-mode) so they don't pick up whatever happens to be configured locally.67These examples highlight common CLI patterns. For CI and other scripted calls, add [`--bare`](#start-faster-with-bare-mode) so they don't pick up whatever happens to be configured locally.

68 68 

69### Pipe data through Claude

70 

71Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool.

72 

73This example pipes a build log into Claude and writes the explanation to a file:

74 

75```bash theme={null}

76cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt

77```

78 

79With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](/en/costs).

80 

81<Note>

82 As of Claude Code v2.1.128, piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it.

83</Note>

84 

85### Add Claude to a build script

86 

87You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer.

88 

89This `package.json` script pipes the diff against `main` into Claude and asks it to report typos. Piping the diff means Claude doesn't need Bash permission to read it, and the escaped double quotes keep the script portable to Windows:

90 

91```json theme={null}

92{

93 "scripts": {

94 "lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""

95 }

96}

97```

98 

69### Get structured output99### Get structured output

70 100 

71Use `--output-format` to control how responses are returned:101Use `--output-format` to control how responses are returned:


123When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. You can use this to surface retry progress or implement custom backoff logic.153When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. You can use this to surface retry progress or implement custom backoff logic.

124 154 

125| Field | Type | Description |155| Field | Type | Description |

126| ---------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |156| ---------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

127| `type` | `"system"` | message type |157| `type` | `"system"` | message type |

128| `subtype` | `"api_retry"` | identifies this as a retry event |158| `subtype` | `"api_retry"` | identifies this as a retry event |

129| `attempt` | integer | current attempt number, starting at 1 |159| `attempt` | integer | current attempt number, starting at 1 |

130| `max_retries` | integer | total retries permitted |160| `max_retries` | integer | total retries permitted |

131| `retry_delay_ms` | integer | milliseconds until the next attempt |161| `retry_delay_ms` | integer | milliseconds until the next attempt |

132| `error_status` | integer or null | HTTP status code, or `null` for connection errors with no HTTP response |162| `error_status` | integer or null | HTTP status code, or `null` for connection errors with no HTTP response |

133| `error` | string | error category: `authentication_failed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |163| `error` | string | error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |

164| `uuid` | string | unique event identifier |

165| `session_id` | string | session the event belongs to |

166 

167The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, in which case `plugin_install` events precede it. Use the plugin fields to fail CI when a plugin did not load:

168 

169| Field | Type | Description |

170| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

171| `plugins` | array | plugins that loaded successfully, each with `name` and `path` |

172| `plugin_errors` | array | plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors |

173 

174When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](/en/env-vars) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI.

175 

176| Field | Type | Description |

177| ------------ | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |

178| `type` | `"system"` | message type |

179| `subtype` | `"plugin_install"` | identifies this as a plugin install event |

180| `status` | `"started"`, `"installed"`, `"failed"`, or `"completed"` | `started` and `completed` bracket the overall install; `installed` and `failed` report individual marketplaces |

181| `name` | string, optional | marketplace name, present on `installed` and `failed` |

182| `error` | string, optional | failure message, present on `failed` |

134| `uuid` | string | unique event identifier |183| `uuid` | string | unique event identifier |

135| `session_id` | string | session the event belongs to |184| `session_id` | string | session the event belongs to |

136 185 


145 --allowedTools "Bash,Read,Edit"194 --allowedTools "Bash,Read,Edit"

146```195```

147 196 

148To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](/en/permission-modes). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted:197To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](/en/permission-modes). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](/en/permissions#read-only-commands), which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted:

149 198 

150```bash theme={null}199```bash theme={null}

151claude -p "Apply the lint fixes" --permission-mode acceptEdits200claude -p "Apply the lint fixes" --permission-mode acceptEdits

hooks.md +349 −75

Details

18 18 

19<div style={{maxWidth: "500px", margin: "0 auto"}}>19<div style={{maxWidth: "500px", margin: "0 auto"}}>

20 <Frame>20 <Frame>

21 <img src="https://mintcdn.com/claude-code/UMJp-WgTWngzO609/images/hooks-lifecycle.svg?fit=max&auto=format&n=UMJp-WgTWngzO609&q=85&s=3f4de67df216c87dc313943b32c15f62" alt="Hook lifecycle diagram showing SessionStart, then a per-turn loop containing UserPromptSubmit, the nested agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCreated, TaskCompleted), and Stop or StopFailure, followed by TeammateIdle, PreCompact, PostCompact, and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution, PermissionDenied as a side branch from PermissionRequest for auto-mode denials, and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, and FileChanged as standalone async events" width="520" height="1155" data-path="images/hooks-lifecycle.svg" />21 <img src="https://mintcdn.com/claude-code/ZIW26Z9pnpsXLhbS/images/hooks-lifecycle.svg?fit=max&auto=format&n=ZIW26Z9pnpsXLhbS&q=85&s=ee23691324deb6501df09bfdae560b64" alt="Hook lifecycle diagram showing optional Setup feeding into SessionStart, then a per-turn loop containing UserPromptSubmit, UserPromptExpansion for slash commands, the nested agentic loop (PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, PostToolBatch, SubagentStart/Stop, TaskCreated, TaskCompleted), and Stop or StopFailure, followed by TeammateIdle, PreCompact, PostCompact, and SessionEnd, with Elicitation and ElicitationResult nested inside MCP tool execution, PermissionDenied as a side branch from PermissionRequest for auto-mode denials, and WorktreeCreate, WorktreeRemove, Notification, ConfigChange, InstructionsLoaded, CwdChanged, and FileChanged as standalone async events" width="520" height="1228" data-path="images/hooks-lifecycle.svg" />

22 </Frame>22 </Frame>

23</div>23</div>

24 24 

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

26 26 

27| Event | When it fires |27| Event | When it fires |

28| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |28| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

29| `SessionStart` | When a session begins or resumes |29| `SessionStart` | When a session begins or resumes |

30| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |

30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |31| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

32| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

31| `PreToolUse` | Before a tool call executes. Can block it |33| `PreToolUse` | Before a tool call executes. Can block it |

32| `PermissionRequest` | When a permission dialog appears |34| `PermissionRequest` | When a permission dialog appears |

33| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |35| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

34| `PostToolUse` | After a tool call succeeds |36| `PostToolUse` | After a tool call succeeds |

35| `PostToolUseFailure` | After a tool call fails |37| `PostToolUseFailure` | After a tool call fails |

38| `PostToolBatch` | After a full batch of parallel tool calls resolves, before the next model call |

36| `Notification` | When Claude Code sends a notification |39| `Notification` | When Claude Code sends a notification |

37| `SubagentStart` | When a subagent is spawned |40| `SubagentStart` | When a subagent is spawned |

38| `SubagentStop` | When a subagent finishes |41| `SubagentStop` | When a subagent finishes |


55 58 

56### How a hook resolves59### How a hook resolves

57 60 

58To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to commands starting with `rm`, so `block-rm.sh` only spawns when both filters match:61To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The `matcher` narrows to Bash tool calls and the `if` condition narrows further to Bash subcommands matching `rm *`, so `block-rm.sh` only spawns when both filters match:

59 62 

60```json theme={null}63```json theme={null}

61{64{


116 </Step>119 </Step>

117 120 

118 <Step title="If condition checks">121 <Step title="If condition checks">

119 The `if` condition `"Bash(rm *)"` matches because the command starts with `rm`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.122 The `if` condition `"Bash(rm *)"` matches because `rm -rf /tmp/build` is a subcommand matching `rm *`, so this handler spawns. If the command had been `npm test`, the `if` check would fail and `block-rm.sh` would never run, avoiding the process spawn overhead. The `if` field is optional; without it, every handler in the matched group runs.

120 </Step>123 </Step>

121 124 

122 <Step title="Hook handler runs">125 <Step title="Hook handler runs">


153See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.156See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.

154 157 

155<Note>158<Note>

156 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, prompt, or agent that runs. "Hook" on its own refers to the general feature.159 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, HTTP endpoint, MCP tool, prompt, or agent that runs. "Hook" on its own refers to the general feature.

157</Note>160</Note>

158 161 

159### Hook locations162### Hook locations


186Each event type matches on a different field:189Each event type matches on a different field:

187 190 

188| Event | What the matcher filters | Example matcher values |191| Event | What the matcher filters | Example matcher values |

189| :------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |192| :------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |

190| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |193| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

191| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |194| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

195| `Setup` | which CLI flag triggered setup | `init`, `maintenance` |

192| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |196| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

193| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |197| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response` |

194| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |198| `SubagentStart` | agent type | `general-purpose`, `Explore`, `Plan`, or custom agent names |

195| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |199| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |

196| `SubagentStop` | agent type | same values as `SubagentStart` |200| `SubagentStop` | agent type | same values as `SubagentStart` |

197| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |201| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

198| `CwdChanged` | no matcher support | always fires on every directory change |202| `CwdChanged` | no matcher support | always fires on every directory change |

199| `FileChanged` | literal filenames to watch (see [FileChanged](#filechanged)) | `.envrc\|.env` |203| `FileChanged` | literal filenames to watch (see [FileChanged](#filechanged)) | `.envrc\|.env` |

200| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |204| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |

201| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |205| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |

206| `UserPromptExpansion` | command name | your skill or command names |

202| `Elicitation` | MCP server name | your configured MCP server names |207| `Elicitation` | MCP server name | your configured MCP server names |

203| `ElicitationResult` | MCP server name | same values as `Elicitation` |208| `ElicitationResult` | MCP server name | same values as `Elicitation` |

204| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |209| `UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |

205 210 

206The 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.211The 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.

207 212 


225}230}

226```231```

227 232 

228`UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.233`UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, and `CwdChanged` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.

229 234 

230For tool events, you can filter more narrowly by setting the [`if` field](#common-fields) on individual hook handlers. `if` uses [permission rule syntax](/en/permissions) to match against the tool name and arguments together, so `"Bash(git *)"` runs only for `git` commands and `"Edit(*.ts)"` runs only for TypeScript files.235For tool events, you can filter more narrowly by setting the [`if` field](#common-fields) on individual hook handlers. `if` uses [permission rule syntax](/en/permissions) to match against the tool name and arguments together, so `"Bash(git *)"` runs when any subcommand of the Bash input matches `git *` and `"Edit(*.ts)"` runs only for TypeScript files.

231 236 

232#### Match MCP tools237#### Match MCP tools

233 238 


275 280 

276### Hook handler fields281### Hook handler fields

277 282 

278Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, LLM prompt, or agent that runs when the matcher matches. There are four types:283Each object in the inner `hooks` array is a hook handler: the shell command, HTTP endpoint, MCP tool, LLM prompt, or agent that runs when the matcher matches. There are five types:

279 284 

280* **[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.285* **[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.

281* **[HTTP hooks](#http-hook-fields)** (`type: "http"`): send the event's JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same [JSON output format](#json-output) as command hooks.286* **[HTTP hooks](#http-hook-fields)** (`type: "http"`): send the event's JSON input as an HTTP POST request to a URL. The endpoint communicates results back through the response body using the same [JSON output format](#json-output) as command hooks.

287* **[MCP tool hooks](#mcp-tool-hook-fields)** (`type: "mcp_tool"`): call a tool on an already-connected [MCP server](/en/mcp). The tool's text output is treated like command-hook stdout.

282* **[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).288* **[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).

283* **[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).289* **[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. Agent hooks are experimental and may change. See [Agent-based hooks](#agent-based-hooks).

284 290 

285#### Common fields291#### Common fields

286 292 

287These fields apply to all hook types:293These fields apply to all hook types:

288 294 

289| Field | Required | Description |295| Field | Required | Description |

290| :-------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |296| :-------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

291| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |297| `type` | yes | `"command"`, `"http"`, `"mcp_tool"`, `"prompt"`, or `"agent"` |

292| `if` | no | Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](/en/permissions) |298| `if` | no | Permission rule syntax to filter when this hook runs, such as `"Bash(git *)"` or `"Edit(*.ts)"`. The hook only spawns if the tool call matches the pattern, or if a Bash command is too complex to parse. Only evaluated on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. On other events, a hook with `if` set never runs. Uses the same syntax as [permission rules](/en/permissions) |

293| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |299| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |

294| `statusMessage` | no | Custom spinner message displayed while the hook runs |300| `statusMessage` | no | Custom spinner message displayed while the hook runs |

295| `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) |301| `once` | no | If `true`, runs once per session then is removed. Only honored for hooks declared in [skill frontmatter](#hooks-in-skills-and-agents); ignored in settings files and agent frontmatter |

302 

303The `if` field holds exactly one permission rule. There is no `&&`, `||`, or list syntax for combining rules; to apply multiple conditions, define a separate hook handler for each. For Bash, the rule is matched against each subcommand of the tool input after leading `VAR=value` assignments are stripped, so `if: "Bash(git push *)"` matches both `FOO=bar git push` and `npm test && git push`. The hook runs if any subcommand matches, and always runs when the command is too complex to parse.

296 304 

297#### Command hook fields305#### Command hook fields

298 306 


344}352}

345```353```

346 354 

355#### MCP tool hook fields

356 

357In addition to the [common fields](#common-fields), MCP tool hooks accept these fields:

358 

359| Field | Required | Description |

360| :------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

361| `server` | yes | Name of a configured MCP server. The server must already be connected; the hook never triggers an OAuth or connection flow |

362| `tool` | yes | Name of the tool to call on that server |

363| `input` | no | Arguments passed to the tool. String values support `${path}` substitution from the hook's [JSON input](#hook-input-and-output), such as `"${tool_input.file_path}"` |

364 

365The tool's text content is treated like command-hook stdout: if it parses as valid [JSON output](#json-output) it is processed as a decision, otherwise it is shown as plain text. If the named server is not connected, or the tool returns `isError: true`, the hook produces a non-blocking error and execution continues.

366 

367MCP tool hooks are available on every hook event once Claude Code has connected to your MCP servers. `SessionStart` and `Setup` typically fire before servers finish connecting, so hooks on those events should expect the "not connected" error on first run.

368 

369This example calls the `security_scan` tool on the `my_server` MCP server after each `Write` or `Edit`, passing the edited file's path:

370 

371```json theme={null}

372{

373 "hooks": {

374 "PostToolUse": [

375 {

376 "matcher": "Write|Edit",

377 "hooks": [

378 {

379 "type": "mcp_tool",

380 "server": "my_server",

381 "tool": "security_scan",

382 "input": { "file_path": "${tool_input.file_path}" }

383 }

384 ]

385 }

386 ]

387 }

388}

389```

390 

347#### Prompt and agent hook fields391#### Prompt and agent hook fields

348 392 

349In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:393In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:


444 488 

445Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook's command, prompt, or URL.489Type `/hooks` in Claude Code to open a read-only browser for your configured hooks. The menu shows every hook event with a count of configured hooks, lets you drill into matchers, and shows the full details of each hook handler. Use it to verify configuration, check which settings file a hook came from, or inspect a hook's command, prompt, or URL.

446 490 

447The menu displays all four hook types: `command`, `prompt`, `agent`, and `http`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:491The menu displays all five hook types: `command`, `prompt`, `agent`, `http`, and `mcp_tool`. Each hook is labeled with a `[type]` prefix and a source indicating where it was defined:

448 492 

449* `User`: from `~/.claude/settings.json`493* `User`: from `~/.claude/settings.json`

450* `Project`: from `.claude/settings.json`494* `Project`: from `.claude/settings.json`


474Hook events receive these fields as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.518Hook events receive these fields as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section. For command hooks, this JSON arrives via stdin. For HTTP hooks, it arrives as the POST request body.

475 519 

476| Field | Description |520| Field | Description |

477| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |521| :---------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

478| `session_id` | Current session identifier |522| `session_id` | Current session identifier |

479| `transcript_path` | Path to conversation JSON |523| `transcript_path` | Path to conversation JSON |

480| `cwd` | Current working directory when the hook is invoked |524| `cwd` | Current working directory when the hook is invoked |

481| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event's JSON example below to check |525| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, `"dontAsk"`, or `"bypassPermissions"`. Not all events receive this field: see each event's JSON example below to check |

526| `effort` | Object with a `level` field holding the active [effort level](/en/model-config#adjust-effort-level) for the turn: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. If the requested effort exceeds what the current model supports, this is the downgraded level the model actually used, not the level you requested. The object matches the [status line](/en/statusline#available-data) `effort` field. Present for events that fire within a tool-use context, such as `PreToolUse`, `PostToolUse`, `Stop`, and `SubagentStop`, when the current model supports the effort parameter. The level is also available to hook commands and the Bash tool as the `$CLAUDE_EFFORT` environment variable. |

482| `hook_event_name` | Name of the event that fired |527| `hook_event_name` | Name of the event that fired |

483 528 

484When running with `--agent` or inside a subagent, two additional fields are included:529When running with `--agent` or inside a subagent, two additional fields are included:


510 555 

511The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.556The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.

512 557 

513**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 written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.558**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 written to the debug log but not shown in the transcript. The exceptions are `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart`, where stdout is added as context that Claude can see and act on.

514 559 

515**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.560**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.

516 561 


540Exit 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.585Exit 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.

541 586 

542| Hook event | Can block? | What happens on exit 2 |587| Hook event | Can block? | What happens on exit 2 |

543| :------------------- | :--------- | :----------------------------------------------------------------------------------------------------------------------------------- |588| :-------------------- | :--------- | :----------------------------------------------------------------------------------------------------------------------------------- |

544| `PreToolUse` | Yes | Blocks the tool call |589| `PreToolUse` | Yes | Blocks the tool call |

545| `PermissionRequest` | Yes | Denies the permission |590| `PermissionRequest` | Yes | Denies the permission |

546| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |591| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |

592| `UserPromptExpansion` | Yes | Blocks the expansion |

547| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |593| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |

548| `SubagentStop` | Yes | Prevents the subagent from stopping |594| `SubagentStop` | Yes | Prevents the subagent from stopping |

549| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |595| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |


553| `StopFailure` | No | Output and exit code are ignored |599| `StopFailure` | No | Output and exit code are ignored |

554| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |600| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |

555| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |601| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |

602| `PostToolBatch` | Yes | Stops the agentic loop before the next model call |

556| `PermissionDenied` | No | Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry |603| `PermissionDenied` | No | Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry |

557| `Notification` | No | Shows stderr to user only |604| `Notification` | No | Shows stderr to user only |

558| `SubagentStart` | No | Shows stderr to user only |605| `SubagentStart` | No | Shows stderr to user only |

559| `SessionStart` | No | Shows stderr to user only |606| `SessionStart` | No | Shows stderr to user only |

607| `Setup` | No | Shows stderr to user only |

560| `SessionEnd` | No | Shows stderr to user only |608| `SessionEnd` | No | Shows stderr to user only |

561| `CwdChanged` | No | Shows stderr to user only |609| `CwdChanged` | No | Shows stderr to user only |

562| `FileChanged` | No | Shows stderr to user only |610| `FileChanged` | No | Shows stderr to user only |


611{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }659{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }

612```660```

613 661 

662#### Add context for Claude

663 

664The `additionalContext` field passes a string from your hook into Claude's context window. Claude Code wraps the string in a system reminder and inserts it into the conversation at the point where the hook fired. Claude reads the reminder on the next model request, but it does not appear as a chat message in the interface.

665 

666Return `additionalContext` inside `hookSpecificOutput` alongside the event name:

667 

668```json theme={null}

669{

670 "hookSpecificOutput": {

671 "hookEventName": "PostToolUse",

672 "additionalContext": "This file is generated. Edit src/schema.ts and run `bun generate` instead."

673 }

674}

675```

676 

677Where the reminder appears depends on the event:

678 

679* [SessionStart](#sessionstart), [Setup](#setup), and [SubagentStart](#subagentstart): at the start of the conversation, before the first prompt

680* [UserPromptSubmit](#userpromptsubmit) and [UserPromptExpansion](#userpromptexpansion): alongside the submitted prompt

681* [PreToolUse](#pretooluse), [PostToolUse](#posttooluse), [PostToolUseFailure](#posttoolusefailure), and [PostToolBatch](#posttoolbatch): next to the tool result

682 

683When several hooks return `additionalContext` for the same event, Claude receives all of the values. If a value exceeds 10,000 characters, Claude Code writes the full text to a file in the session directory and passes Claude the file path with a short preview instead.

684 

685Use `additionalContext` for information Claude should know about the current state of your environment or the operation that just ran:

686 

687* **Environment state**: the current branch, deployment target, or active feature flags

688* **Conditional project rules**: which test command applies to the file just edited, which directories are read-only in this worktree

689* **External data**: open issues assigned to you, recent CI results, content fetched from an internal service

690 

691For instructions that never change, prefer [CLAUDE.md](/en/memory). It loads without running a script and is the standard place for static project conventions.

692 

693Write the text as factual statements rather than imperative system instructions. Phrasing such as "The deployment target is production" or "This repo uses `bun test`" reads as project information. Text framed as out-of-band system commands can trigger Claude's prompt-injection defenses, which causes Claude to surface the text to you instead of treating it as context.

694 

695Once injected, the text is saved in the session transcript. For mid-session events like `PostToolUse` or `UserPromptSubmit`, resuming with `--continue` or `--resume` replays the saved text rather than re-running the hook for past turns, so values like timestamps or commit SHAs become stale on resume. `SessionStart` hooks run again on resume with `source` set to `"resume"`, so they can refresh their context.

696 

614#### Decision control697#### Decision control

615 698 

616Not 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:699Not 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:

617 700 

618| Events | Decision pattern | Key fields |701| Events | Decision pattern | Key fields |

619| :-------------------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |702| :---------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

620| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange, PreCompact | Top-level `decision` | `decision: "block"`, `reason` |703| UserPromptSubmit, UserPromptExpansion, PostToolUse, PostToolUseFailure, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact | Top-level `decision` | `decision: "block"`, `reason` |

621| TeammateIdle, TaskCreated, TaskCompleted | Exit code or `continue: false` | Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior |704| TeammateIdle, TaskCreated, TaskCompleted | Exit code or `continue: false` | Exit code 2 blocks the action with stderr feedback. JSON `{"continue": false, "stopReason": "..."}` also stops the teammate entirely, matching `Stop` hook behavior |

622| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason` |705| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason` |

623| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |706| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |


631 714 

632<Tabs>715<Tabs>

633 <Tab title="Top-level decision">716 <Tab title="Top-level decision">

634 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:717 Used by `UserPromptSubmit`, `UserPromptExpansion`, `PostToolUse`, `PostToolUseFailure`, `PostToolBatch`, `Stop`, `SubagentStop`, `ConfigChange`, and `PreCompact`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:

635 718 

636 ```json theme={null}719 ```json theme={null}

637 {720 {


684 767 

685Runs 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.768Runs 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.

686 769 

687SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.770SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` and `type: "mcp_tool"` hooks are supported.

688 771 

689The matcher value corresponds to how the session was initiated:772The matcher value corresponds to how the session was initiated:

690 773 


715Any 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:798Any 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:

716 799 

717| Field | Description |800| Field | Description |

718| :------------------ | :------------------------------------------------------------------------ |801| :------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

719| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |802| `additionalContext` | String added to Claude's context at the start of the conversation, before the first prompt. See [Add context for Claude](#add-context-for-claude) for how the text is delivered and what to put in it |

720 803 

721```json theme={null}804```json theme={null}

722{805{

723 "hookSpecificOutput": {806 "hookSpecificOutput": {

724 "hookEventName": "SessionStart",807 "hookEventName": "SessionStart",

725 "additionalContext": "My additional context here"808 "additionalContext": "Current branch: feat/auth-refactor\nUncommitted changes: src/auth.ts, src/login.tsx\nActive issue: #4211 Migrate to OAuth2"

726 }809 }

727}810}

728```811```

729 812 

813Since plain stdout already reaches Claude for this event, a hook that only loads context can print to stdout directly without building JSON. Use the JSON form when you need to combine context with other fields such as `suppressOutput`.

814 

730#### Persist environment variables815#### Persist environment variables

731 816 

732SessionStart 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.817SessionStart 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.


767Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.852Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.

768 853 

769<Note>854<Note>

770 `CLAUDE_ENV_FILE` is available for SessionStart, [CwdChanged](#cwdchanged), and [FileChanged](#filechanged) hooks. Other hook types do not have access to this variable.855 `CLAUDE_ENV_FILE` is available for SessionStart, [Setup](#setup), [CwdChanged](#cwdchanged), and [FileChanged](#filechanged) hooks. Other hook types do not have access to this variable.

771</Note>856</Note>

772 857 

858### Setup

859 

860Fires only when you launch Claude Code with `--init-only`, or with `--init` or `--maintenance` in print mode (`-p`). It does not fire on normal startup. Use it for one-time dependency installation or scheduled cleanup that you trigger explicitly from CI or scripts, separate from normal session startup. For per-session initialization, use [SessionStart](#sessionstart) instead.

861 

862The matcher value corresponds to the CLI flag that triggered the hook:

863 

864| Matcher | When it fires |

865| :------------ | :----------------------------------------- |

866| `init` | `claude --init-only` or `claude -p --init` |

867| `maintenance` | `claude -p --maintenance` |

868 

869`--init-only` runs Setup hooks and `SessionStart` hooks with the `startup` matcher, then exits without starting a conversation. `--init` and `--maintenance` fire Setup hooks only when combined with `-p` (print mode); in an interactive session those two flags do not currently fire Setup hooks.

870 

871Because Setup does not fire on every launch, a plugin that needs a dependency installed cannot rely on Setup alone. The practical pattern is to check for the dependency on first use and install on miss, for example a hook or skill that tests for `${CLAUDE_PLUGIN_DATA}/node_modules` and runs `npm install` if absent. See the [persistent data directory](/en/plugins-reference#persistent-data-directory) for where to store installed dependencies.

872 

873#### Setup input

874 

875In addition to the [common input fields](#common-input-fields), Setup hooks receive a `trigger` field set to either `"init"` or `"maintenance"`:

876 

877```json theme={null}

878{

879 "session_id": "abc123",

880 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

881 "cwd": "/Users/...",

882 "hook_event_name": "Setup",

883 "trigger": "init"

884}

885```

886 

887#### Setup decision control

888 

889Setup hooks cannot block. On exit code 2, stderr is shown to the user; on any other non-zero exit code, stderr appears only when you launch with `--verbose`. In both cases execution continues. To pass information into Claude's context, return `additionalContext` in JSON output; plain stdout is written to the debug log only. In addition to the [JSON output fields](#json-output) available to all hooks, you can return these event-specific fields:

890 

891| Field | Description |

892| :------------------ | :------------------------------------------------------------------------ |

893| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |

894 

895```json theme={null}

896{

897 "hookSpecificOutput": {

898 "hookEventName": "Setup",

899 "additionalContext": "Dependencies installed: node_modules, .venv"

900 }

901}

902```

903 

904Setup hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` and `type: "mcp_tool"` hooks are supported.

905 

773### InstructionsLoaded906### InstructionsLoaded

774 907 

775Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes.908Fires when a `CLAUDE.md` or `.claude/rules/*.md` file is loaded into context. This event fires at session start for eagerly-loaded files and again later when files are lazily loaded, for example when Claude accesses a subdirectory that contains a nested `CLAUDE.md` or when conditional rules with `paths:` frontmatter match. The hook does not support blocking or decision control. It runs asynchronously for observability purposes.


840To block a prompt, return a JSON object with `decision` set to `"block"`:973To block a prompt, return a JSON object with `decision` set to `"block"`:

841 974 

842| Field | Description |975| Field | Description |

843| :------------------ | :----------------------------------------------------------------------------------------------------------------- |976| :------------------ | :--------------------------------------------------------------------------------------------------------------------- |

844| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |977| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |

845| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |978| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |

846| `additionalContext` | String added to Claude's context |979| `additionalContext` | String added to Claude's context alongside the submitted prompt. See [Add context for Claude](#add-context-for-claude) |

847| `sessionTitle` | Sets the session title, same effect as `/rename`. Use to name sessions automatically based on the prompt content |980| `sessionTitle` | Sets the session title. Use to name sessions automatically based on the prompt content |

848 981 

849```json theme={null}982```json theme={null}

850{983{


863 block prompts or want more structured control.996 block prompts or want more structured control.

864</Note>997</Note>

865 998 

999### UserPromptExpansion

1000 

1001Runs when a user-typed slash command expands into a prompt before reaching Claude. Use this to block specific commands from direct invocation, inject context for a particular skill, or log which commands users invoke. For example, a hook matching `deploy` can block `/deploy` unless an approval file is present, or a hook matching a review skill can append the team's review checklist as `additionalContext`.

1002 

1003This event covers the path `PreToolUse` does not: a `PreToolUse` hook matching the `Skill` tool fires only when Claude calls the tool, but typing `/skillname` directly bypasses `PreToolUse`. `UserPromptExpansion` fires on that direct path.

1004 

1005Matches on `command_name`. Leave the matcher empty to fire on every prompt-type slash command.

1006 

1007#### UserPromptExpansion input

1008 

1009In addition to the [common input fields](#common-input-fields), UserPromptExpansion hooks receive `expansion_type`, `command_name`, `command_args`, `command_source`, and the original `prompt` string. The `expansion_type` field is `slash_command` for skill and custom commands, or `mcp_prompt` for MCP server prompts.

1010 

1011```json theme={null}

1012{

1013 "session_id": "abc123",

1014 "transcript_path": "/Users/.../00893aaf.jsonl",

1015 "cwd": "/Users/...",

1016 "permission_mode": "default",

1017 "hook_event_name": "UserPromptExpansion",

1018 "expansion_type": "slash_command",

1019 "command_name": "example-skill",

1020 "command_args": "arg1 arg2",

1021 "command_source": "plugin",

1022 "prompt": "/example-skill arg1 arg2"

1023}

1024```

1025 

1026#### UserPromptExpansion decision control

1027 

1028`UserPromptExpansion` hooks can block the expansion or add context. All [JSON output fields](#json-output) are available.

1029 

1030| Field | Description |

1031| :------------------ | :-------------------------------------------------------------------------------------------------------------------- |

1032| `decision` | `"block"` prevents the slash command from expanding. Omit to allow it to proceed |

1033| `reason` | Shown to the user when `decision` is `"block"` |

1034| `additionalContext` | String added to Claude's context alongside the expanded prompt. See [Add context for Claude](#add-context-for-claude) |

1035 

1036```json theme={null}

1037{

1038 "decision": "block",

1039 "reason": "This slash command is not available",

1040 "hookSpecificOutput": {

1041 "hookEventName": "UserPromptExpansion",

1042 "additionalContext": "Additional context for this expansion"

1043 }

1044}

1045```

1046 

866### PreToolUse1047### PreToolUse

867 1048 

868Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any [MCP tool names](#match-mcp-tools).1049Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Agent`, `WebFetch`, `WebSearch`, `AskUserQuestion`, `ExitPlanMode`, and any [MCP tool names](#match-mcp-tools).


984| `permissionDecision` | `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](/en/permissions#manage-permissions) are still evaluated regardless of what the hook returns |1165| `permissionDecision` | `"allow"` skips the permission prompt. `"deny"` prevents the tool call. `"ask"` prompts the user to confirm. `"defer"` exits gracefully so the tool can be resumed later. [Deny and ask rules](/en/permissions#manage-permissions) are still evaluated regardless of what the hook returns |

985| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored |1166| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored |

986| `updatedInput` | Modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored |1167| `updatedInput` | Modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user. For `"defer"`, ignored |

987| `additionalContext` | String added to Claude's context before the tool executes. For `"defer"`, ignored |1168| `additionalContext` | String added to Claude's context alongside the tool result. Ignored when `permissionDecision` is `"defer"`. See [Add context for Claude](#add-context-for-claude) |

988 1169 

989When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`.1170When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`.

990 1171 


1042}1223}

1043```1224```

1044 1225 

1045There is no timeout or retry limit. The session remains on disk until you resume it. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook.1226There is no timeout or retry limit. The session remains on disk until you resume it, subject to the [`cleanupPeriodDays`](/en/settings#available-settings) retention sweep that deletes session files after 30 days by default. If the answer is not ready when you resume, the hook can return `"defer"` again and the process exits the same way. The calling process controls when to break the loop by eventually returning `"allow"` or `"deny"` from the hook.

1046 1227 

1047`"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved.1228`"defer"` only works when Claude makes a single tool call in the turn. If Claude makes several tool calls at once, `"defer"` is ignored with a warning and the tool proceeds through the normal permission flow. The constraint exists because resume can only re-run one tool: there is no way to defer one call from a batch without leaving the others unresolved.

1048 1229 

1049If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.1230If the deferred tool is no longer available when you resume, the process exits with `stop_reason: "tool_deferred_unavailable"` and `is_error: true` before the hook fires. This happens when an MCP server that provided the tool is not connected for the resumed session. The `deferred_tool_use` payload is still included so you can identify which tool went missing.

1050 1231 

1051<Warning>1232<Note>

1052 `--resume` does not restore the permission mode from the prior session. Pass the same `--permission-mode` flag on resume that was active when the tool was deferred. Claude Code logs a warning if the modes differ.1233 `--resume` restores the permission mode that was active when the tool was deferred, so you do not need to pass `--permission-mode` again. The exceptions are `plan` and `bypassPermissions`, which are never carried over. Passing `--permission-mode` explicitly on resume overrides the restored value.

1053</Warning>1234</Note>

1054 1235 

1055### PermissionRequest1236### PermissionRequest

1056 1237 


1091`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:1272`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:

1092 1273 

1093| Field | Description |1274| Field | Description |

1094| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |1275| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1095| `behavior` | `"allow"` grants the permission, `"deny"` denies it |1276| `behavior` | `"allow"` grants the permission, `"deny"` denies it. [Deny and ask rules](/en/permissions#manage-permissions) are still evaluated, so a hook returning `"allow"` does not override a matching deny rule |

1096| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones |1277| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones. The modified input is re-evaluated against deny and ask rules |

1097| `updatedPermissions` | For `"allow"` only: array of [permission update entries](#permission-update-entries) to apply, such as adding an allow rule or changing the session permission mode |1278| `updatedPermissions` | For `"allow"` only: array of [permission update entries](#permission-update-entries) to apply, such as adding an allow rule or changing the session permission mode |

1098| `message` | For `"deny"` only: tells Claude why the permission was denied |1279| `message` | For `"deny"` only: tells Claude why the permission was denied |

1099| `interrupt` | For `"deny"` only: if `true`, stops Claude |1280| `interrupt` | For `"deny"` only: if `true`, stops Claude |


1125| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |1306| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |

1126| `removeDirectories` | `directories`, `destination` | Removes working directories |1307| `removeDirectories` | `directories`, `destination` | Removes working directories |

1127 1308 

1309<Note>

1310 `setMode` with `bypassPermissions` only takes effect if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and the mode is not disabled by [`permissions.disableBypassPermissionsMode`](/en/permissions#managed-settings). Otherwise the update is a no-op. `bypassPermissions` is never persisted as `defaultMode` regardless of `destination`.

1311</Note>

1312 

1128The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.1313The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.

1129 1314 

1130| `destination` | Writes to |1315| `destination` | Writes to |


1162 "filePath": "/path/to/file.txt",1347 "filePath": "/path/to/file.txt",

1163 "success": true1348 "success": true

1164 },1349 },

1165 "tool_use_id": "toolu_01ABC123..."1350 "tool_use_id": "toolu_01ABC123...",

1351 "duration_ms": 12

1166}1352}

1167```1353```

1168 1354 

1355| Field | Description |

1356| :------------ | :------------------------------------------------------------------------------------------------------------ |

1357| `duration_ms` | Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks |

1358 

1169#### PostToolUse decision control1359#### PostToolUse decision control

1170 1360 

1171`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:1361`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:

1172 1362 

1173| Field | Description |1363| Field | Description |

1174| :--------------------- | :----------------------------------------------------------------------------------------- |1364| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |

1175| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |1365| `decision` | `"block"` adds the `reason` next to the tool result. Claude still sees the original output; to replace it, use `updatedToolOutput` |

1176| `reason` | Explanation shown to Claude when `decision` is `"block"` |1366| `reason` | Explanation shown to Claude when `decision` is `"block"` |

1177| `additionalContext` | Additional context for Claude to consider |1367| `additionalContext` | String added to Claude's context alongside the tool result. See [Add context for Claude](#add-context-for-claude) |

1178| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |1368| `updatedToolOutput` | Replaces the tool's output with the provided value before it is sent to Claude. The value must match the tool's output shape |

1369| `updatedMCPToolOutput` | Replaces the output for [MCP tools](#match-mcp-tools) only. Prefer `updatedToolOutput`, which works for all tools |

1370 

1371The example below replaces the output of a `Bash` call. The replacement value matches the `Bash` tool's output shape:

1179 1372 

1180```json theme={null}1373```json theme={null}

1181{1374{

1182 "decision": "block",

1183 "reason": "Explanation for decision",

1184 "hookSpecificOutput": {1375 "hookSpecificOutput": {

1185 "hookEventName": "PostToolUse",1376 "hookEventName": "PostToolUse",

1186 "additionalContext": "Additional information for Claude"1377 "additionalContext": "Additional information for Claude",

1378 "updatedToolOutput": {

1379 "stdout": "[redacted]",

1380 "stderr": "",

1381 "interrupted": false,

1382 "isImage": false

1383 }

1187 }1384 }

1188}1385}

1189```1386```

1190 1387 

1388<Warning>

1389 `updatedToolOutput` only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect. Telemetry such as OpenTelemetry tool spans and analytics events also captures the original output before the hook runs. To prevent or modify a tool call before it runs, use a [PreToolUse](#pretooluse) hook instead.

1390 

1391 The replacement value must match the tool's output shape. Built-in tools return structured objects rather than plain strings. For example, `Bash` returns an object with `stdout`, `stderr`, `interrupted`, and `isImage` fields. For built-in tools, a value that does not match the tool's output schema is ignored and the original output is used. MCP tool output is passed through without schema validation. Stripping error details that Claude needs can cause it to proceed on a false assumption.

1392</Warning>

1393 

1191### PostToolUseFailure1394### PostToolUseFailure

1192 1395 

1193Runs 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.1396Runs 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.


1212 },1415 },

1213 "tool_use_id": "toolu_01ABC123...",1416 "tool_use_id": "toolu_01ABC123...",

1214 "error": "Command exited with non-zero status code 1",1417 "error": "Command exited with non-zero status code 1",

1215 "is_interrupt": false1418 "is_interrupt": false,

1419 "duration_ms": 4187

1216}1420}

1217```1421```

1218 1422 

1219| Field | Description |1423| Field | Description |

1220| :------------- | :------------------------------------------------------------------------------ |1424| :------------- | :------------------------------------------------------------------------------------------------------------ |

1221| `error` | String describing what went wrong |1425| `error` | String describing what went wrong |

1222| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |1426| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |

1427| `duration_ms` | Optional. Tool execution time in milliseconds. Excludes time spent in permission prompts and PreToolUse hooks |

1223 1428 

1224#### PostToolUseFailure decision control1429#### PostToolUseFailure decision control

1225 1430 

1226`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:1431`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:

1227 1432 

1228| Field | Description |1433| Field | Description |

1229| :------------------ | :------------------------------------------------------------ |1434| :------------------ | :---------------------------------------------------------------------------------------------------------- |

1230| `additionalContext` | Additional context for Claude to consider alongside the error |1435| `additionalContext` | String added to Claude's context alongside the error. See [Add context for Claude](#add-context-for-claude) |

1231 1436 

1232```json theme={null}1437```json theme={null}

1233{1438{


1238}1443}

1239```1444```

1240 1445 

1446### PostToolBatch

1447 

1448Runs once after every tool call in a batch has resolved, before Claude Code sends the next request to the model. `PostToolUse` fires once per tool, which means it fires concurrently when Claude makes parallel tool calls. `PostToolBatch` fires exactly once with the full batch, so it is the right place to inject context that depends on the set of tools that ran rather than on any single tool. There is no matcher for this event.

1449 

1450#### PostToolBatch input

1451 

1452In addition to the [common input fields](#common-input-fields), PostToolBatch hooks receive `tool_calls`, an array describing every tool call in the batch:

1453 

1454```json theme={null}

1455{

1456 "session_id": "abc123",

1457 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1458 "cwd": "/Users/...",

1459 "permission_mode": "default",

1460 "hook_event_name": "PostToolBatch",

1461 "tool_calls": [

1462 {

1463 "tool_name": "Read",

1464 "tool_input": {"file_path": "/.../ledger/accounts.py"},

1465 "tool_use_id": "toolu_01...",

1466 "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."

1467 },

1468 {

1469 "tool_name": "Read",

1470 "tool_input": {"file_path": "/.../ledger/transactions.py"},

1471 "tool_use_id": "toolu_02...",

1472 "tool_response": " 1\tfrom __future__ import annotations\n 2\t..."

1473 }

1474 ]

1475}

1476```

1477 

1478`tool_response` contains the same content the model receives in the corresponding `tool_result` block. The value is a serialized string or content-block array, exactly as the tool emitted it. For `Read`, that means line-number-prefixed text rather than raw file contents. Responses can be large, so parse only the fields you need.

1479 

1480<Note>

1481 The `tool_response` shape differs from `PostToolUse`'s. `PostToolUse` passes the tool's structured `Output` object, such as `{filePath: "...", success: true}` for `Write`; `PostToolBatch` passes the serialized `tool_result` content the model sees.

1482</Note>

1483 

1484#### PostToolBatch decision control

1485 

1486`PostToolBatch` hooks can inject context for Claude. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:

1487 

1488| Field | Description |

1489| :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1490| `additionalContext` | Context string injected once before the next model call. See [Add context for Claude](#add-context-for-claude) for delivery details, what to put in it, and how resumed sessions handle past values |

1491 

1492```json theme={null}

1493{

1494 "hookSpecificOutput": {

1495 "hookEventName": "PostToolBatch",

1496 "additionalContext": "These files are part of the ledger module. Run pytest before marking the task complete."

1497 }

1498}

1499```

1500 

1501Returning `decision: "block"` or `continue: false` stops the agentic loop before the next model call.

1502 

1241### PermissionDenied1503### PermissionDenied

1242 1504 

1243Runs when the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier denies a tool call. This hook only fires in auto mode: it does not run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call.1505Runs when the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier denies a tool call. This hook only fires in auto mode: it does not run when you manually deny a permission dialog, when a `PreToolUse` hook blocks a call, or when a `deny` rule matches. Use it to log classifier denials, adjust configuration, or tell the model it may retry the tool call.


1286 1548 

1287### Notification1549### Notification

1288 1550 

1289Runs 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.1551Runs when Claude Code sends notifications. Matches on notification type: `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`. Omit the matcher to run hooks for all notification types.

1290 1552 

1291Use 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:1553Use 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:

1292 1554 


1333}1595}

1334```1596```

1335 1597 

1336Notification 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:1598Notification hooks cannot block or modify notifications. They are intended for side effects such as forwarding the notification to an external service. The [common JSON output fields](#json-output) such as `systemMessage` apply.

1337 

1338| Field | Description |

1339| :------------------ | :------------------------------- |

1340| `additionalContext` | String added to Claude's context |

1341 1599 

1342### SubagentStart1600### SubagentStart

1343 1601 

1344Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).1602Runs when a Claude Code subagent is spawned via the Agent tool. Supports matchers to filter by agent type name (built-in agents like `general-purpose`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).

1345 1603 

1346#### SubagentStart input1604#### SubagentStart input

1347 1605 

1348In 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).1606In 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 `"general-purpose"`, `"Explore"`, `"Plan"`, or custom agent names).

1349 1607 

1350```json theme={null}1608```json theme={null}

1351{1609{


1361SubagentStart 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:1619SubagentStart 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:

1362 1620 

1363| Field | Description |1621| Field | Description |

1364| :------------------ | :------------------------------------- |1622| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------ |

1365| `additionalContext` | String added to the subagent's context |1623| `additionalContext` | String added to the subagent's context at the start of its conversation, before its first prompt. See [Add context for Claude](#add-context-for-claude) |

1366 1624 

1367```json theme={null}1625```json theme={null}

1368{1626{


1557 1815 

1558| Field | Description |1816| Field | Description |

1559| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1817| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1560| `error` | Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |1818| `error` | Error type: `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |

1561| `error_details` | Additional details about the error, when available |1819| `error_details` | Additional details about the error, when available |

1562| `last_assistant_message` | The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude's conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"` |1820| `last_assistant_message` | The rendered error text shown in the conversation. Unlike `Stop` and `SubagentStop`, where this field holds Claude's conversational output, for `StopFailure` it contains the API error string itself, such as `"API Error: Rate limit reached"` |

1563 1821 


1694 1952 

1695Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with [FileChanged](#filechanged) for tools like [direnv](https://direnv.net/) that manage per-directory environment.1953Runs when the working directory changes during a session, for example when Claude executes a `cd` command. Use this to react to directory changes: reload environment variables, activate project-specific toolchains, or run setup scripts automatically. Pairs with [FileChanged](#filechanged) for tools like [direnv](https://direnv.net/) that manage per-directory environment.

1696 1954 

1697CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.1955CwdChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables).

1698 1956 

1699CwdChanged does not support matchers and fires on every directory change.1957CwdChanged does not support matchers and fires on every directory change.

1700 1958 


1732* **Build the watch list**: the value is split on `|` and each segment is registered as a literal filename in the working directory, so `".envrc|.env"` watches exactly those two files. Regex patterns are not useful here: a value like `^\.env` would watch a file literally named `^\.env`.1990* **Build the watch list**: the value is split on `|` and each segment is registered as a literal filename in the working directory, so `".envrc|.env"` watches exactly those two files. Regex patterns are not useful here: a value like `^\.env` would watch a file literally named `^\.env`.

1733* **Filter which hooks run**: when a watched file changes, the same value filters which hook groups run using the standard [matcher rules](#matcher-patterns) against the changed file's basename.1991* **Filter which hooks run**: when a watched file changes, the same value filters which hook groups run using the standard [matcher rules](#matcher-patterns) against the changed file's basename.

1734 1992 

1735FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables). Only `type: "command"` hooks are supported.1993FileChanged hooks have access to `CLAUDE_ENV_FILE`. Variables written to that file persist into subsequent Bash commands for the session, just as in [SessionStart hooks](#persist-environment-variables).

1736 1994 

1737#### FileChanged input1995#### FileChanged input

1738 1996 


1768 2026 

1769When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](/en/sub-agents#choose-the-subagent-scope), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial.2027When you run `claude --worktree` or a [subagent uses `isolation: "worktree"`](/en/sub-agents#choose-the-subagent-scope), Claude Code creates an isolated working copy using `git worktree`. If you configure a WorktreeCreate hook, it replaces the default git behavior, letting you use a different version control system like SVN, Perforce, or Mercurial.

1770 2028 

1771Because the hook replaces the default behavior entirely, [`.worktreeinclude`](/en/common-workflows#copy-gitignored-files-to-worktrees) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script.2029Because the hook replaces the default behavior entirely, [`.worktreeinclude`](/en/worktrees#copy-gitignored-files-into-worktrees) is not processed. If you need to copy local configuration files like `.env` into the new worktree, do it inside your hook script.

1772 2030 

1773The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`.2031The hook must return the absolute path to the created worktree directory. Claude Code uses this path as the working directory for the isolated session. Command hooks print it on stdout; HTTP hooks return it via `hookSpecificOutput.worktreePath`.

1774 2032 


2069 2327 

2070## Prompt-based hooks2328## Prompt-based hooks

2071 2329 

2072In addition to command and HTTP hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type.2330In addition to command, HTTP, and MCP tool hooks, Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action, and agent hooks (`type: "agent"`) that spawn an agentic verifier with tool access. Not all events support every hook type.

2073 2331 

2074Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):2332Events that support all five hook types (`command`, `http`, `mcp_tool`, `prompt`, and `agent`):

2075 2333 

2076* `PermissionRequest`2334* `PermissionRequest`

2335* `PostToolBatch`

2077* `PostToolUse`2336* `PostToolUse`

2078* `PostToolUseFailure`2337* `PostToolUseFailure`

2079* `PreToolUse`2338* `PreToolUse`


2081* `SubagentStop`2340* `SubagentStop`

2082* `TaskCompleted`2341* `TaskCompleted`

2083* `TaskCreated`2342* `TaskCreated`

2343* `UserPromptExpansion`

2084* `UserPromptSubmit`2344* `UserPromptSubmit`

2085 2345 

2086Events that support `command` and `http` hooks but not `prompt` or `agent`:2346Events that support `command`, `http`, and `mcp_tool` hooks but not `prompt` or `agent`:

2087 2347 

2088* `ConfigChange`2348* `ConfigChange`

2089* `CwdChanged`2349* `CwdChanged`


2102* `WorktreeCreate`2362* `WorktreeCreate`

2103* `WorktreeRemove`2363* `WorktreeRemove`

2104 2364 

2105`SessionStart` supports only `command` hooks.2365`SessionStart` and `Setup` support `command` and `mcp_tool` hooks. They do not support `http`, `prompt`, or `agent` hooks.

2106 2366 

2107### How prompt-based hooks work2367### How prompt-based hooks work

2108 2368 


2154```2414```

2155 2415 

2156| Field | Description |2416| Field | Description |

2157| :------- | :--------------------------------------------------------- |2417| :------- | :------------------------------------------------------------------ |

2158| `ok` | `true` allows the action, `false` prevents it |2418| `ok` | `true` to allow, `false` to block. See the per-event behavior below |

2159| `reason` | Required when `ok` is `false`. Explanation shown to Claude |2419| `reason` | Required when `ok` is `false`. Explanation for the decision |

2420 

2421What happens on `ok: false` depends on the event:

2422 

2423* `Stop` and `SubagentStop`: the reason is fed back to Claude as its next instruction and the turn continues

2424* `PreToolUse`: the tool call is denied and the reason is returned to Claude as the tool error, equivalent to a command hook's `permissionDecision: "deny"`

2425* `PostToolUse`, `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the reason appears in the chat as a warning line, equivalent to returning `"continue": false` from a command hook

2426* `PostToolUseFailure`, `TaskCreated`, and `TaskCompleted`: the reason is returned to Claude as a tool error, similar to `PreToolUse`

2427* `PermissionRequest`: `ok: false` has no effect. To deny an approval from a hook, use a [command hook](#command-hook-fields) returning `hookSpecificOutput.decision.behavior: "deny"`

2428 

2429If you need finer control on any event, use a [command hook](#command-hook-fields) with the per-event fields described in [Decision control](#decision-control).

2160 2430 

2161### Example: Multi-criteria Stop hook2431### Example: Multi-criteria Stop hook

2162 2432 


2182 2452 

2183## Agent-based hooks2453## Agent-based hooks

2184 2454 

2455<Warning>

2456 Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](#command-hook-fields).

2457</Warning>

2458 

2185Agent-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.2459Agent-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.

2186 2460 

2187### How agent hooks work2461### How agent hooks work


2383 2657 

2384For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching.2658For more granular hook matching details, set `CLAUDE_CODE_DEBUG_LOG_LEVEL=verbose` to see additional log lines such as hook matcher counts and query matching.

2385 2659 

2386For 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.2660For 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. For a broader diagnostic walkthrough covering `/context`, `/doctor`, and settings precedence, see [Debug your config](/en/debug-your-config).

hooks-guide.md +62 −16

Details

171 </Tab>171 </Tab>

172</Tabs>172</Tabs>

173 173 

174The empty `matcher` fires on all notification types. To fire only on specific events, set it to one of these values:

175 

176| Matcher | Fires when |

177| :--------------------- | :----------------------------------------------------- |

178| `permission_prompt` | Claude needs you to approve a tool use |

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

180| `auth_success` | Authentication completes |

181| `elicitation_dialog` | An MCP server opens an elicitation form |

182| `elicitation_complete` | An MCP elicitation form is submitted or dismissed |

183| `elicitation_response` | An MCP elicitation response is sent back to the server |

184 

185Type `/hooks` and select `Notification` to confirm the hook is registered. For the full event schema, see the [Notification reference](/en/hooks#notification).

186 

174### Auto-format code after edits187### Auto-format code after edits

175 188 

176Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.189Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.


316 329 

317Some projects set different environment variables depending on which directory you are in. Tools like [direnv](https://direnv.net/) do this automatically in your shell, but Claude's Bash tool does not pick up those changes on its own.330Some projects set different environment variables depending on which directory you are in. Tools like [direnv](https://direnv.net/) do this automatically in your shell, but Claude's Bash tool does not pick up those changes on its own.

318 331 

319A `CwdChanged` hook fixes this: it runs each time Claude changes directory, so you can reload the correct variables for the new location. The hook writes the updated values to `CLAUDE_ENV_FILE`, which Claude Code applies before each Bash command. Add this to `~/.claude/settings.json`:332Pairing a `SessionStart` hook with a `CwdChanged` hook fixes this. `SessionStart` loads the variables for the directory you launch in, and `CwdChanged` reloads them each time Claude changes directory. Both write to `CLAUDE_ENV_FILE`, which Claude Code runs as a script preamble before each Bash command. Add this to `~/.claude/settings.json`:

320 333 

321```json theme={null}334```json theme={null}

322{335{

323 "hooks": {336 "hooks": {

337 "SessionStart": [

338 {

339 "hooks": [

340 {

341 "type": "command",

342 "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""

343 }

344 ]

345 }

346 ],

324 "CwdChanged": [347 "CwdChanged": [

325 {348 {

326 "hooks": [349 "hooks": [

327 {350 {

328 "type": "command",351 "type": "command",

329 "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""352 "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""

330 }353 }

331 ]354 ]

332 }355 }


335}358}

336```359```

337 360 

361Run `direnv allow` once in each directory that has an `.envrc` so direnv is permitted to load it. If you use devbox or nix instead of direnv, the same pattern works with `devbox shellenv` or `devbox global shellenv` in place of `direnv export bash`.

362 

338To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](/en/hooks#filechanged) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:363To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch, separated by `|`. To build the watch list, this value is split into literal filenames rather than evaluated as a regex. See [FileChanged](/en/hooks#filechanged) for how the same value also filters which hook groups run when a file changes. This example watches `.envrc` and `.env` in the working directory:

339 364 

340```json theme={null}365```json theme={null}


346 "hooks": [371 "hooks": [

347 {372 {

348 "type": "command",373 "type": "command",

349 "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""374 "command": "direnv export bash > \"$CLAUDE_ENV_FILE\""

350 }375 }

351 ]376 ]

352 }377 }


387 412 

388To set a specific permission mode instead, your hook's output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.413To set a specific permission mode instead, your hook's output can include an `updatedPermissions` array with a `setMode` entry. The `mode` value is any permission mode like `default`, `acceptEdits`, or `bypassPermissions`, and `destination: "session"` applies it for the current session only.

389 414 

415<Note>

416 `bypassPermissions` only applies if the session was launched with bypass mode already available: `--dangerously-skip-permissions`, `--permission-mode bypassPermissions`, `--allow-dangerously-skip-permissions`, or `permissions.defaultMode: "bypassPermissions"` in settings, and not disabled by [`permissions.disableBypassPermissionsMode`](/en/permissions#managed-settings). It is never persisted as `defaultMode`.

417</Note>

418 

390To switch the session to `acceptEdits`, your hook writes this JSON to stdout:419To switch the session to `acceptEdits`, your hook writes this JSON to stdout:

391 420 

392```json theme={null}421```json theme={null}


410Hook 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:439Hook 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:

411 440 

412| Event | When it fires |441| Event | When it fires |

413| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |442| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

414| `SessionStart` | When a session begins or resumes |443| `SessionStart` | When a session begins or resumes |

444| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |

415| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |445| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

446| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

416| `PreToolUse` | Before a tool call executes. Can block it |447| `PreToolUse` | Before a tool call executes. Can block it |

417| `PermissionRequest` | When a permission dialog appears |448| `PermissionRequest` | When a permission dialog appears |

418| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |449| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

419| `PostToolUse` | After a tool call succeeds |450| `PostToolUse` | After a tool call succeeds |

420| `PostToolUseFailure` | After a tool call fails |451| `PostToolUseFailure` | After a tool call fails |

452| `PostToolBatch` | After a full batch of parallel tool calls resolves, before the next model call |

421| `Notification` | When Claude Code sends a notification |453| `Notification` | When Claude Code sends a notification |

422| `SubagentStart` | When a subagent is spawned |454| `SubagentStart` | When a subagent is spawned |

423| `SubagentStop` | When a subagent finishes |455| `SubagentStop` | When a subagent finishes |


440 472 

441When multiple hooks match, each one returns its own result. For decisions, Claude Code picks the most restrictive answer. A `PreToolUse` hook returning `deny` cancels the tool call no matter what the others return. One hook returning `ask` forces the permission prompt even if the rest return `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together.473When multiple hooks match, each one returns its own result. For decisions, Claude Code picks the most restrictive answer. A `PreToolUse` hook returning `deny` cancels the tool call no matter what the others return. One hook returning `ask` forces the permission prompt even if the rest return `allow`. Text from `additionalContext` is kept from every hook and passed to Claude together.

442 474 

443Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:475Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Four other types are available:

444 476 

445* `"type": "http"`: POST event data to a URL. See [HTTP hooks](#http-hooks).477* `"type": "http"`: POST event data to a URL. See [HTTP hooks](#http-hooks).

478* `"type": "mcp_tool"`: call a tool on an already-connected MCP server. See [MCP tool hooks](/en/hooks#mcp-tool-hook-fields).

446* `"type": "prompt"`: single-turn LLM evaluation. See [Prompt-based hooks](#prompt-based-hooks).479* `"type": "prompt"`: single-turn LLM evaluation. See [Prompt-based hooks](#prompt-based-hooks).

447* `"type": "agent"`: multi-turn verification with tool access. See [Agent-based hooks](#agent-based-hooks).480* `"type": "agent"`: multi-turn verification with tool access. Agent hooks are experimental and may change. See [Agent-based hooks](#agent-based-hooks).

448 481 

449### Read input and return output482### Read input and return output

450 483 


487 520 

488The exit code determines what happens next:521The exit code determines what happens next:

489 522 

490* **Exit 0**: the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude's context.523* **Exit 0**: the action proceeds. For `UserPromptSubmit`, `UserPromptExpansion`, and `SessionStart` hooks, anything you write to stdout is added to Claude's context.

491* **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.524* **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust. Some events cannot be blocked: for `SessionStart`, `Setup`, `Notification`, and others, exit 2 shows stderr to the user and execution continues. See [exit code 2 behavior per event](/en/hooks#exit-code-2-behavior-per-event) for the full list.

492* **Any other exit code**: the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](/en/hooks#debug-hooks).525* **Any other exit code**: the action proceeds. The transcript shows a `<hook name> hook error` notice followed by the first line of stderr; the full stderr goes to the [debug log](/en/hooks#debug-hooks).

493 526 

494#### Structured JSON output527#### Structured JSON output


546 579 

547The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. See [Matcher patterns](/en/hooks#matcher-patterns) for how plain names and regular expressions are evaluated.580The `"Edit|Write"` matcher fires only when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool. See [Matcher patterns](/en/hooks#matcher-patterns) for how plain names and regular expressions are evaluated.

548 581 

582<Note>

583 Claude can also create or modify files by running shell commands through the `Bash` tool. If your hook must see every file change, such as for compliance scanning or audit logging, add a [`Stop`](/en/hooks#stop) hook that scans the working tree once per turn. For per-call coverage instead, also match `Bash` and have your script list modified and untracked files with `git status --porcelain`.

584</Note>

585 

549Each event type matches on a specific field:586Each event type matches on a specific field:

550 587 

551| Event | What the matcher filters | Example matcher values |588| Event | What the matcher filters | Example matcher values |

552| :--------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |589| :-------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |

553| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |590| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

554| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |591| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

592| `Setup` | which CLI flag triggered setup | `init`, `maintenance` |

555| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |593| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

556| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |594| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response` |

557| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |595| `SubagentStart` | agent type | `general-purpose`, `Explore`, `Plan`, or custom agent names |

558| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |596| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |

559| `SubagentStop` | agent type | same values as `SubagentStart` |597| `SubagentStop` | agent type | same values as `SubagentStart` |

560| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |598| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

561| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |599| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |

562| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |600| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |

563| `Elicitation` | MCP server name | your configured MCP server names |601| `Elicitation` | MCP server name | your configured MCP server names |

564| `ElicitationResult` | MCP server name | same values as `Elicitation` |602| `ElicitationResult` | MCP server name | same values as `Elicitation` |

565| `FileChanged` | literal filenames to watch (see [FileChanged](/en/hooks#filechanged)) | `.envrc\|.env` |603| `FileChanged` | literal filenames to watch (see [FileChanged](/en/hooks#filechanged)) | `.envrc\|.env` |

566| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged` | no matcher support | always fires on every occurrence |604| `UserPromptExpansion` | command name | your skill or command names |

605| `UserPromptSubmit`, `PostToolBatch`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged` | no matcher support | always fires on every occurrence |

567 606 

568A few more examples showing matchers on different event types:607A few more examples showing matchers on different event types:

569 608 


645 The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.684 The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.

646</Note>685</Note>

647 686 

648The `if` field uses [permission rule syntax](/en/permissions) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches. This goes beyond `matcher`, which filters at the group level by tool name only.687The `if` field uses [permission rule syntax](/en/permissions) to filter hooks by tool name and arguments together, so the hook process only spawns when the tool call matches, or when a Bash command is too complex to parse. This goes beyond `matcher`, which filters at the group level by tool name only.

649 688 

650For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:689For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:

651 690 


668}707}

669```708```

670 709 

671The hook process only spawns when the Bash command starts with `git`. Other Bash commands skip this handler entirely. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported.710The hook process only spawns when a subcommand of the Bash command matches `git *`, or when the command is too complex to parse into subcommands. For compound commands like `npm test && git push`, Claude Code evaluates each subcommand and fires the hook because `git push` matches. The `if` field accepts the same patterns as permission rules: `"Bash(git *)"`, `"Edit(*.ts)"`, and so on. To match multiple tool names, use separate handlers each with its own `if` value, or match at the `matcher` level where pipe alternation is supported.

672 711 

673`if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.712`if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.

674 713 


696The model's only job is to return a yes/no decision as JSON:735The model's only job is to return a yes/no decision as JSON:

697 736 

698* `"ok": true`: the action proceeds737* `"ok": true`: the action proceeds

699* `"ok": false`: the action is blocked. The model's `"reason"` is fed back to Claude so it can adjust.738* `"ok": false`: what happens depends on the event:

739 * `Stop` and `SubagentStop`: the `reason` is fed back to Claude so it keeps working

740 * `PreToolUse`: the tool call is denied and the `reason` is returned to Claude as the tool error, so it can adjust and continue

741 * `PostToolUse`, `PostToolBatch`, `UserPromptSubmit`, and `UserPromptExpansion`: the turn ends and the `reason` appears in the chat as a warning line

700 742 

701This 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:743This 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:

702 744 


721 763 

722## Agent-based hooks764## Agent-based hooks

723 765 

766<Warning>

767 Agent hooks are experimental. Behavior and configuration may change in future releases. For production workflows, prefer [command hooks](/en/hooks#command-hook-fields).

768</Warning>

769 

724When 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.770When 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.

725 771 

726Agent 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.772Agent 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.

Details

100 100 

101### Work across branches101### Work across branches

102 102 

103Each Claude Code conversation is a session tied to your current directory. When you resume, you only see sessions from that directory.103Each Claude Code conversation is a session tied to your current directory. The `/resume` picker shows sessions from the current worktree by default, with keyboard shortcuts to widen the list to other worktrees or projects. See [Manage sessions](/en/sessions#use-the-session-picker) for the full list of picker shortcuts and how name resolution works.

104 104 

105Claude sees your current branch's files. When you switch branches, Claude sees the new branch's files, but your conversation history stays the same. Claude remembers what you discussed even after switching.105Claude sees your current branch's files. When you switch branches, Claude sees the new branch's files, but your conversation history stays the same. Claude remembers what you discussed even after switching.

106 106 

107Since sessions are tied to directories, you can run parallel Claude sessions by using [git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees), which create separate directories for individual branches.107Since sessions are tied to directories, you can run parallel Claude sessions by using [git worktrees](/en/worktrees), which create separate directories for individual branches.

108 108 

109### Resume or fork sessions109### Resume or fork sessions

110 110 

111When you resume a session with `claude --continue` or `claude --resume`, you pick up where you left off using the same session ID. New messages append to the existing conversation. Your full conversation history is restored, but session-scoped permissions are not. You'll need to re-approve those.111Resuming a session with `claude --continue` or `claude --resume` reopens it under the same session ID and appends new messages to the existing conversation. Forking with `--fork-session` or `/branch` copies the history into a new session ID, leaving the original unchanged.

112 112 

113<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/session-continuity.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=fa41d12bfb57579cabfeece907151d30" alt="Session continuity: resume continues the same session, fork creates a new branch with a new ID." width="560" height="280" data-path="images/session-continuity.svg" />113<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/session-continuity.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=fa41d12bfb57579cabfeece907151d30" alt="Session continuity: resume continues the same session, fork creates a new branch with a new ID." width="560" height="280" data-path="images/session-continuity.svg" />

114 114 

115To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:115For the resume flags, the `/resume` picker, naming, and what happens when the same session is open in two terminals, see [Manage sessions](/en/sessions).

116 

117```bash theme={null}

118claude --continue --fork-session

119```

120 

121This creates a new session ID while preserving the conversation history up to that point. The original session remains unchanged. Like resume, forked sessions don't inherit session-scoped permissions.

122 

123**Same session in multiple terminals**: If you resume the same session in multiple terminals, both terminals write to the same session file. Messages from both get interleaved, like two people writing in the same notebook. Nothing corrupts, but the conversation becomes jumbled. Each terminal only sees its own messages during the session, but if you resume that session later, you'll see everything interleaved. For parallel work from the same starting point, use `--fork-session` to give each terminal its own clean session.

124 116 

125### The context window117### The context window

126 118 


142 134 

143Beyond compaction, you can use other features to control what loads into context.135Beyond compaction, you can use other features to control what loads into context.

144 136 

145[Skills](/en/skills) load on demand. Claude sees skill descriptions at session start, but the full content only loads when a skill is used. For skills you invoke manually, set `disable-model-invocation: true` to keep descriptions out of context until you need them.137[Skills](/en/skills) load on demand. Claude sees skill descriptions at session start, but the full content only loads when a skill is used. For skills you invoke manually, set `disable-model-invocation: true` to keep descriptions out of context until you need them. For skills you didn't write, use [`skillOverrides`](/en/skills#override-skill-visibility-from-settings) to do the same from settings.

146 138 

147[Subagents](/en/sub-agents) get their own fresh context, completely separate from your main conversation. Their work doesn't bloat your context. When done, they return a summary. This isolation is why subagents help with long sessions.139[Subagents](/en/sub-agents) get their own fresh context, completely separate from your main conversation. Their work doesn't bloat your context. When done, they return a summary. This isolation is why subagents help with long sessions.

148 140 

Details

11<Note>11<Note>

12 Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment.12 Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment.

13 13 

14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`, `Alt+T`) require configuring Option as Meta in your terminal:14 **macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal:

15 15 

16 * **iTerm2**: settings → Profiles → Keys → set Left/Right Option key to "Esc+"16 * **iTerm2**: Settings → Profiles → Keys → General → set Left/Right Option key to "Esc+"

17 * **Terminal.app**: settings → Profiles → Keyboard → check "Use Option as Meta Key"17 * **Apple Terminal**: Settings → Profiles → Keyboard → check "Use Option as Meta Key"

18 * **VS Code**: set `"terminal.integrated.macOptionIsMeta": true` in VS Code settings18 * **VS Code**: set `"terminal.integrated.macOptionIsMeta": true` in VS Code settings

19 19 

20 See [Terminal configuration](/en/terminal-config) for details.20 See [Terminal configuration](/en/terminal-config) for details.


23### General controls23### General controls

24 24 

25| Shortcut | Description | Context |25| Shortcut | Description | Context |

26| :------------------------------------------------ | :------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |26| :------------------------------------------------ | :------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

27| `Ctrl+C` | Cancel current input or generation | Standard interrupt |27| `Ctrl+C` | Cancel current input or generation | Standard interrupt |

28| `Ctrl+X Ctrl+K` | Kill all background agents. Press twice within 3 seconds to confirm | Background agent control |28| `Ctrl+X Ctrl+K` | Kill all background agents. Press twice within 3 seconds to confirm | Background agent control |

29| `Ctrl+D` | Exit Claude Code session | EOF signal |29| `Ctrl+D` | Exit Claude Code session | EOF signal |

30| `Ctrl+G` or `Ctrl+X Ctrl+E` | Open in default text editor | Edit your prompt or custom response in your default text editor. `Ctrl+X Ctrl+E` is the readline-native binding |30| `Ctrl+G` or `Ctrl+X Ctrl+E` | Open in default text editor | Edit your prompt or custom response in your default text editor. `Ctrl+X Ctrl+E` is the readline-native binding. Turn on Show last response in external editor in `/config` to prepend Claude's previous reply as `#`-commented context above your prompt; the comment block is stripped when you save |

31| `Ctrl+L` | Clear prompt input | Clears typed text, keeps conversation history |31| `Ctrl+L` | Redraw screen | Forces a full terminal redraw. Input and conversation history are kept. Use this to recover if the display becomes garbled or partially blank |

32| `Ctrl+O` | Toggle transcript viewer | Shows detailed tool usage and execution. Also expands MCP calls, which collapse to a single line like "Called slack 3 times" by default. In [fullscreen rendering](/en/fullscreen), cycles through three states: normal prompt, transcript mode, and focus view (last prompt + tool summary + response) |32| `Ctrl+O` | Toggle transcript viewer | Shows detailed tool usage and execution. Also expands MCP calls, which collapse to a single line like "Called slack 3 times" by default |

33| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |33| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |

34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt |34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Inserts an `[Image #N]` chip at the cursor so you can reference it positionally in your prompt |

35| `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 |36| `Ctrl+T` | Toggle task list | Show or hide the [task list](#task-list) in the terminal status area |

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

38| `Up/Down arrows` | Navigate command history | Recall previous inputs |38| `Up/Down arrows` or `Ctrl+P`/`Ctrl+N` | Move cursor or navigate command history | In multiline input, first moves the cursor within the prompt. Once the cursor is already on the top or bottom edge, pressing again navigates command history |

39| `Esc` + `Esc` | Rewind or summarize | Restore code and/or conversation to a previous point, or summarize from a selected message |39| `Esc` + `Esc` | Rewind or summarize | Restore code and/or conversation to a previous point, or summarize from a selected message |

40| `Shift+Tab` or `Alt+M` (some configurations) | Cycle permission modes | Cycle through `default`, `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](/en/permission-modes). |40| `Shift+Tab` or `Alt+M` (some configurations) | Cycle permission modes | Cycle through `default`, `acceptEdits`, `plan`, and any modes you have enabled, such as `auto` or `bypassPermissions`. See [permission modes](/en/permission-modes). |

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

42| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. On macOS, configure your terminal to send Option as Meta for this shortcut to work |42| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. {/* min-version: 2.1.132 */}As of v2.1.132 this shortcut works on macOS without configuring Option as Meta |

43| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |43| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |

44 44 

45### Text editing45### Text editing

46 46 

47| Shortcut | Description | Context |47| Shortcut | Description | Context |

48| :----------------------- | :------------------------------- | :------------------------------------------------------------------------------------------------------------ |48| :----------------------- | :----------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

49| `Ctrl+A` | Move cursor to start of current line | In multiline input, moves to the start of the current logical line |

50| `Ctrl+E` | Move cursor to end of current line | In multiline input, moves to the end of the current logical line |

49| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |51| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |

50| `Ctrl+U` | Delete from cursor to line start | Stores deleted text for pasting. Repeat to clear across lines in multiline input |52| `Ctrl+U` | Delete from cursor to line start | Stores deleted text for pasting. Repeat to clear across lines in multiline input. On macOS, terminal emulators including iTerm2 and Terminal.app map `Cmd+Backspace` to this shortcut |

51| `Ctrl+Y` | Paste deleted text | Paste text deleted with `Ctrl+K` or `Ctrl+U` |53| `Ctrl+W` | Delete previous word | Stores deleted text for pasting. On Windows, `Ctrl+Backspace` also deletes the previous word |

54| `Ctrl+Y` | Paste deleted text | Paste text deleted with `Ctrl+K`, `Ctrl+U`, or `Ctrl+W` |

52| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |55| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

53| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |56| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

54| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |57| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |


62### Multiline input65### Multiline input

63 66 

64| Method | Shortcut | Context |67| Method | Shortcut | Context |

65| :--------------- | :------------- | :------------------------------------------------------ |68| :--------------- | :------------- | :------------------------------------------------------------------------------------------------- |

66| Quick escape | `\` + `Enter` | Works in all terminals |69| Quick escape | `\` + `Enter` | Works in all terminals |

67| macOS default | `Option+Enter` | Default on macOS |70| Option key | `Option+Enter` | After enabling [Option as Meta](/en/terminal-config#enable-option-key-shortcuts-on-macos) on macOS |

68| Shift+Enter | `Shift+Enter` | Works out of the box in iTerm2, WezTerm, Ghostty, Kitty |71| Shift+Enter | `Shift+Enter` | Native in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, Windows Terminal |

69| Control sequence | `Ctrl+J` | Line feed character for multiline |72| Control sequence | `Ctrl+J` | Works in any terminal without configuration |

70| Paste mode | Paste directly | For code blocks, logs |73| Paste mode | Paste directly | For code blocks, logs |

71 74 

72<Tip>75<Tip>

73 Shift+Enter works without configuration in iTerm2, WezTerm, Ghostty, and Kitty. For other terminals (VS Code, Alacritty, Zed, Warp), run `/terminal-setup` to install the binding.76 Shift+Enter works without configuration in iTerm2, WezTerm, Ghostty, Kitty, Warp, Apple Terminal, and Windows Terminal. For VS Code, Cursor, Windsurf, Alacritty, and Zed, run `/terminal-setup` to install the binding.

74</Tip>77</Tip>

75 78 

76### Quick commands79### Quick commands


78| Shortcut | Description | Notes |81| Shortcut | Description | Notes |

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

80| `/` at start | Command or skill | See [commands](#commands) and [skills](/en/skills) |83| `/` at start | Command or skill | See [commands](#commands) and [skills](/en/skills) |

81| `!` at start | Bash mode | Run commands directly and add execution output to the session |84| `!` at start | Shell mode | Run commands directly and add execution output to the session |

82| `@` | File path mention | Trigger file path autocomplete |85| `@` | File path mention | Trigger file path autocomplete |

83 86 

84### Transcript viewer87### Transcript viewer


86When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).89When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).

87 90 

88| Shortcut | Description |91| Shortcut | Description |

89| :------------------- | :-------------------------------------------------------------------------------------- |92| :------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

90| `Ctrl+E` | Toggle show all content |93| `Ctrl+E` | Toggle show all content |

94| `[` | Write the full conversation to your terminal's native scrollback so `Cmd+F`, tmux copy mode, and other native tools can search it. Requires [fullscreen rendering](/en/fullscreen#search-and-review-the-conversation) |

95| `v` | Write the conversation to a temporary file and open it in `$VISUAL` or `$EDITOR`. Requires [fullscreen rendering](/en/fullscreen) |

91| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |96| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |

92 97 

93### Voice input98### Voice input

94 99 

95| Shortcut | Description | Notes |100| Shortcut | Description | Notes |

96| :----------- | :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |101| :------------------ | :-------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

97| Hold `Space` | Push-to-talk dictation | Requires [voice dictation](/en/voice-dictation) to be enabled. Transcript inserts at cursor. [Rebindable](/en/voice-dictation#rebind-the-push-to-talk-key) |102| Hold or tap `Space` | Voice dictation | Requires [voice dictation](/en/voice-dictation) to be enabled. Hold to record, or run `/voice tap` for tap-to-toggle. [Rebindable](/en/voice-dictation#rebind-the-dictation-key) |

98 103 

99## Commands104## Commands

100 105 


109### Mode switching114### Mode switching

110 115 

111| Command | Action | From mode |116| Command | Action | From mode |

112| :------ | :-------------------------- | :-------- |117| :------ | :------------------------------------ | :------------- |

113| `Esc` | Enter NORMAL mode | INSERT |118| `Esc` | Enter NORMAL mode | INSERT, VISUAL |

114| `i` | Insert before cursor | NORMAL |119| `i` | Insert before cursor | NORMAL |

115| `I` | Insert at beginning of line | NORMAL |120| `I` | Insert at beginning of line | NORMAL |

116| `a` | Insert after cursor | NORMAL |121| `a` | Insert after cursor | NORMAL |

117| `A` | Insert at end of line | NORMAL |122| `A` | Insert at end of line | NORMAL |

118| `o` | Open line below | NORMAL |123| `o` | Open line below | NORMAL |

119| `O` | Open line above | NORMAL |124| `O` | Open line above | NORMAL |

125| `v` | Start character-wise visual selection | NORMAL |

126| `V` | Start line-wise visual selection | NORMAL |

120 127 

121### Navigation (NORMAL mode)128### Navigation (NORMAL mode)

122 129 

123| Command | Action |130| Command | Action |

124| :-------------- | :-------------------------------------------------- |131| :-------------- | :-------------------------------------------------- |

125| `h`/`j`/`k`/`l` | Move left/down/up/right |132| `h`/`j`/`k`/`l` | Move left/down/up/right |

133| `Space` | Move right |

126| `w` | Next word |134| `w` | Next word |

127| `e` | End of word |135| `e` | End of word |

128| `b` | Previous word |136| `b` | Previous word |


160| `>>` | Indent line |168| `>>` | Indent line |

161| `<<` | Dedent line |169| `<<` | Dedent line |

162| `J` | Join lines |170| `J` | Join lines |

171| `u` | Undo |

163| `.` | Repeat last change |172| `.` | Repeat last change |

164 173 

165### Text objects (NORMAL mode)174### Text objects (NORMAL mode)


176| `i[`/`a[` | Inner/around brackets |185| `i[`/`a[` | Inner/around brackets |

177| `i{`/`a{` | Inner/around braces |186| `i{`/`a{` | Inner/around braces |

178 187 

188### Visual mode

189 

190Press `v` for character-wise selection or `V` for line-wise selection. Motions extend the selection, and operators act on it directly.

191 

192| Command | Action |

193| :--------------- | :--------------------------------------------------- |

194| `d`/`x` | Delete selection |

195| `y` | Yank selection |

196| `c`/`s` | Change selection |

197| `p` | Replace selection with register contents |

198| `r{char}` | Replace every selected character with `{char}` |

199| `~`/`u`/`U` | Toggle, lowercase, or uppercase selection |

200| `>`/`<` | Indent or dedent selected lines |

201| `J` | Join selected lines |

202| `o` | Swap cursor and anchor |

203| `iw`/`aw`/`i"`/… | Select a text object |

204| `v`/`V` | Toggle between character-wise and line-wise, or exit |

205 

206Block-wise visual mode with `Ctrl+V` is not supported.

207 

179## Command history208## Command history

180 209 

181Claude Code maintains command history for the current session:210Claude Code maintains command history for the current session:


1921. **Start search**: press `Ctrl+R` to activate reverse history search2211. **Start search**: press `Ctrl+R` to activate reverse history search

1932. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results2222. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results

1943. **Navigate matches**: press `Ctrl+R` again to cycle through older matches2233. **Navigate matches**: press `Ctrl+R` again to cycle through older matches

1954. **Accept match**:2244. **Change scope**: search defaults to prompts from all projects. Press `Ctrl+S` to cycle the scope through this session, this project, and all projects

2255. **Accept match**:

196 * Press `Tab` or `Esc` to accept the current match and continue editing226 * Press `Tab` or `Esc` to accept the current match and continue editing

197 * Press `Enter` to accept and execute the command immediately227 * Press `Enter` to accept and execute the command immediately

1985. **Cancel search**:2286. **Cancel search**:

199 * Press `Ctrl+C` to cancel and restore your original input229 * Press `Ctrl+C` to cancel and restore your original input

200 * Press `Backspace` on empty search to cancel230 * Press `Backspace` on empty search to cancel

201 231 


231* Development servers261* Development servers

232* Long-running processes (docker, terraform)262* Long-running processes (docker, terraform)

233 263 

234### Bash mode with `!` prefix264### Shell mode with `!` prefix

235 265 

236Run bash commands directly without going through Claude by prefixing your input with `!`:266Run shell commands directly without going through Claude by prefixing your input with `!`:

237 267 

238```bash theme={null}268```bash theme={null}

239! npm test269! npm test


241! ls -la271! ls -la

242```272```

243 273 

244Bash mode:274Shell mode:

245 275 

246* Adds the command and its output to the conversation context276* Adds the command and its output to the conversation context

247* Shows real-time progress and output277* Shows real-time progress and output


249* Does not require Claude to interpret or approve the command279* Does not require Claude to interpret or approve the command

250* Supports history-based autocomplete: type a partial command and press **Tab** to complete from previous `!` commands in the current project280* Supports history-based autocomplete: type a partial command and press **Tab** to complete from previous `!` commands in the current project

251* Exit with `Escape`, `Backspace`, or `Ctrl+U` on an empty prompt281* Exit with `Escape`, `Backspace`, or `Ctrl+U` on an empty prompt

252* Pasting text that starts with `!` into an empty prompt enters bash mode automatically, matching typed `!` behavior282* Pasting text that starts with `!` into an empty prompt enters shell mode automatically, matching typed `!` behavior

253 283 

254This is useful for quick shell operations while maintaining conversation context.284This is useful for quick shell operations while maintaining conversation context.

255 285 


259 289 

260After 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.290After 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.

261 291 

262* Press **Tab** or **Right arrow** to accept the suggestion, or press **Enter** to accept and submit292* Press **Tab** or **Right arrow** to place the suggestion in the prompt input, then **Enter** to submit

263* Start typing to dismiss it293* Start typing to dismiss it

264 294 

265The 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.295The 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.


295 325 

296When 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.326When 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.

297 327 

298* Press `Ctrl+T` to toggle the task list view. The display shows up to 10 tasks at a time328* Press `Ctrl+T` to toggle the task list view. The display shows up to 5 tasks at a time

299* To see all tasks or clear them, ask Claude directly: "show me all tasks" or "clear all tasks"329* To see all tasks or clear them, ask Claude directly: "show me all tasks" or "clear all tasks"

300* Tasks persist across context compactions, helping Claude stay organized on larger projects330* Tasks persist across context compactions, helping Claude stay organized on larger projects

301* 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`331* 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`

302 332 

333## Session recap

334 

335When you return to the terminal after stepping away, Claude Code shows a one-line recap of what happened in the session so far. The recap generates in the background once at least three minutes have passed since the last completed turn and the terminal is unfocused, so it's ready when you switch back. Recaps only appear once the session has at least three turns, and never twice in a row.

336 

337Run `/recap` to generate a summary on demand. To turn automatic recaps off, open `/config` and disable **Session recap**.

338 

339Session recap is on by default for every plan and provider. The recap is always skipped in non-interactive mode.

340 

303## PR review status341## PR review status

304 342 

305When 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:343When 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:

jetbrains.md +72 −35

Details

21 21 

22## Features22## Features

23 23 

24* **Quick launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UI24* **Quick launch**: use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UI

25* **Diff viewing**: Code changes can be displayed directly in the IDE diff viewer instead of the terminal25* **Diff viewing**: code changes can be displayed directly in the IDE diff viewer instead of the terminal

26* **Selection context**: The current selection/tab in the IDE is automatically shared with Claude Code26* **Selection context**: the current selection or tab in the IDE is automatically shared with Claude Code

27* **File reference shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references (for example, @File#L1-99)27* **File reference shortcuts**: use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references such as `@src/auth.ts#L1-99`

28* **Diagnostic sharing**: Diagnostic errors (lint, syntax, etc.) from the IDE are automatically shared with Claude as you work28* **Diagnostic sharing**: diagnostic errors from the IDE, such as lint and syntax errors, are automatically shared with Claude as you work

29 29 

30## Installation30## Installation

31 31 

32### Marketplace Installation32### Marketplace installation

33 33 

34Find and install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains marketplace and restart your IDE.34Find and install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains marketplace and restart your IDE.

35 35 

36If you haven't installed Claude Code yet, see [our quickstart guide](/en/quickstart) for installation instructions.36If you haven't installed Claude Code yet, see the [quickstart guide](/en/quickstart) for installation instructions.

37 37 

38<Note>38<Note>

39 After installing the plugin, you may need to restart your IDE completely for it to take effect.39 After installing the plugin, you may need to restart your IDE completely for it to take effect.


41 41 

42## Usage42## Usage

43 43 

44### From Your IDE44### From your IDE

45 45 

46Run `claude` from your IDE's integrated terminal, and all integration features will be active.46Run `claude` from your IDE's integrated terminal, and all integration features will be active.

47 47 

48### From External Terminals48### From external terminals

49 49 

50Use the `/ide` command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features:50Use the `/ide` command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features:

51 51 


61 61 

62## Configuration62## Configuration

63 63 

64### Claude Code Settings64### Claude Code settings

65 65 

66Configure IDE integration through Claude Code's settings:66Configure IDE integration through Claude Code's settings:

67 67 

681. Run `claude`681. Run `claude`

692. Enter the `/config` command692. Enter the `/config` command

703. Set the diff tool to `auto` for automatic IDE detection703. Set the diff tool to `auto` to show diffs in the IDE, or `terminal` to keep them in the terminal

71 71 

72### Plugin Settings72### Plugin settings

73 73 

74Configure the Claude Code plugin by going to **Settings → Tools → Claude Code \[Beta]**:74Configure the Claude Code plugin by going to **Settings → Tools → Claude Code \[Beta]**:

75 75 

76#### General Settings76#### General settings

77 77 

78* **Claude command**: Specify a custom command to run Claude (for example, `claude`, `/usr/local/bin/claude`, or `npx @anthropic-ai/claude-code`)78* **Claude command**: specify a custom command to run Claude, for example `claude`, `/usr/local/bin/claude`, or `npx @anthropic-ai/claude-code`

79* **Suppress notification for Claude command not found**: Skip notifications about not finding the Claude command79* **Suppress notification for Claude command not found**: skip notifications about not finding the Claude command

80* **Enable using Option+Enter for multi-line prompts** (macOS only): When enabled, Option+Enter inserts new lines in Claude Code prompts. Disable if experiencing issues with the Option key being captured unexpectedly (requires terminal restart)80* **Enable using Option+Enter for multi-line prompts**: on macOS only. When enabled, Option+Enter inserts new lines in Claude Code prompts. Disable if the Option key is being captured unexpectedly. Requires a terminal restart.

81* **Enable automatic updates**: Automatically check for and install plugin updates (applied on restart)81* **Enable automatic updates**: automatically check for and install plugin updates, applied on restart

82 82 

83<Tip>83<Tip>

84 For WSL users: Set `wsl -d Ubuntu -- bash -lic "claude"` as your Claude command (replace `Ubuntu` with your WSL distribution name)84 For WSL users: Set `wsl -d Ubuntu -- bash -lic "claude"` as your Claude command (replace `Ubuntu` with your WSL distribution name)

85</Tip>85</Tip>

86 86 

87#### ESC Key Configuration87#### ESC key configuration

88 88 

89If the ESC key doesn't interrupt Claude Code operations in JetBrains terminals:89If the ESC key doesn't interrupt Claude Code operations in JetBrains terminals:

90 90 


96 96 

97This allows the ESC key to properly interrupt Claude Code operations.97This allows the ESC key to properly interrupt Claude Code operations.

98 98 

99## Special Configurations99## Special configurations

100 100 

101### Remote Development101### Remote development

102 102 

103<Warning>103<Warning>

104 When using JetBrains Remote Development, you must install the plugin in the remote host via **Settings → Plugin (Host)**.104 When using JetBrains Remote Development, you must install the plugin in the remote host via **Settings → Plugin (Host)**.


106 106 

107The plugin must be installed on the remote host, not on your local client machine.107The plugin must be installed on the remote host, not on your local client machine.

108 108 

109### WSL Configuration109### WSL configuration

110 110 

111<Warning>111If you're using Claude Code on WSL2 with a JetBrains IDE and see "No available IDEs detected", the cause is usually WSL2's NAT networking or Windows Firewall blocking the connection between WSL2 and the IDE running on the Windows host. WSL1 uses the host's network directly and isn't affected.

112 WSL users may need additional configuration for IDE detection to work properly. See our [WSL troubleshooting guide](/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2) for detailed setup instructions.112 

113</Warning>113#### Allow WSL2 traffic through Windows Firewall

114 

115This is the recommended fix because it keeps your existing WSL2 networking mode.

116 

117<Steps>

118 <Step title="Find your WSL2 IP address">

119 From inside your WSL shell, run:

120 

121 ```bash theme={null}

122 hostname -I

123 ```

124 

125 Note the subnet, for example `172.21.123.45` is in `172.21.0.0/16`.

126 </Step>

127 

128 <Step title="Create a firewall rule">

129 Open PowerShell as Administrator and run the following, adjusting the IP range to match your subnet:

114 130 

115WSL configuration may require:131 ```powershell theme={null}

132 New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16

133 ```

134 </Step>

116 135 

117* Proper terminal configuration136 <Step title="Restart your IDE and Claude Code">

118* Networking mode adjustments137 Close and reopen both so the new rule takes effect.

119* Firewall settings updates138 </Step>

139</Steps>

140 

141#### Switch WSL2 to mirrored networking

142 

143Mirrored networking requires Windows 11 22H2 or later. If you're on Windows 10, use the firewall rule above instead.

144 

145Add this to `.wslconfig` in your Windows user directory:

146 

147```ini theme={null}

148[wsl2]

149networkingMode=mirrored

150```

151 

152Then restart WSL with `wsl --shutdown` from PowerShell.

120 153 

121## Troubleshooting154## Troubleshooting

122 155 

123### Plugin Not Working156### Plugin not working

157 

158If the plugin is installed but Claude Code features don't appear in your IDE:

124 159 

125* Ensure you're running Claude Code from the project root directory160* Ensure you're running Claude Code from the project root directory

126* Check that the JetBrains plugin is enabled in the IDE settings161* Check that the JetBrains plugin is enabled in the IDE settings

127* Completely restart the IDE (you may need to do this multiple times)162* Completely restart the IDE (you may need to do this multiple times)

128* For Remote Development, ensure the plugin is installed in the remote host163* For Remote Development, ensure the plugin is installed in the remote host

129 164 

130### IDE Not Detected165### IDE not detected

166 

167If running `claude` shows "No available IDEs detected":

131 168 

132* Verify the plugin is installed and enabled169* Verify the plugin is installed and enabled

133* Restart the IDE completely170* Restart the IDE completely

134* Check that you're running Claude Code from the integrated terminal171* Check that you're running Claude Code from the integrated terminal

135* For WSL users, see the [WSL troubleshooting guide](/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2)172* For WSL users, see [WSL configuration](#wsl-configuration) above

136 173 

137### Command Not Found174### Command not found

138 175 

139If clicking the Claude icon shows "command not found":176If clicking the Claude icon shows "command not found":

140 177 

1411. Verify Claude Code is installed: `npm list -g @anthropic-ai/claude-code`1781. Verify Claude Code is installed by running `claude --version` in a terminal

1422. Configure the Claude command path in plugin settings1792. Configure the Claude command path in plugin settings

1433. For WSL users, use the WSL command format mentioned in the configuration section1803. For WSL users, use the WSL command format mentioned in the configuration section

144 181 

145## Security Considerations182## Security considerations

146 183 

147When Claude Code runs in a JetBrains IDE with auto-edit permissions enabled, it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in auto-edit mode and allow bypassing Claude Code's permission prompts for bash execution.184When Claude Code runs in a JetBrains IDE with auto-edit permissions enabled, it may be able to modify IDE configuration files that can be automatically executed by your IDE. This may increase the risk of running Claude Code in auto-edit mode and allow bypassing Claude Code's permission prompts for bash execution.

148 185 


152* Taking extra care to ensure Claude is only used with trusted prompts189* Taking extra care to ensure Claude is only used with trusted prompts

153* Being aware of which files Claude Code has access to modify190* Being aware of which files Claude Code has access to modify

154 191 

155For additional help, see our [troubleshooting guide](/en/troubleshooting).192For Claude Code installation or login problems outside the IDE, see [Troubleshoot installation and login](/en/troubleshoot-install).

keybindings.md +26 −14

Details

100Actions available in the `Chat` context:100Actions available in the `Chat` context:

101 101 

102| Action | Default | Description |102| Action | Default | Description |

103| :-------------------- | :------------------------ | :---------------------------------- |103| :-------------------- | :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |

104| `chat:cancel` | Escape | Cancel current input |104| `chat:cancel` | Escape | Cancel current input |

105| `chat:clearInput` | Ctrl+L | Clear prompt input |105| `chat:clearInput` | Ctrl+L | Force a full screen redraw, preserving input. In [fullscreen rendering](/en/fullscreen#clear-the-conversation), press twice within two seconds to run `/clear` |

106| `chat:clearScreen` | Cmd+K | In [fullscreen rendering](/en/fullscreen#clear-the-conversation), press twice within two seconds to run `/clear` |

106| `chat:killAgents` | Ctrl+X Ctrl+K | Kill all background agents |107| `chat:killAgents` | Ctrl+X Ctrl+K | Kill all background agents |

107| `chat:cycleMode` | Shift+Tab\* | Cycle permission modes |108| `chat:cycleMode` | Shift+Tab\* | Cycle permission modes |

108| `chat:modelPicker` | Cmd+P / Meta+P | Open model picker |109| `chat:modelPicker` | Meta+P | Open model picker |

109| `chat:fastMode` | Meta+O | Toggle fast mode |110| `chat:fastMode` | Meta+O | Toggle fast mode |

110| `chat:thinkingToggle` | Cmd+T / Meta+T | Toggle extended thinking |111| `chat:thinkingToggle` | Meta+T | Toggle extended thinking |

111| `chat:submit` | Enter | Submit message |112| `chat:submit` | Enter | Submit message |

112| `chat:newline` | Ctrl+J | Insert a newline without submitting |113| `chat:newline` | Ctrl+J | Insert a newline without submitting |

113| `chat:undo` | Ctrl+\_, Ctrl+Shift+- | Undo last action |114| `chat:undo` | Ctrl+\_, Ctrl+Shift+- | Undo last action |


166Actions available in the `HistorySearch` context:167Actions available in the `HistorySearch` context:

167 168 

168| Action | Default | Description |169| Action | Default | Description |

169| :---------------------- | :---------- | :----------------------- |170| :------------------------- | :---------- | :---------------------------------------- |

170| `historySearch:next` | Ctrl+R | Next match |171| `historySearch:next` | Ctrl+R | Next match |

171| `historySearch:accept` | Escape, Tab | Accept selection |172| `historySearch:accept` | Escape, Tab | Accept selection |

172| `historySearch:cancel` | Ctrl+C | Cancel search |173| `historySearch:cancel` | Ctrl+C | Cancel search |

173| `historySearch:execute` | Enter | Execute selected command |174| `historySearch:execute` | Enter | Execute selected command |

175| `historySearch:cycleScope` | Ctrl+S | Cycle scope: session, project, everywhere |

174 176 

175### Task actions177### Task actions

176 178 


280Actions available in the `Plugin` context:282Actions available in the `Plugin` context:

281 283 

282| Action | Default | Description |284| Action | Default | Description |

283| :--------------- | :------ | :----------------------- |285| :---------------- | :------ | :------------------------------------------------------------------------- |

284| `plugin:toggle` | Space | Toggle plugin selection |286| `plugin:toggle` | Space | Toggle plugin selection |

285| `plugin:install` | I | Install selected plugins |287| `plugin:install` | I | Install selected plugins |

288| `plugin:favorite` | F | Favorite the selected plugin so it sorts near the top of the Installed tab |

286 289 

287### Settings actions290### Settings actions

288 291 


307Actions available in the `Chat` context when [voice dictation](/en/voice-dictation) is enabled:310Actions available in the `Chat` context when [voice dictation](/en/voice-dictation) is enabled:

308 311 

309| Action | Default | Description |312| Action | Default | Description |

310| :----------------- | :------ | :----------------------- |313| :----------------- | :------ | :------------------------------------------------------- |

311| `voice:pushToTalk` | Space | Hold to dictate a prompt |314| `voice:pushToTalk` | Space | Dictate a prompt. Hold or tap depending on `/voice` mode |

312 315 

313### Scroll actions316### Scroll actions

314 317 

315Actions available in the `Scroll` context when [fullscreen rendering](/en/fullscreen) is enabled:318Actions available in the `Scroll` context when [fullscreen rendering](/en/fullscreen) is enabled:

316 319 

317| Action | Default | Description |320| Action | Default | Description |

318| :-------------------- | :------------------- | :------------------------------------------------------------------------------------------------------ |321| :-------------------------- | :------------------- | :-------------------------------------------------------------------------------------------------------- |

319| `scroll:lineUp` | (unbound) | Scroll up one line. Mouse wheel scrolling triggers this action |322| `scroll:lineUp` | (unbound) | Scroll up one line. Mouse wheel scrolling triggers this action |

320| `scroll:lineDown` | (unbound) | Scroll down one line. Mouse wheel scrolling triggers this action |323| `scroll:lineDown` | (unbound) | Scroll down one line. Mouse wheel scrolling triggers this action |

321| `scroll:pageUp` | PageUp | Scroll up half the viewport height |324| `scroll:pageUp` | PageUp | Scroll up half the viewport height |


328| `scroll:fullPageDown` | (unbound) | Scroll down the full viewport height |331| `scroll:fullPageDown` | (unbound) | Scroll down the full viewport height |

329| `selection:copy` | Ctrl+Shift+C / Cmd+C | Copy the selected text to the clipboard |332| `selection:copy` | Ctrl+Shift+C / Cmd+C | Copy the selected text to the clipboard |

330| `selection:clear` | (unbound) | Clear the active text selection |333| `selection:clear` | (unbound) | Clear the active text selection |

334| `selection:extendLeft` | Shift+Left | Extend the active selection one column left |

335| `selection:extendRight` | Shift+Right | Extend the active selection one column right |

336| `selection:extendUp` | Shift+Up | Extend the active selection one row up. Scrolls the viewport when the selection reaches the top edge |

337| `selection:extendDown` | Shift+Down | Extend the active selection one row down. Scrolls the viewport when the selection reaches the bottom edge |

338| `selection:extendLineStart` | Shift+Home | Extend the active selection to the start of the line |

339| `selection:extendLineEnd` | Shift+End | Extend the active selection to the end of the line |

331 340 

332## Keystroke syntax341## Keystroke syntax

333 342 


336Use modifier keys with the `+` separator:345Use modifier keys with the `+` separator:

337 346 

338* `ctrl` or `control` - Control key347* `ctrl` or `control` - Control key

339* `alt`, `opt`, or `option` - Alt/Option key

340* `shift` - Shift key348* `shift` - Shift key

341* `meta`, `cmd`, or `command` - Meta/Command key349* `alt`, `opt`, `option`, or `meta` - Alt key on Windows and Linux, Option key on macOS

350* `cmd`, `command`, `super`, or `win` - Command key on macOS, Windows key on Windows, Super key on Linux

351 

352The `cmd` group is only detected in terminals that report the Super modifier, such as those supporting the Kitty keyboard protocol or xterm's `modifyOtherKeys` mode. Most terminals do not send it, so use `ctrl` or `meta` for bindings you want to work everywhere.

342 353 

343For example:354For example:

344 355 

345```text theme={null}356```text theme={null}

346ctrl+k Single key with modifier357ctrl+k Ctrl + K

347shift+tab Shift + Tab358shift+tab Shift + Tab

348meta+p Command/Meta + P359meta+p Option + P on macOS, Alt + P elsewhere

349ctrl+shift+c Multiple modifiers360ctrl+shift+c Multiple modifiers

350```361```

351 362 


413These shortcuts cannot be rebound:424These shortcuts cannot be rebound:

414 425 

415| Shortcut | Reason |426| Shortcut | Reason |

416| :------- | :--------------------------------------------- |427| :-------- | :--------------------------------------------- |

417| Ctrl+C | Hardcoded interrupt/cancel |428| Ctrl+C | Hardcoded interrupt/cancel |

418| Ctrl+D | Hardcoded exit |429| Ctrl+D | Hardcoded exit |

419| Ctrl+M | Identical to Enter in terminals (both send CR) |430| Ctrl+M | Identical to Enter in terminals (both send CR) |

431| Caps Lock | Not delivered to terminal applications |

420 432 

421## Terminal conflicts433## Terminal conflicts

422 434 

llm-gateway.md +10 −2

Details

45| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |45| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

46| `X-Claude-Code-Session-Id` | A unique identifier for the current Claude Code session. Proxies can use this to aggregate all API requests from a single session without parsing the request body. |46| `X-Claude-Code-Session-Id` | A unique identifier for the current Claude Code session. Proxies can use this to aggregate all API requests from a single session without parsing the request body. |

47 47 

48Claude Code also prepends a short attribution block to the system prompt containing the client version and a fingerprint derived from the conversation. The Anthropic API strips this block before processing, so it does not affect first-party prompt caching. If your gateway implements its own prompt cache keyed on the full request body, set [`CLAUDE_CODE_ATTRIBUTION_HEADER=0`](/en/env-vars) to omit it.

49 

48## Configuration50## Configuration

49 51 

50### Model selection52### Model selection

51 53 

52By default, Claude Code will use standard model names for the selected API format.54By default, Claude Code uses standard model names for the selected API format.

55 

56When `ANTHROPIC_BASE_URL` points at a gateway that exposes the Anthropic Messages format, Claude Code can query the gateway's `/v1/models` endpoint at startup and add the returned models to the `/model` picker. Set `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` to enable this. Discovery is off by default so that gateways backed by a shared API key do not surface every model the key can access to every user. Each discovered entry is labeled "From gateway" and uses the `display_name` field from the response when one is provided. This requires Claude Code v2.1.129 or later.

57 

58Discovery applies only to the Anthropic Messages format. It does not run for Bedrock or Vertex pass-through endpoints, and it does not run when `ANTHROPIC_BASE_URL` is unset or points at `api.anthropic.com`.

59 

60The discovery request authenticates the same way as inference requests: it sends `ANTHROPIC_AUTH_TOKEN` as a bearer token, or `ANTHROPIC_API_KEY` as the `x-api-key` header when no auth token is set, along with any headers from `ANTHROPIC_CUSTOM_HEADERS`. Only models whose ID begins with `claude` or `anthropic` are added to the picker. Results are cached to `~/.claude/cache/gateway-models.json` and refreshed on each startup. If the request fails or the gateway does not implement `/v1/models`, the picker falls back to the cached list from the previous startup or to the built-in model list.

53 61 

54If you have configured custom model names in your gateway, use the environment variables documented in [Model configuration](/en/model-config) to match your custom names.62If your gateway uses model names that do not match the discovery filter, use the environment variables documented in [Model configuration](/en/model-config) to add them manually.

55 63 

56## LiteLLM configuration64## LiteLLM configuration

57 65 

mcp.md +74 −26

Details

60 --header "Authorization: Bearer your-token"60 --header "Authorization: Bearer your-token"

61```61```

62 62 

63When configuring MCP servers via JSON in `.mcp.json`, `~/.claude.json`, or `claude mcp add-json`, the `type` field accepts `streamable-http` as an alias for `http`. The MCP specification uses the name `streamable-http` for this transport, so configurations copied from server documentation work without modification.

64 

63### Option 2: Add a remote SSE server65### Option 2: Add a remote SSE server

64 66 

65<Warning>67<Warning>


122/mcp124/mcp

123```125```

124 126 

127The `/mcp` panel shows the tool count next to each connected server and flags servers that advertise the tools capability but expose no tools.

128 

129The server name `workspace` is reserved for internal use. If your configuration defines a server with that name, Claude Code skips it at load time and shows a warning asking you to rename it.

130 

125### Dynamic tool updates131### Dynamic tool updates

126 132 

127Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server.133Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server.

128 134 

135### Automatic reconnection

136 

137If an HTTP or SSE server disconnects mid-session, Claude Code automatically reconnects with exponential backoff: up to five attempts, starting at a one-second delay and doubling each time. The server appears as pending in `/mcp` while reconnection is in progress. After five failed attempts the server is marked as failed and you can retry manually from `/mcp`. Stdio servers are local processes and are not reconnected automatically.

138 

139The same backoff applies when an HTTP or SSE server fails its initial connection at startup. As of v2.1.121, Claude Code retries the initial connection up to three times on transient errors such as a 5xx response, a connection refused, or a timeout, then marks the server as failed if it still cannot connect. Authentication and not-found errors are not retried because they require a configuration change to resolve.

140 

129### Push messages with channels141### Push messages with channels

130 142 

131An MCP server can also push messages directly into your session so Claude can react to external events like CI results, monitoring alerts, or chat messages. To enable this, your server declares the `claude/channel` capability and you opt it in with the `--channels` flag at startup. See [Channels](/en/channels) to use an officially supported channel, or [Channels reference](/en/channels-reference) to build your own.143An MCP server can also push messages directly into your session so Claude can react to external events like CI results, monitoring alerts, or chat messages. To enable this, your server declares the `claude/channel` capability and you opt it in with the `--channels` flag at startup. See [Channels](/en/channels) to use an officially supported channel, or [Channels reference](/en/channels-reference) to build your own.


143 * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication155 * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication

144</Tip>156</Tip>

145 157 

146<Warning>

147 **Windows Users**: On native Windows (not WSL), local MCP servers that use `npx` require the `cmd /c` wrapper to ensure proper execution.

148 

149 ```bash theme={null}

150 # This creates command="cmd" which Windows can execute

151 claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package

152 ```

153 

154 Without the `cmd /c` wrapper, you'll encounter "Connection closed" errors because Windows cannot directly execute `npx`. (See the note above for an explanation of the `--` parameter.)

155</Warning>

156 

157### Plugin-provided MCP servers158### Plugin-provided MCP servers

158 159 

159[Plugins](/en/plugins) can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured servers.160[Plugins](/en/plugins) can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured servers.


223 224 

224## MCP installation scopes225## MCP installation scopes

225 226 

226MCP servers can be configured at three scopes. The scope you choose controls which projects the server loads in and whether the configuration is shared with your team.227MCP servers can be configured at three scopes. The scope you choose controls which projects the server loads in and whether the configuration is shared with your team. Administrators can also deploy servers at the enterprise level via [managed configuration](#managed-mcp-configuration).

227 228 

228| Scope | Loads in | Shared with team | Stored in |229| Scope | Loads in | Shared with team | Stored in |

229| ------------------------- | -------------------- | ------------------------ | --------------------------- |230| ------------------------- | -------------------- | ------------------------ | --------------------------- |


394 395 

395### Example: Connect to GitHub for code reviews396### Example: Connect to GitHub for code reviews

396 397 

397```bash theme={null}398GitHub's remote MCP server authenticates with a GitHub personal access token passed as a header. To get one, open your [GitHub token settings](https://github.com/settings/personal-access-tokens), generate a new fine-grained token with access to the repositories you want Claude to work with, then add the server:

398claude mcp add --transport http github https://api.githubcopilot.com/mcp/

399```

400 399 

401Authenticate if needed by selecting "Authenticate" for GitHub:400```bash theme={null}

402 401claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \

403```text theme={null}402 --header "Authorization: Bearer YOUR_GITHUB_PAT"

404/mcp

405```403```

406 404 

407Then work with GitHub:405Then work with GitHub:


559 557 

560### Override OAuth metadata discovery558### Override OAuth metadata discovery

561 559 

562If your MCP server's standard OAuth metadata endpoints return errors but the server exposes a working OIDC endpoint, you can point Claude Code at a specific metadata URL to bypass the default discovery chain. By default, Claude Code first checks RFC 9728 Protected Resource Metadata at `/.well-known/oauth-protected-resource`, then falls back to RFC 8414 authorization server metadata at `/.well-known/oauth-authorization-server`.560Point Claude Code at a specific OAuth authorization server metadata URL to bypass the default discovery chain. Set `authServerMetadataUrl` when the MCP server's standard endpoints error, or when you want to route discovery through an internal proxy. By default, Claude Code first checks RFC 9728 Protected Resource Metadata at `/.well-known/oauth-protected-resource`, then falls back to RFC 8414 authorization server metadata at `/.well-known/oauth-authorization-server`.

563 561 

564Set `authServerMetadataUrl` in the `oauth` object of your server's config in `.mcp.json`:562Set `authServerMetadataUrl` in the `oauth` object of your server's config in `.mcp.json`:

565 563 


577}575}

578```576```

579 577 

580The URL must use `https://`. This option requires Claude Code v2.1.64 or later.578The URL must use `https://`. `authServerMetadataUrl` requires Claude Code v2.1.64 or later. The metadata URL's `scopes_supported` overrides the scopes the upstream server advertises.

579 

580### Restrict OAuth scopes

581 

582Set `oauth.scopes` to pin the scopes Claude Code requests during the authorization flow. This is the supported way to restrict an MCP server to a security-team-approved subset when the upstream authorization server advertises more scopes than you want to grant. The value is a single space-separated string, matching the `scope` parameter format in RFC 6749 §3.3.

583 

584```json theme={null}

585{

586 "mcpServers": {

587 "slack": {

588 "type": "http",

589 "url": "https://mcp.slack.com/mcp",

590 "oauth": {

591 "scopes": "channels:read chat:write search:read"

592 }

593 }

594 }

595}

596```

597 

598`oauth.scopes` takes precedence over both `authServerMetadataUrl` and the scopes the server discovers at `/.well-known`. Leave it unset to let the MCP server determine the requested scope set.

599 

600If the authorization server advertises `offline_access` in `scopes_supported`, Claude Code appends it to the pinned scopes so the access token can be refreshed without a new browser sign-in.

601 

602If the server later returns a 403 `insufficient_scope` for a tool call, Claude Code re-authenticates with the same pinned scopes. Widen `oauth.scopes` when a tool you need requires a scope outside the pin.

581 603 

582### Use dynamic headers for custom authentication604### Use dynamic headers for custom authentication

583 605 


705 727 

706<Steps>728<Steps>

707 <Step title="Configure MCP servers in Claude.ai">729 <Step title="Configure MCP servers in Claude.ai">

708 Add servers at [claude.ai/settings/connectors](https://claude.ai/settings/connectors). On Team and Enterprise plans, only admins can add servers.730 Add servers at [claude.ai/customize/connectors](https://claude.ai/customize/connectors). On Team and Enterprise plans, only admins can add servers.

709 </Step>731 </Step>

710 732 

711 <Step title="Authenticate the MCP server">733 <Step title="Authenticate the MCP server">


723 </Step>745 </Step>

724</Steps>746</Steps>

725 747 

748A server you've added in Claude Code takes [precedence](#scope-hierarchy-and-precedence) over a claude.ai connector that points at the same URL. When this happens, `/mcp` lists the connector as hidden and shows how to remove the duplicate if you'd rather use the connector.

749 

726To disable claude.ai MCP servers in Claude Code, set the `ENABLE_CLAUDEAI_MCP_SERVERS` environment variable to `false`:750To disable claude.ai MCP servers in Claude Code, set the `ENABLE_CLAUDEAI_MCP_SERVERS` environment variable to `false`:

727 751 

728```bash theme={null}752```bash theme={null}


910 934 

911### Configure tool search935### Configure tool search

912 936 

913Tool search is enabled by default: MCP tools are deferred and discovered on demand. When `ANTHROPIC_BASE_URL` points to a non-first-party host, tool search is disabled by default because most proxies do not forward `tool_reference` blocks. Set `ENABLE_TOOL_SEARCH` explicitly if your proxy does. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.937Tool search is enabled by default: MCP tools are deferred and discovered on demand. It is disabled by default on Vertex AI, which does not accept the tool search beta header, and when `ANTHROPIC_BASE_URL` points to a non-first-party host, since most proxies do not forward `tool_reference` blocks. Set `ENABLE_TOOL_SEARCH` explicitly to opt in. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.

914 938 

915Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:939Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:

916 940 

917| Value | Behavior |941| Value | Behavior |

918| :--------- | :----------------------------------------------------------------------------------------------------------------------------- |942| :--------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |

919| (unset) | All MCP tools deferred and loaded on demand. Falls back to loading upfront when `ANTHROPIC_BASE_URL` is a non-first-party host |943| (unset) | All MCP tools deferred and loaded on demand. Falls back to loading upfront on Vertex AI or when `ANTHROPIC_BASE_URL` is a non-first-party host |

920| `true` | All MCP tools deferred, including for non-first-party `ANTHROPIC_BASE_URL` |944| `true` | All MCP tools deferred, including on Vertex AI and for non-first-party `ANTHROPIC_BASE_URL` |

921| `auto` | Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise |945| `auto` | Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise |

922| `auto:<N>` | Threshold mode with a custom percentage, where `<N>` is 0-100 (e.g., `auto:5` for 5%) |946| `auto:<N>` | Threshold mode with a custom percentage, where `<N>` is 0-100 (e.g., `auto:5` for 5%) |

923| `false` | All MCP tools loaded upfront, no deferral |947| `false` | All MCP tools loaded upfront, no deferral |


942}966}

943```967```

944 968 

969### Exempt a server from deferral

970 

971If a server's tools should always be visible to Claude without a search step, set `alwaysLoad` to `true` in that server's configuration. Every tool from that server then loads into context at session start regardless of the `ENABLE_TOOL_SEARCH` setting. Use this for a small number of tools that Claude needs on every turn, since each upfront tool consumes context that would otherwise be available for your conversation.

972 

973The following `.mcp.json` entry exempts one HTTP server while leaving other servers deferred:

974 

975```json theme={null}

976{

977 "mcpServers": {

978 "core-tools": {

979 "type": "http",

980 "url": "https://mcp.example.com/mcp",

981 "alwaysLoad": true

982 }

983 }

984}

985```

986 

987The `alwaysLoad` field is available on all server types and requires Claude Code v2.1.121 or later. An MCP server can also mark individual tools as always-loaded by including `"anthropic/alwaysLoad": true` in the tool's `_meta` object, which has the same effect for that tool only.

988 

989Setting `alwaysLoad: true` also blocks startup until the server connects, capped at the standard 5-second connect timeout. This applies even when [`MCP_CONNECTION_NONBLOCKING=1`](/en/env-vars) is set, since the tools must be present when the first prompt is built. Other servers still connect in the background when nonblocking is enabled.

990 

945## Use MCP prompts as commands991## Use MCP prompts as commands

946 992 

947MCP servers can expose prompts that become available as commands in Claude Code.993MCP servers can expose prompts that become available as commands in Claude Code.


1110* `https://*.example.com/*` - Allow any subdomain of example.com1156* `https://*.example.com/*` - Allow any subdomain of example.com

1111* `http://localhost:*/*` - Allow any port on localhost1157* `http://localhost:*/*` - Allow any port on localhost

1112 1158 

1159Hostname matching is case-insensitive and ignores a trailing FQDN dot, matching DNS semantics. A pattern like `*://Mcp.Example.com/*` matches `https://mcp.example.com/api`, and `https://mcp.example.com.` is treated the same as `https://mcp.example.com`. Paths remain case-sensitive.

1160 

1113**Remote server behavior**:1161**Remote server behavior**:

1114 1162 

1115* When the allowlist contains **any** `serverUrl` entries, remote servers **must** match one of those URL patterns1163* When the allowlist contains **any** `serverUrl` entries, remote servers **must** match one of those URL patterns

memory.md +18 −5

Details

78 78 

79CLAUDE.md files are loaded into the context window at the start of every session, consuming tokens alongside your conversation. The [context window visualization](/en/context-window) shows where CLAUDE.md loads relative to the rest of the startup context. Because they're context rather than enforced configuration, how you write instructions affects how reliably Claude follows them. Specific, concise, well-structured instructions work best.79CLAUDE.md files are loaded into the context window at the start of every session, consuming tokens alongside your conversation. The [context window visualization](/en/context-window) shows where CLAUDE.md loads relative to the rest of the startup context. Because they're context rather than enforced configuration, how you write instructions affects how reliably Claude follows them. Specific, concise, well-structured instructions work best.

80 80 

81**Size**: target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence. If your instructions are growing large, split them using [imports](#import-additional-files) or [`.claude/rules/`](#organize-rules-with-claude/rules/) files.81**Size**: target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence. If your instructions are growing large, use [path-scoped rules](#path-specific-rules) so instructions load only when Claude works with matching files. You can also split content into [imports](#import-additional-files) for organization, though imported files still load and enter the context window at launch.

82 82 

83**Structure**: use markdown headers and bullets to group related instructions. Claude scans structure the same way readers do: organized sections are easier to follow than dense paragraphs.83**Structure**: use markdown headers and bullets to group related instructions. Claude scans structure the same way readers do: organized sections are easier to follow than dense paragraphs.

84 84 


132Use plan mode for changes under `src/billing/`.132Use plan mode for changes under `src/billing/`.

133```133```

134 134 

135A symlink also works if you don't need to add Claude-specific content:

136 

137```bash theme={null}

138ln -s AGENTS.md CLAUDE.md

139```

140 

141On Windows, creating a symlink requires Administrator privileges or Developer Mode, so use the `@AGENTS.md` import instead.

142 

143Running [`/init`](/en/commands) in a repo that already has an `AGENTS.md` reads it and incorporates the relevant parts into the generated `CLAUDE.md`. It also reads other tool configs like `.cursorrules` and `.windsurfrules`.

144 

135### How CLAUDE.md files load145### How CLAUDE.md files load

136 146 

137Claude Code reads CLAUDE.md files by walking up the directory tree from your current working directory, checking each directory along the way for `CLAUDE.md` and `CLAUDE.local.md` files. This means if you run Claude Code in `foo/bar/`, it loads instructions from `foo/bar/CLAUDE.md`, `foo/CLAUDE.md`, and any `CLAUDE.local.md` files alongside them.147Claude Code reads CLAUDE.md files by walking up the directory tree from your current working directory, checking each directory along the way for `CLAUDE.md` and `CLAUDE.local.md` files. This means if you run Claude Code in `foo/bar/`, it loads instructions from `foo/bar/CLAUDE.md`, `foo/CLAUDE.md`, and any `CLAUDE.local.md` files alongside them.

138 148 

139All discovered files are concatenated into context rather than overriding each other. Within each directory, `CLAUDE.local.md` is appended after `CLAUDE.md`, so when instructions conflict, your personal notes are the last thing Claude reads at that level.149All discovered files are concatenated into context rather than overriding each other. Across the directory tree, content is ordered from the filesystem root down to your working directory. For the `foo/bar/` example, `foo/CLAUDE.md` appears in context before `foo/bar/CLAUDE.md`, so instructions closer to where you launched Claude are read last. Within each directory, `CLAUDE.local.md` is appended after `CLAUDE.md`, so your personal notes are the last thing Claude reads at that level.

140 150 

141Claude also discovers `CLAUDE.md` and `CLAUDE.local.md` files in subdirectories under your current working directory. Instead of loading them at launch, they are included when Claude reads files in those subdirectories.151Claude also discovers `CLAUDE.md` and `CLAUDE.local.md` files in subdirectories under your current working directory. Instead of loading them at launch, they are included when Claude reads files in those subdirectories.

142 152 


319 329 

320Each project gets its own memory directory at `~/.claude/projects/<project>/memory/`. The `<project>` path is derived from the git repository, so all worktrees and subdirectories within the same repo share one auto memory directory. Outside a git repo, the project root is used instead.330Each project gets its own memory directory at `~/.claude/projects/<project>/memory/`. The `<project>` path is derived from the git repository, so all worktrees and subdirectories within the same repo share one auto memory directory. Outside a git repo, the project root is used instead.

321 331 

322To store auto memory in a different location, set `autoMemoryDirectory` in your user or local settings:332To store auto memory in a different location, set `autoMemoryDirectory` in your user settings at `~/.claude/settings.json`:

323 333 

324```json theme={null}334```json theme={null}

325{335{


327}337}

328```338```

329 339 

330This setting is accepted from policy, local, and user settings. It is not accepted from project settings (`.claude/settings.json`) to prevent a shared project from redirecting auto memory writes to sensitive locations.340The value must be an absolute path or start with `~/`. This setting is accepted from policy and user settings, and from the `--settings` flag. It is not accepted from project or local settings, since both files live inside the project directory and a cloned repository could supply either to redirect auto memory writes to sensitive locations.

331 341 

332The directory contains a `MEMORY.md` entrypoint and optional topic files:342The directory contains a `MEMORY.md` entrypoint and optional topic files:

333 343 


378* Make instructions more specific. "Use 2-space indentation" works better than "format code nicely."388* Make instructions more specific. "Use 2-space indentation" works better than "format code nicely."

379* Look for conflicting instructions across CLAUDE.md files. If two files give different guidance for the same behavior, Claude may pick one arbitrarily.389* Look for conflicting instructions across CLAUDE.md files. If two files give different guidance for the same behavior, Claude may pick one arbitrarily.

380 390 

391If the instruction is something that must run at a specific point, such as before every commit or after each file edit, write it as a [hook](/en/hooks-guide) instead. Hooks execute as shell commands at fixed lifecycle events and apply regardless of what Claude decides to do.

392 

381For instructions you want at the system prompt level, use [`--append-system-prompt`](/en/cli-reference#system-prompt-flags). This must be passed every invocation, so it's better suited to scripts and automation than interactive use.393For instructions you want at the system prompt level, use [`--append-system-prompt`](/en/cli-reference#system-prompt-flags). This must be passed every invocation, so it's better suited to scripts and automation than interactive use.

382 394 

383<Tip>395<Tip>


390 402 

391### My CLAUDE.md is too large403### My CLAUDE.md is too large

392 404 

393Files over 200 lines consume more context and may reduce adherence. Move detailed content into separate files referenced with `@path` imports (see [Import additional files](#import-additional-files)), or split your instructions across `.claude/rules/` files.405Files over 200 lines consume more context and may reduce adherence. Use [path-scoped rules](#path-specific-rules) to load instructions only when Claude works with matching files, or trim content that isn't needed in every session. Splitting into [`@path` imports](#import-additional-files) helps organization but does not reduce context, since imported files load at launch.

394 406 

395### Instructions seem lost after `/compact`407### Instructions seem lost after `/compact`

396 408 


402 414 

403## Related resources415## Related resources

404 416 

417* [Debug your configuration](/en/debug-your-config): diagnose why CLAUDE.md or settings aren't taking effect

405* [Skills](/en/skills): package repeatable workflows that load on demand418* [Skills](/en/skills): package repeatable workflows that load on demand

406* [Settings](/en/settings): configure Claude Code behavior with settings files419* [Settings](/en/settings): configure Claude Code behavior with settings files

407* [Subagent memory](/en/sub-agents#enable-persistent-memory): let subagents maintain their own auto memory420* [Subagent memory](/en/sub-agents#enable-persistent-memory): let subagents maintain their own auto memory

Details

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

8 8 

9 9 

10 10<ContactSalesCard surface="foundry" />

11<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="foundry" />} />

12 11 

13## Prerequisites12## Prerequisites

14 13 


85 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."84 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."

86</Warning>85</Warning>

87 86 

88Set the model variables to match the deployment names you created in step 1:87Set the model variables to match the deployment names you created in step 1.

88 

89Without `ANTHROPIC_DEFAULT_OPUS_MODEL`, the `opus` alias on Foundry resolves to Opus 4.6. Set it to the Opus 4.7 ID to use the latest model:

89 90 

90```bash theme={null}91```bash theme={null}

91export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'92export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'

92export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'93export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

93export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'94export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'

94```95```

95 96 

96For 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.97For 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.

97 98 

99[Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) is enabled automatically. To request a 1-hour cache TTL instead of the 5-minute default, set the following variable; cache writes with a 1-hour TTL are billed at a higher rate:

100 

101```bash theme={null}

102export ENABLE_PROMPT_CACHING_1H=1

103```

104 

98## Azure RBAC configuration105## Azure RBAC configuration

99 106 

100The `Azure AI User` and `Cognitive Services User` default roles include all required permissions for invoking Claude models.107The `Azure AI User` and `Cognitive Services User` default roles include all required permissions for invoking Claude models.

model-config.md +104 −38

Details

17 * Foundry: a deployment name17 * Foundry: a deployment name

18 * Vertex: a version name18 * Vertex: a version name

19 19 

20<Note>

21 `ANTHROPIC_BASE_URL` changes where requests are sent, not which model answers them. To route Claude through an LLM gateway, see [LLM gateway configuration](/en/llm-gateway).

22</Note>

23 

20### Model aliases24### Model aliases

21 25 

22Model aliases provide a convenient way to select model settings without26Model aliases provide a convenient way to select model settings without


26| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |30| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

27| **`default`** | Special value that clears any model override and reverts to the recommended model for your account type. Not itself a model alias |31| **`default`** | Special value that clears any model override and reverts to the recommended model for your account type. Not itself a model alias |

28| **`best`** | Uses the most capable available model, currently equivalent to `opus` |32| **`best`** | Uses the most capable available model, currently equivalent to `opus` |

29| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.6) for daily coding tasks |33| **`sonnet`** | Uses the latest Sonnet model for daily coding tasks |

30| **`opus`** | Uses the latest Opus model (currently Opus 4.6) for complex reasoning tasks |34| **`opus`** | Uses the latest Opus model for complex reasoning tasks |

31| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |35| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |

32| **`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 |36| **`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 |

33| **`opus[1m]`** | Uses Opus with a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions |37| **`opus[1m]`** | Uses Opus with a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions |

34| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |38| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |

35 39 

36Aliases 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`.40On the Anthropic API, `opus` resolves to Opus 4.7 and `sonnet` resolves to Sonnet 4.6. On Bedrock, Vertex, and Foundry, `opus` resolves to Opus 4.6 and `sonnet` resolves to Sonnet 4.5; newer models are available on those providers by selecting the full model name explicitly or setting `ANTHROPIC_DEFAULT_OPUS_MODEL` or `ANTHROPIC_DEFAULT_SONNET_MODEL`.

41 

42Aliases point to the recommended version for your provider and update over time. To pin to a specific version, use the full model name (for example, `claude-opus-4-7`) or set the corresponding environment variable like `ANTHROPIC_DEFAULT_OPUS_MODEL`.

43 

44<Note>

45 Opus 4.7 requires Claude Code v2.1.111 or later. Run `claude update` to upgrade.

46</Note>

37 47 

38### Setting your model48### Setting your model

39 49 

40You can configure your model in several ways, listed in order of priority:50You can configure your model in several ways, listed in order of priority:

41 51 

421. **During session** - Use `/model <alias|name>` to switch models mid-session521. **During session** - Use `/model <alias|name>` to switch immediately, or run `/model` with no argument to open the picker. The picker asks for confirmation when the conversation has prior output, since the next response re-reads the full history without cached context

432. **At startup** - Launch with `claude --model <alias|name>`532. **At startup** - Launch with `claude --model <alias|name>`

443. **Environment variable** - Set `ANTHROPIC_MODEL=<alias|name>`543. **Environment variable** - Set `ANTHROPIC_MODEL=<alias|name>`

454. **Settings** - Configure permanently in your settings file using the `model`554. **Settings** - Configure permanently in your settings file using the `model`

46 field.56 field.

47 57 

58Your `/model` selection is saved to user settings and persists across restarts. As of v2.1.117, if the project's `.claude/settings.json` pins a different model, Claude Code also writes your choice to `.claude/settings.local.json` so it continues to apply in that project after a restart. Managed settings take precedence and reapply on the next launch.

59 

60When the active model at startup comes from project or managed settings rather than your own selection, the startup header shows which settings file set it. Run `/model` to override for the current session.

61 

48Example usage:62Example usage:

49 63 

50```bash theme={null}64```bash theme={null}


70 84 

71Enterprise administrators can use `availableModels` in [managed or policy settings](/en/settings#settings-files) to restrict which models users can select.85Enterprise administrators can use `availableModels` in [managed or policy settings](/en/settings#settings-files) to restrict which models users can select.

72 86 

73When `availableModels` is set, users cannot switch to models not in the list via `/model`, `--model` flag, Config tool, or `ANTHROPIC_MODEL` environment variable.87When `availableModels` is set, users cannot switch to models not in the list via `/model`, `--model` flag, or `ANTHROPIC_MODEL` environment variable.

74 88 

75```json theme={null}89```json theme={null}

76{90{


122 136 

123The behavior of `default` depends on your account type:137The behavior of `default` depends on your account type:

124 138 

125* **Max and Team Premium**: defaults to Opus 4.6139* **Max and Team Premium**: defaults to Opus 4.7

126* **Pro and Team Standard**: defaults to Sonnet 4.6140* **Pro, Team Standard, Enterprise, and Anthropic API**: defaults to Sonnet 4.6

127* **Enterprise**: Opus 4.6 is available but not the default141* **Bedrock, Vertex, and Foundry**: defaults to Sonnet 4.5

128 142 

129Claude Code may automatically fall back to Sonnet if you hit a usage threshold with Opus.143Claude Code may automatically fall back to Sonnet if you hit a usage threshold with Opus.

130 144 

145<Note>

146 On April 23, 2026, the default model for Enterprise pay-as-you-go and Anthropic API users will change to Opus 4.7. To keep a different default, set `ANTHROPIC_MODEL` or the `model` field in [server-managed settings](/en/server-managed-settings).

147</Note>

148 

131### `opusplan` model setting149### `opusplan` model setting

132 150 

133The `opusplan` model alias provides an automated hybrid approach:151The `opusplan` model alias provides an automated hybrid approach:


140This gives you the best of both worlds: Opus's superior reasoning for planning,158This gives you the best of both worlds: Opus's superior reasoning for planning,

141and Sonnet's efficiency for execution.159and Sonnet's efficiency for execution.

142 160 

161The plan-mode Opus phase runs with the standard 200K context window. The automatic 1M upgrade described in [Extended context](#extended-context) applies to the `opus` model setting and does not extend to `opusplan`.

162 

143### Adjust effort level163### Adjust effort level

144 164 

145[Effort levels](https://platform.claude.com/docs/en/build-with-claude/effort) control adaptive reasoning, which dynamically allocates thinking based on task complexity. Lower effort is faster and cheaper for straightforward tasks, while higher effort provides deeper reasoning for complex problems.165[Effort levels](https://platform.claude.com/docs/en/build-with-claude/effort) control adaptive reasoning, which lets the model decide whether and how much to think on each step based on task complexity. Lower effort is faster and cheaper for straightforward tasks, while higher effort provides deeper reasoning for complex problems.

166 

167Effort is supported on Opus 4.7, Opus 4.6, and Sonnet 4.6. The available levels depend on the model:

168 

169| Model | Levels |

170| :---------------------- | :-------------------------------------- |

171| Opus 4.7 | `low`, `medium`, `high`, `xhigh`, `max` |

172| Opus 4.6 and Sonnet 4.6 | `low`, `medium`, `high`, `max` |

146 173 

147Three levels persist across sessions: **low**, **medium**, and **high**. A fourth level, **max**, provides the deepest reasoning with no constraint on token spending, so responses are slower and cost more than at `high`. `max` is available on Opus 4.6 only and does not persist across sessions except through the `CLAUDE_CODE_EFFORT_LEVEL` environment variable.174If you set a level the active model does not support, Claude Code falls back to the highest supported level at or below the one you set. For example, `xhigh` runs as `high` on Opus 4.6.

148 175 

149The default effort level depends on your plan. Pro and Max subscribers default to medium effort. All other users default to high effort: API key, Team, Enterprise, and third-party provider (Bedrock, Vertex AI, Foundry) users.176As of v2.1.117, the default effort is `xhigh` on Opus 4.7 and `high` on Opus 4.6 and Sonnet 4.6.

150 177 

151Your plan's default suits most coding tasks. Raise effort for work that benefits from deeper reasoning, such as hard debugging problems or complex architectural decisions. Higher levels can cause the model to overthink routine work.178When you first run Opus 4.7, Claude Code applies `xhigh` even if you previously set a different effort level for Opus 4.6 or Sonnet 4.6. Run `/effort` again to choose a different level after switching.

152 179 

153For one-off deep reasoning without changing your session setting, include "ultrathink" in your prompt to trigger high effort for that turn. This has no effect if your session is already at high or max.180`low`, `medium`, `high`, and `xhigh` persist across sessions. `max` provides the deepest reasoning with no constraint on token spending and applies to the current session only, except when set through the `CLAUDE_CODE_EFFORT_LEVEL` environment variable.

154 181 

155**Setting effort:**182#### Choose an effort level

156 183 

157* **`/effort`**: run `/effort low`, `/effort medium`, `/effort high`, or `/effort max` to change the level, or `/effort auto` to reset to the model default184Each level trades token spend against capability. The default suits most coding tasks; adjust when you want a different balance.

185 

186| Level | When to use it |

187| :------- | :------------------------------------------------------------------------------------------------------------------------------------- |

188| `low` | Reserve for short, scoped, latency-sensitive tasks that are not intelligence-sensitive |

189| `medium` | Reduces token usage for cost-sensitive work that can trade off some intelligence |

190| `high` | Balances token usage and intelligence. Use as a minimum for intelligence-sensitive work, or to reduce token spend relative to `xhigh` |

191| `xhigh` | Best results for most coding and agentic tasks. Recommended default on Opus 4.7 |

192| `max` | Can improve performance on demanding tasks but may show diminishing returns and is prone to overthinking. Test before adopting broadly |

193 

194The effort scale is calibrated per model, so the same level name does not represent the same underlying value across models.

195 

196#### Use ultrathink for one-off deep reasoning

197 

198Include `ultrathink` anywhere in your prompt to request deeper reasoning on that turn without changing your session effort setting. Claude Code recognizes the keyword and adds an in-context instruction. The effort level sent to the API is unchanged. Other phrases such as "think", "think hard", and "think more" are passed through as ordinary prompt text and are not recognized as keywords.

199 

200#### Set the effort level

201 

202You can change effort through any of the following:

203 

204* **`/effort`**: run `/effort` with no arguments to open an interactive slider, `/effort` followed by a level name to set it directly, or `/effort auto` to reset to the model default

158* **In `/model`**: use left/right arrow keys to adjust the effort slider when selecting a model205* **In `/model`**: use left/right arrow keys to adjust the effort slider when selecting a model

159* **`--effort` flag**: pass `low`, `medium`, `high`, or `max` to set the level for a single session when launching Claude Code206* **`--effort` flag**: pass a level name to set it for a single session when launching Claude Code

160* **Environment variable**: set `CLAUDE_CODE_EFFORT_LEVEL` to `low`, `medium`, `high`, `max`, or `auto`207* **Environment variable**: set `CLAUDE_CODE_EFFORT_LEVEL` to a level name or `auto`

161* **Settings**: set `effortLevel` in your settings file to `"low"`, `"medium"`, or `"high"`208* **Settings**: set `effortLevel` in your settings file

162* **Skill and subagent frontmatter**: set `effort` in a [skill](/en/skills#frontmatter-reference) or [subagent](/en/sub-agents#supported-frontmatter-fields) markdown file to override the effort level when that skill or subagent runs209* **Skill and subagent frontmatter**: set `effort` in a [skill](/en/skills#frontmatter-reference) or [subagent](/en/sub-agents#supported-frontmatter-fields) markdown file to override the effort level when that skill or subagent runs

163 210 

164The environment variable takes precedence over all other methods, then your configured level, then the model default. Frontmatter effort applies when that skill or subagent is active, overriding the session level but not the environment variable.211The environment variable takes precedence over all other methods, then your configured level, then the model default. Frontmatter effort applies when that skill or subagent is active, overriding the session level but not the environment variable.

165 212 

166Effort is supported on Opus 4.6 and Sonnet 4.6. The effort slider appears in `/model` when a supported model is selected. The current effort level is also displayed next to the logo and spinner, for example "with low effort", so you can confirm which setting is active without opening `/model`.213The effort slider appears in `/model` when a supported model is selected. The current effort level is also displayed next to the logo and spinner, for example "with low effort", so you can confirm which setting is active without opening `/model`.

214 

215#### Adaptive reasoning and fixed thinking budgets

216 

217Adaptive reasoning makes thinking optional on each step, so Claude can respond faster to routine prompts and reserve deeper thinking for steps that benefit from it. If you want Claude to think more or less often than the current level produces, you can say so directly in your prompt or in `CLAUDE.md`; the model responds to that guidance within its effort setting.

218 

219Opus 4.7 always uses adaptive reasoning. The fixed thinking budget mode and `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` do not apply to it.

220 

221On Opus 4.6 and Sonnet 4.6, you can set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1` to revert to the previous fixed thinking budget controlled by `MAX_THINKING_TOKENS`. See [environment variables](/en/env-vars).

222 

223### Extended thinking

224 

225Extended thinking is the reasoning Claude emits before responding. On models that support [adaptive reasoning](#adjust-effort-level), the effort level is the primary control for how much thinking happens; the settings below turn thinking on or off and control how it displays.

226 

227| Control | How to set it |

228| :----------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- |

229| Toggle for the current session | Press `Option+T` on macOS or `Alt+T` on Windows and Linux |

230| Set the global default | Run `/config` and toggle thinking mode. Saved as `alwaysThinkingEnabled` in `~/.claude/settings.json` |

231| Disable regardless of effort | Set [`MAX_THINKING_TOKENS=0`](/en/env-vars). Other values apply only with a [fixed thinking budget](#adaptive-reasoning-and-fixed-thinking-budgets) |

167 232 

168To disable adaptive reasoning on Opus 4.6 and Sonnet 4.6 and revert to the previous fixed thinking budget, set `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1`. When disabled, these models use the fixed budget controlled by `MAX_THINKING_TOKENS`. See [environment variables](/en/env-vars).233Thinking output is collapsed by default. Press `Ctrl+O` to toggle verbose mode and see the reasoning as gray italic text. Interactive sessions on the Anthropic API receive redacted thinking blocks by default, so set `showThinkingSummaries: true` in [settings](/en/settings) if you want the full summaries available when you expand. You are charged for all thinking tokens generated, even when collapsed or redacted.

169 234 

170### Extended context235### Extended context

171 236 

172Opus 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.237Opus 4.7, Opus 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.

173 238 

174Availability varies by model and plan. On Max, Team, and Enterprise plans, Opus is automatically upgraded to 1M context with no additional configuration. This applies to both Team Standard and Team Premium seats.239Availability varies by model and plan. On Max, Team, and Enterprise plans, Opus is automatically upgraded to 1M context with no additional configuration. This applies to both Team Standard and Team Premium seats.

175 240 

176| Plan | Opus 4.6 with 1M context | Sonnet 4.6 with 1M context |241| Plan | Opus with 1M context | Sonnet with 1M context |

177| ------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |242| ------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |

178| Max, Team, and Enterprise | Included with subscription | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |243| Max, Team, and Enterprise | Included with subscription | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

179| Pro | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |244| Pro | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |


193/model sonnet[1m]258/model sonnet[1m]

194 259 

195# Or append [1m] to a full model name260# Or append [1m] to a full model name

196/model claude-opus-4-6[1m]261/model claude-opus-4-7[1m]

197```262```

198 263 

199## Checking your current model264## Checking your current model


205 270 

206## Add a custom model option271## Add a custom model option

207 272 

208Use `ANTHROPIC_CUSTOM_MODEL_OPTION` to add a single custom entry to the `/model` picker without replacing the built-in aliases. This is useful for LLM gateway deployments or testing model IDs that Claude Code does not list by default.273Use `ANTHROPIC_CUSTOM_MODEL_OPTION` to add a single custom entry to the `/model` picker without replacing the built-in aliases. This is useful for testing model IDs that Claude Code does not list by default. For LLM gateway deployments, Claude Code can populate the picker from the gateway's `/v1/models` endpoint when `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` is set, so this variable is needed only when discovery is disabled or does not return the model you want. See [LLM gateway model selection](/en/llm-gateway#model-selection).

209 274 

210This example sets all three variables to make a gateway-routed Opus deployment selectable:275This example sets all three variables to make a gateway-routed Opus deployment selectable:

211 276 

212```bash theme={null}277```bash theme={null}

213export ANTHROPIC_CUSTOM_MODEL_OPTION="my-gateway/claude-opus-4-6"278export ANTHROPIC_CUSTOM_MODEL_OPTION="my-gateway/claude-opus-4-7"

214export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="Opus via Gateway"279export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="Opus via Gateway"

215export ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION="Custom deployment routed through the internal LLM gateway"280export ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION="Custom deployment routed through the internal LLM gateway"

216```281```


247Use the following environment variables with version-specific model IDs for your provider:312Use the following environment variables with version-specific model IDs for your provider:

248 313 

249| Provider | Example |314| Provider | Example |

250| :-------- | :---------------------------------------------------------------------- |315| :-------- | :------------------------------------------------------------------- |

251| Bedrock | `export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'` |316| Bedrock | `export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-7'` |

252| Vertex AI | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |317| Vertex AI | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'` |

253| Foundry | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |318| Foundry | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7'` |

254 319 

255Apply 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.320Apply 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.

256 321 

257To enable [extended context](#extended-context) for a pinned model, append `[1m]` to the model ID in `ANTHROPIC_DEFAULT_OPUS_MODEL` or `ANTHROPIC_DEFAULT_SONNET_MODEL`:322To enable [extended context](#extended-context) for a pinned model, append `[1m]` to the model ID in `ANTHROPIC_DEFAULT_OPUS_MODEL` or `ANTHROPIC_DEFAULT_SONNET_MODEL`:

258 323 

259```bash theme={null}324```bash theme={null}

260export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6[1m]'325export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-7[1m]'

261```326```

262 327 

263The `[1m]` suffix applies the 1M context window to all usage of that alias, including `opusplan`. Claude Code strips the suffix before sending the model ID to your provider. Only append `[1m]` when the underlying model supports 1M context, such as Opus 4.6 or Sonnet 4.6.328The `[1m]` suffix applies the 1M context window to all usage of that alias, including `opusplan`. Claude Code strips the suffix before sending the model ID to your provider. Only append `[1m]` when the underlying model supports 1M context, such as Opus 4.7 or Sonnet 4.6.

264 329 

265<Note>330<Note>

266 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.331 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.


270 335 

271When you pin a model on a third-party provider, the provider-specific ID appears as-is in the `/model` picker and Claude Code may not recognize which features the model supports. You can override the display name and declare capabilities with companion environment variables for each pinned model.336When you pin a model on a third-party provider, the provider-specific ID appears as-is in the `/model` picker and Claude Code may not recognize which features the model supports. You can override the display name and declare capabilities with companion environment variables for each pinned model.

272 337 

273These variables only take effect on third-party providers such as Bedrock, Vertex AI, and Foundry. They have no effect when using the Anthropic API directly.338These variables take effect on third-party providers such as Bedrock, Vertex AI, and Foundry. The `_NAME` and `_DESCRIPTION` variables also take effect when `ANTHROPIC_BASE_URL` points to an [LLM gateway](/en/llm-gateway). They have no effect when connecting directly to `api.anthropic.com`.

274 339 

275| Environment variable | Description |340| Environment variable | Description |

276| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |341| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |


280 345 

281The same `_NAME`, `_DESCRIPTION`, and `_SUPPORTED_CAPABILITIES` suffixes are available for `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_HAIKU_MODEL`, and `ANTHROPIC_CUSTOM_MODEL_OPTION`.346The same `_NAME`, `_DESCRIPTION`, and `_SUPPORTED_CAPABILITIES` suffixes are available for `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_HAIKU_MODEL`, and `ANTHROPIC_CUSTOM_MODEL_OPTION`.

282 347 

283Claude Code enables features like [effort levels](#adjust-effort-level) and [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) by matching the model ID against known patterns. Provider-specific IDs such as Bedrock ARNs or custom deployment names often don't match these patterns, leaving supported features disabled. Set `_SUPPORTED_CAPABILITIES` to tell Claude Code which features the model actually supports:348Claude Code enables features like [effort levels](#adjust-effort-level) and [extended thinking](#extended-thinking) by matching the model ID against known patterns. Provider-specific IDs such as Bedrock ARNs or custom deployment names often don't match these patterns, leaving supported features disabled. Set `_SUPPORTED_CAPABILITIES` to tell Claude Code which features the model actually supports:

284 349 

285| Capability value | Enables |350| Capability value | Enables |

286| ---------------------- | ------------------------------------------------------------------------------- |351| ---------------------- | ------------------------------------------------------------------------------- |

287| `effort` | [Effort levels](#adjust-effort-level) and the `/effort` command |352| `effort` | [Effort levels](#adjust-effort-level) and the `/effort` command |

353| `xhigh_effort` | {/* min-version: 2.1.111 */}The `xhigh` effort level |

288| `max_effort` | The `max` effort level |354| `max_effort` | The `max` effort level |

289| `thinking` | [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) |355| `thinking` | [Extended thinking](#extended-thinking) |

290| `adaptive_thinking` | Adaptive reasoning that dynamically allocates thinking based on task complexity |356| `adaptive_thinking` | Adaptive reasoning that dynamically allocates thinking based on task complexity |

291| `interleaved_thinking` | Thinking between tool calls |357| `interleaved_thinking` | Thinking between tool calls |

292 358 


297```bash theme={null}363```bash theme={null}

298export ANTHROPIC_DEFAULT_OPUS_MODEL='arn:aws:bedrock:us-east-1:123456789012:custom-model/abc'364export ANTHROPIC_DEFAULT_OPUS_MODEL='arn:aws:bedrock:us-east-1:123456789012:custom-model/abc'

299export ANTHROPIC_DEFAULT_OPUS_MODEL_NAME='Opus via Bedrock'365export ANTHROPIC_DEFAULT_OPUS_MODEL_NAME='Opus via Bedrock'

300export ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION='Opus 4.6 routed through a Bedrock custom endpoint'366export ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION='Opus 4.7 routed through a Bedrock custom endpoint'

301export ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES='effort,max_effort,thinking,adaptive_thinking,interleaved_thinking'367export ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES='effort,xhigh_effort,max_effort,thinking,adaptive_thinking,interleaved_thinking'

302```368```

303 369 

304### Override model IDs per version370### Override model IDs per version


314```json theme={null}380```json theme={null}

315{381{

316 "modelOverrides": {382 "modelOverrides": {

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

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

319 "claude-sonnet-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/sonnet-prod"385 "claude-sonnet-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/sonnet-prod"

320 }386 }

321}387}

monitoring-usage.md +437 −22

Details

64 Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users.64 Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users.

65</Note>65</Note>

66 66 

67Claude Code does not pass `OTEL_*` environment variables to the subprocesses it spawns, including the Bash tool, hooks, MCP servers, and language servers. An OpenTelemetry-instrumented application that you run through the Bash tool does not inherit Claude Code's exporter endpoint or headers, so set those variables directly in the command if that application needs to export its own telemetry.

68 

67## Configuration details69## Configuration details

68 70 

69### Common configuration variables71### Common configuration variables

70 72 

71| Environment Variable | Description | Example Values |73| Environment Variable | Description | Example Values |

72| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |74| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |

73| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |75| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |

74| `OTEL_METRICS_EXPORTER` | Metrics exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `prometheus`, `none` |76| `OTEL_METRICS_EXPORTER` | Metrics exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `prometheus`, `none` |

75| `OTEL_LOGS_EXPORTER` | Logs/events exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `none` |77| `OTEL_LOGS_EXPORTER` | Logs/events exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `none` |


80| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs, overrides general setting | `grpc`, `http/json`, `http/protobuf` |82| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

81| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint, overrides general setting | `http://localhost:4318/v1/logs` |83| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint, overrides general setting | `http://localhost:4318/v1/logs` |

82| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |84| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |

83| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |

84| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |

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

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

87| `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 tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input (default: disabled) | `1` to enable |88| `OTEL_LOG_TOOL_DETAILS` | Enable logging of tool parameters and input arguments in tool events and trace span attributes: Bash commands, MCP server and tool names, skill names, and tool input. Also enables custom, plugin, and MCP command names on `user_prompt` events (default: disabled) | `1` to enable |

89| `OTEL_LOG_TOOL_CONTENT` | Enable logging of tool input and output content in span events (default: disabled). Requires [tracing](#traces-beta). Content is truncated at 60 KB | `1` to enable |89| `OTEL_LOG_TOOL_CONTENT` | Enable logging of tool input and output content in span events (default: disabled). Requires [tracing](#traces-beta). Content is truncated at 60 KB | `1` to enable |

90| `OTEL_LOG_RAW_API_BODIES` | Emit the full Anthropic Messages API request and response JSON as `api_request_body` / `api_response_body` log events (default: disabled). Bodies include the entire conversation history. Enabling this implies consent to everything `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS`, and `OTEL_LOG_TOOL_CONTENT` would reveal | `1` for inline bodies truncated at 60 KB, or `file:<dir>` for untruncated bodies on disk with a `body_ref` pointer in the event |

90| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality | `delta`, `cumulative` |91| `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` | Metrics temporality preference (default: `delta`). Set to `cumulative` if your backend expects cumulative temporality | `delta`, `cumulative` |

91| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |92| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |

92 93 

94### mTLS authentication

95 

96How you configure client certificates for the OTLP exporter depends on the OTLP protocol in use for that signal, set via `OTEL_EXPORTER_OTLP_PROTOCOL` or the per-signal override. The same configuration applies to metrics, logs, and traces.

97 

98| Protocol | Client certificate variables | Trust the collector's CA with |

99| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------- |

100| `http/protobuf`, `http/json` | `CLAUDE_CODE_CLIENT_CERT`, `CLAUDE_CODE_CLIENT_KEY`, and optionally `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`. See [Network configuration](/en/network-config#mtls-authentication) | `NODE_EXTRA_CA_CERTS` |

101| `grpc` | `OTEL_EXPORTER_OTLP_CLIENT_KEY` and `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE`, or the per-signal variants such as `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` to use a different certificate per signal | `OTEL_EXPORTER_OTLP_CERTIFICATE` |

102 

103For `grpc`, the OpenTelemetry SDK reads the standard OTLP variables directly, so existing configurations that set the per-signal metrics variables continue to work.

104 

93### Metrics cardinality control105### Metrics cardinality control

94 106 

95The following environment variables control which attributes are included in metrics to manage cardinality:107The following environment variables control which attributes are included in metrics to manage cardinality:


106 118 

107Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend.119Distributed tracing exports spans that link each user prompt to the API requests and tool executions it triggers, so you can view a full request as a single trace in your tracing backend.

108 120 

109Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the [common OTLP configuration](#common-configuration-variables) for endpoint, protocol, and headers.121Tracing is off by default. To enable it, set both `CLAUDE_CODE_ENABLE_TELEMETRY=1` and `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1`, then set `OTEL_TRACES_EXPORTER` to choose where spans are sent. Traces reuse the [common OTLP configuration](#common-configuration-variables) for endpoint, protocol, headers, and [mTLS](#mtls-authentication).

110 122 

111| Environment Variable | Description | Example Values |123| Environment Variable | Description | Example Values |

112| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |124| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |


120 132 

121When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs.133When tracing is active, Bash and PowerShell subprocesses automatically inherit a `TRACEPARENT` environment variable containing the W3C trace context of the active tool execution span. This lets any subprocess that reads `TRACEPARENT` parent its own spans under the same trace, enabling end-to-end distributed tracing through scripts and commands that Claude runs.

122 134 

135In Agent SDK and non-interactive sessions started with `-p`, Claude Code also reads `TRACEPARENT` and `TRACESTATE` from its own environment when starting each interaction span. This lets an embedding process pass its active W3C trace context into the subprocess so Claude Code's spans appear as children of the caller's distributed trace. Interactive sessions ignore inbound `TRACEPARENT` to avoid accidentally inheriting ambient values from CI or container environments.

136 

137#### Span hierarchy

138 

139Each user prompt starts a `claude_code.interaction` root span. API calls, tool calls, and hook executions are recorded as its children. Tool spans have two child spans of their own: one for the time spent waiting on a permission decision and one for the execution itself. When the Task tool spawns a subagent, the subagent's API and tool spans nest under the parent's `claude_code.tool` span.

140 

141```text theme={null}

142claude_code.interaction

143├── claude_code.llm_request

144├── claude_code.hook (requires detailed beta tracing)

145└── claude_code.tool

146 ├── claude_code.tool.blocked_on_user

147 ├── claude_code.tool.execution

148 └── (Task tool) subagent claude_code.llm_request / claude_code.tool spans

149```

150 

151In Agent SDK and `claude -p` sessions, `claude_code.interaction` itself becomes a child of the caller's span when `TRACEPARENT` is set in the environment.

152 

153#### Span attributes

154 

155Every span carries the [standard attributes](#standard-attributes) plus a `span.type` attribute matching its name. The tables below list the additional attributes set on each span. The `llm_request`, `tool.execution`, and `hook` spans set OpenTelemetry status `ERROR` when they record a failure; the other spans always end with status `UNSET`.

156 

157**`claude_code.interaction`**

158 

159| Attribute | Description | Gated by |

160| ------------------------- | --------------------------------------------------------- | ----------------------- |

161| `user_prompt` | Prompt text. Value is `<REDACTED>` unless the gate is set | `OTEL_LOG_USER_PROMPTS` |

162| `user_prompt_length` | Prompt length in characters | |

163| `interaction.sequence` | 1-based counter of interactions in this session | |

164| `interaction.duration_ms` | Wall-clock duration of the turn | |

165 

166**`claude_code.llm_request`**

167 

168| Attribute | Description | Gated by |

169| -------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------- |

170| `model` | Model identifier | |

171| `gen_ai.system` | Always `anthropic`. OpenTelemetry GenAI semantic convention | |

172| `gen_ai.request.model` | Same value as `model`. OpenTelemetry GenAI semantic convention | |

173| `query_source` | Subsystem that issued the request, such as `repl_main_thread` or a subagent name | |

174| `speed` | `fast` or `normal` | |

175| `llm_request.context` | `interaction`, `tool`, or `standalone` depending on the parent span | |

176| `duration_ms` | Wall-clock duration including retries | |

177| `ttft_ms` | Time to first token in milliseconds | |

178| `input_tokens` | Input token count from the API usage block | |

179| `output_tokens` | Output token count | |

180| `cache_read_tokens` | Tokens read from prompt cache | |

181| `cache_creation_tokens` | Tokens written to prompt cache | |

182| `request_id` | Anthropic API request ID from the `request-id` response header | |

183| `gen_ai.response.id` | Same value as `request_id`. OpenTelemetry GenAI semantic convention | |

184| `client_request_id` | Client-generated `x-client-request-id` of the final attempt | |

185| `attempt` | Total attempts made for this request | |

186| `success` | `true` or `false` | |

187| `status_code` | HTTP status code when the request failed | |

188| `error` | Error message when the request failed | |

189| `response.has_tool_call` | `true` when the response contained tool-use blocks | |

190| `stop_reason` | API response `stop_reason`, such as `end_turn`, `tool_use`, `max_tokens`, `stop_sequence`, `pause_turn`, or `refusal` | |

191| `gen_ai.response.finish_reasons` | Same value as `stop_reason`, wrapped in a string array. OpenTelemetry GenAI semantic convention | |

192 

193Each retry attempt is also recorded as a `gen_ai.request.attempt` span event with `attempt` and `client_request_id` attributes.

194 

195**`claude_code.tool`**

196 

197| Attribute | Description | Gated by |

198| --------------- | ----------------------------------------------------------- | ----------------------- |

199| `tool_name` | Tool name | |

200| `duration_ms` | Wall-clock duration including permission wait and execution | |

201| `result_tokens` | Approximate token size of the tool result | |

202| `file_path` | Target file path for Read, Edit, and Write tools | `OTEL_LOG_TOOL_DETAILS` |

203| `full_command` | Command string for the Bash tool | `OTEL_LOG_TOOL_DETAILS` |

204| `skill_name` | Skill name for the Skill tool | `OTEL_LOG_TOOL_DETAILS` |

205| `subagent_type` | Subagent type for the Task tool | `OTEL_LOG_TOOL_DETAILS` |

206 

207When `OTEL_LOG_TOOL_CONTENT=1`, this span also records a `tool.output` span event whose attributes contain the tool's input and output bodies, truncated at 60 KB per attribute.

208 

209**`claude_code.tool.blocked_on_user`**

210 

211| Attribute | Description | Gated by |

212| ------------- | ------------------------------------------------------------------------- | -------- |

213| `duration_ms` | Time spent waiting for the permission decision | |

214| `decision` | `accept` or `reject` | |

215| `source` | Decision source, matching the [Tool decision event](#tool-decision-event) | |

216 

217**`claude_code.tool.execution`**

218 

219| Attribute | Description | Gated by |

220| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |

221| `duration_ms` | Time spent running the tool body | |

222| `success` | `true` or `false` | |

223| `error` | Error category string when execution failed, such as `Error:ENOENT` or `ShellError`. Contains the full error message instead when the gate is set | `OTEL_LOG_TOOL_DETAILS` |

224 

225**`claude_code.hook`**

226 

227This span is emitted only when detailed beta tracing is active, which requires `ENABLE_BETA_TRACING_DETAILED=1` and `BETA_TRACING_ENDPOINT` in addition to the trace exporter configuration above. In interactive CLI sessions, this also requires your organization to be allowlisted for the feature. Agent SDK and non-interactive `-p` sessions are not gated. It is not emitted when only `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` is set.

228 

229| Attribute | Description | Gated by |

230| ------------------------ | ------------------------------------------------ | ----------------------- |

231| `hook_event` | Hook event type, such as `PreToolUse` | |

232| `hook_name` | Full hook name, such as `PreToolUse:Write` | |

233| `num_hooks` | Number of matching hook commands executed | |

234| `hook_definitions` | JSON-serialized hook configuration | `OTEL_LOG_TOOL_DETAILS` |

235| `duration_ms` | Wall-clock duration of all matching hooks | |

236| `num_success` | Count of hooks that completed successfully | |

237| `num_blocking` | Count of hooks that returned a blocking decision | |

238| `num_non_blocking_error` | Count of hooks that failed without blocking | |

239| `num_cancelled` | Count of hooks cancelled before completion | |

240 

241<Note>

242 Additional content-bearing attributes such as `new_context`, `system_prompt_preview`, `user_system_prompt`, `tool_input`, and `response.model_output` are emitted only when detailed beta tracing is active. They are not part of the stable span schema. `user_system_prompt` additionally requires `OTEL_LOG_USER_PROMPTS=1`. It carries only the system prompt text you provide via the `systemPrompt` SDK option or `--system-prompt` and `--append-system-prompt` flags, truncated at 60 KB, and is emitted once per session rather than per request.

243</Note>

244 

123### Dynamic headers245### Dynamic headers

124 246 

125For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:247For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically. Dynamic headers apply only to the `http/protobuf` and `http/json` protocols. The `grpc` exporter uses only the static `OTEL_EXPORTER_OTLP_HEADERS` value.

126 248 

127#### Settings configuration249#### Settings configuration

128 250 


286**Attributes**:408**Attributes**:

287 409 

288* All [standard attributes](#standard-attributes)410* All [standard attributes](#standard-attributes)

411* `start_type`: How the session was started. One of `"fresh"`, `"resume"`, or `"continue"`

289 412 

290#### Lines of code counter413#### Lines of code counter

291 414 


298 421 

299#### Pull request counter422#### Pull request counter

300 423 

301Incremented when creating pull requests via Claude Code.424Incremented when Claude Code creates a pull request or merge request through a shell command or an MCP tool.

302 425 

303**Attributes**:426**Attributes**:

304 427 


320 443 

321* All [standard attributes](#standard-attributes)444* All [standard attributes](#standard-attributes)

322* `model`: Model identifier (for example, "claude-sonnet-4-6")445* `model`: Model identifier (for example, "claude-sonnet-4-6")

446* `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"`

447* `speed`: `"fast"` when the request used fast mode. Absent otherwise

448* `effort`: [Effort level](/en/model-config#adjust-effort-level) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort.

323 449 

324#### Token counter450#### Token counter

325 451 


330* All [standard attributes](#standard-attributes)456* All [standard attributes](#standard-attributes)

331* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)457* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)

332* `model`: Model identifier (for example, "claude-sonnet-4-6")458* `model`: Model identifier (for example, "claude-sonnet-4-6")

459* `query_source`: Category of the subsystem that issued the request. One of `"main"`, `"subagent"`, or `"auxiliary"`

460* `speed`: `"fast"` when the request used fast mode. Absent otherwise

461* `effort`: [Effort level](/en/model-config#adjust-effort-level) applied to the request. See [Cost counter](#cost-counter) for details.

333 462 

334#### Code edit tool decision counter463#### Code edit tool decision counter

335 464 


340* All [standard attributes](#standard-attributes)469* All [standard attributes](#standard-attributes)

341* `tool_name`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)470* `tool_name`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)

342* `decision`: User decision (`"accept"`, `"reject"`)471* `decision`: User decision (`"accept"`, `"reject"`)

343* `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`472* `source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the [Tool decision event](#tool-decision-event) for what each value means.

344* `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions.473* `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions.

345 474 

346#### Active time counter475#### Active time counter


384* `event.sequence`: monotonically increasing counter for ordering events within a session513* `event.sequence`: monotonically increasing counter for ordering events within a session

385* `prompt_length`: Length of the prompt514* `prompt_length`: Length of the prompt

386* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)515* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)

516* `command_name`: Command name when the prompt invokes one. Built-in and bundled command names such as `compact` or `debug` are emitted as-is; aliases such as `reset` emit as typed rather than the canonical name. Custom, plugin, and MCP command names collapse to `custom` or `mcp` unless `OTEL_LOG_TOOL_DETAILS=1` is set

517* `command_source`: Origin of the command when present: `builtin`, `custom`, or `mcp`. Plugin-provided commands report as `custom`

387 518 

388#### Tool result event519#### Tool result event

389 520 


398* `event.timestamp`: ISO 8601 timestamp529* `event.timestamp`: ISO 8601 timestamp

399* `event.sequence`: monotonically increasing counter for ordering events within a session530* `event.sequence`: monotonically increasing counter for ordering events within a session

400* `tool_name`: Name of the tool531* `tool_name`: Name of the tool

532* `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data.

401* `success`: `"true"` or `"false"`533* `success`: `"true"` or `"false"`

402* `duration_ms`: Execution time in milliseconds534* `duration_ms`: Execution time in milliseconds

403* `error`: Error message (if failed)535* `error_type`: Error category string when the tool failed, such as `"Error:ENOENT"` or `"ShellError"`

536* `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the tool failed

404* `decision_type`: Either `"accept"` or `"reject"`537* `decision_type`: Either `"accept"` or `"reject"`

405* `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`538* `decision_source`: Where the decision came from. One of `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`. See the [Tool decision event](#tool-decision-event) for what each value means.

539* `tool_input_size_bytes`: Size of the JSON-serialized tool input in bytes

406* `tool_result_size_bytes`: Size of the tool result in bytes540* `tool_result_size_bytes`: Size of the tool result in bytes

407* `mcp_server_scope`: MCP server scope identifier (for MCP tools)541* `mcp_server_scope`: MCP server scope identifier (for MCP tools)

408* `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters:542* `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters:

409 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds)543 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds)

410 * For MCP tools: includes `mcp_server_name`, `mcp_tool_name`544 * For MCP tools: includes `mcp_server_name`, `mcp_tool_name`

411 * For Skill tool: includes `skill_name`545 * For Skill tool: includes `skill_name`

546 * For Task tool: includes `subagent_type`

412* `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to \~4 K characters. Applies to all tools including MCP tools.547* `tool_input` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON-serialized tool arguments. Individual values over 512 characters are truncated, and the full payload is bounded to \~4 K characters. Applies to all tools including MCP tools.

413 548 

414#### API request event549#### API request event


430* `output_tokens`: Number of output tokens565* `output_tokens`: Number of output tokens

431* `cache_read_tokens`: Number of tokens read from cache566* `cache_read_tokens`: Number of tokens read from cache

432* `cache_creation_tokens`: Number of tokens used for cache creation567* `cache_creation_tokens`: Number of tokens used for cache creation

568* `request_id`: Anthropic API request ID from the response's `request-id` header, such as `"req_011..."`. Present only when the API returns one.

433* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active569* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active

570* `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name

571* `effort`: [Effort level](/en/model-config#adjust-effort-level) applied to the request: `"low"`, `"medium"`, `"high"`, `"xhigh"`, or `"max"`. Absent when the model does not support effort.

434 572 

435#### API error event573#### API error event

436 574 


446* `event.sequence`: monotonically increasing counter for ordering events within a session584* `event.sequence`: monotonically increasing counter for ordering events within a session

447* `model`: Model used (for example, "claude-sonnet-4-6")585* `model`: Model used (for example, "claude-sonnet-4-6")

448* `error`: Error message586* `error`: Error message

449* `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors587* `status_code`: HTTP status code as a number. Absent for non-HTTP errors such as connection failures.

450* `duration_ms`: Request duration in milliseconds588* `duration_ms`: Request duration in milliseconds

451* `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred)589* `attempt`: Total number of attempts made, including the initial request (`1` means no retries occurred)

590* `request_id`: Anthropic API request ID from the response's `request-id` header, such as `"req_011..."`. Present only when the API returns one.

452* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active591* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active

592* `query_source`: Subsystem that issued the request, such as `"repl_main_thread"`, `"compact"`, or a subagent name

593* `effort`: [Effort level](/en/model-config#adjust-effort-level) applied to the request. Absent when the model does not support effort.

594 

595#### API request body event

596 

597Logged for each API request attempt when `OTEL_LOG_RAW_API_BODIES` is set. One event is emitted per attempt, so retries with adjusted parameters each produce their own event.

598 

599**Event Name**: `claude_code.api_request_body`

600 

601**Attributes**:

602 

603* All [standard attributes](#standard-attributes)

604* `event.name`: `"api_request_body"`

605* `event.timestamp`: ISO 8601 timestamp

606* `event.sequence`: monotonically increasing counter for ordering events within a session

607* `body`: JSON-serialized Messages API request parameters (system prompt, messages, tools, etc.), truncated at 60 KB. Extended-thinking content in prior assistant turns is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`).

608* `body_ref`: Absolute path to a `<dir>/<uuid>.request.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`).

609* `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1`

610* `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred.

611* `model`: Model identifier from the request parameters

612* `query_source`: Subsystem that issued the request (for example, `"compact"`)

613 

614#### API response body event

615 

616Logged for each successful API response when `OTEL_LOG_RAW_API_BODIES` is set.

617 

618**Event Name**: `claude_code.api_response_body`

619 

620**Attributes**:

621 

622* All [standard attributes](#standard-attributes)

623* `event.name`: `"api_response_body"`

624* `event.timestamp`: ISO 8601 timestamp

625* `event.sequence`: monotonically increasing counter for ordering events within a session

626* `body`: JSON-serialized Messages API response (id, content blocks, usage, stop reason), truncated at 60 KB. Extended-thinking content is redacted. Emitted only in inline mode (`OTEL_LOG_RAW_API_BODIES=1`).

627* `body_ref`: Absolute path to a `<dir>/<request_id>.response.json` file containing the untruncated body. Emitted only in file mode (`OTEL_LOG_RAW_API_BODIES=file:<dir>`).

628* `body_length`: Untruncated body length. UTF-8 bytes when `OTEL_LOG_RAW_API_BODIES=file:<dir>`, or UTF-16 code units when `=1`

629* `body_truncated`: `"true"` when inline truncation occurred. Absent in file mode and when no truncation occurred.

630* `model`: Model identifier

631* `query_source`: Subsystem that issued the request

632* `request_id`: Anthropic API request ID from the response's `request-id` header, such as `"req_011..."`. Present only when the API returns one.

453 633 

454#### Tool decision event634#### Tool decision event

455 635 


464* `event.timestamp`: ISO 8601 timestamp644* `event.timestamp`: ISO 8601 timestamp

465* `event.sequence`: monotonically increasing counter for ordering events within a session645* `event.sequence`: monotonically increasing counter for ordering events within a session

466* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")646* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")

647* `tool_use_id`: Unique identifier for this tool invocation. Matches the `tool_use_id` passed to hooks, allowing correlation between OTel events and hook-captured data.

467* `decision`: Either `"accept"` or `"reject"`648* `decision`: Either `"accept"` or `"reject"`

468* `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`649* `source`: Where the decision came from:

650 * `"config"`: Decided automatically without prompting, based on project settings, allow rules in the user's personal settings, enterprise managed policy, `--allowedTools` or `--disallowedTools` flags, the active permission mode, a session-scoped grant from an earlier prompt in the same interactive CLI session, or because the tool is inherently safe. The event does not indicate which of these sources matched.

651 * `"hook"`: A `PreToolUse` or `PermissionRequest` hook returned the decision.

652 * `"user_permanent"`: Emitted when the user chose "Yes, and don't ask again for ..." at a permission prompt, which saves an allow rule to their personal settings. In the interactive CLI this is emitted only for that choice itself; later calls that match the saved rule emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the initial choice and later rule matches emit `"user_permanent"`. Treated as an accept.

653 * `"user_temporary"`: Emitted when the user chose "Yes" at a permission prompt for a one-time approval, or chose one of the "... during this session" options on a file edit or read prompt. In the interactive CLI this is emitted only for the choice itself; later calls allowed by that session-scoped grant emit `"config"` instead. In Agent SDK or non-interactive `-p` sessions, both the choice and later matches emit `"user_temporary"`. Treated as an accept.

654 * `"user_abort"`: Emitted when the user dismissed the permission prompt without answering. Treated as a reject.

655 * `"user_reject"`: Emitted when the user chose "No" when prompted, or a call matched a deny rule in their personal settings. Treated as a reject.

656 

657#### Permission mode changed event

658 

659Logged when the permission mode changes, for example from `Shift+Tab` cycling, exiting plan mode, or an auto mode gate check.

660 

661**Event Name**: `claude_code.permission_mode_changed`

662 

663**Attributes**:

664 

665* All [standard attributes](#standard-attributes)

666* `event.name`: `"permission_mode_changed"`

667* `event.timestamp`: ISO 8601 timestamp

668* `event.sequence`: monotonically increasing counter for ordering events within a session

669* `from_mode`: The previous permission mode, for example `"default"`, `"plan"`, `"acceptEdits"`, `"auto"`, or `"bypassPermissions"`

670* `to_mode`: The new permission mode

671* `trigger`: What caused the change. One of `"shift_tab"`, `"exit_plan_mode"`, `"auto_gate_denied"`, or `"auto_opt_in"`. Absent when the transition originates from the SDK or bridge

672 

673#### Auth event

674 

675Logged when `/login` or `/logout` completes.

676 

677**Event Name**: `claude_code.auth`

678 

679**Attributes**:

680 

681* All [standard attributes](#standard-attributes)

682* `event.name`: `"auth"`

683* `event.timestamp`: ISO 8601 timestamp

684* `event.sequence`: monotonically increasing counter for ordering events within a session

685* `action`: `"login"` or `"logout"`

686* `success`: `"true"` or `"false"`

687* `auth_method`: Authentication method, such as `"oauth"`

688* `error_category`: Categorical error kind when the action failed. The raw error message is never included

689* `status_code`: HTTP status code as a string when the action failed with an HTTP error

690 

691#### MCP server connection event

692 

693Logged when an MCP server connects, disconnects, or fails to connect.

694 

695**Event Name**: `claude_code.mcp_server_connection`

696 

697**Attributes**:

698 

699* All [standard attributes](#standard-attributes)

700* `event.name`: `"mcp_server_connection"`

701* `event.timestamp`: ISO 8601 timestamp

702* `event.sequence`: monotonically increasing counter for ordering events within a session

703* `status`: `"connected"`, `"failed"`, or `"disconnected"`

704* `transport_type`: Server transport, such as `"stdio"`, `"sse"`, or `"http"`

705* `server_scope`: Scope the server is configured at, such as `"user"`, `"project"`, or `"local"`

706* `duration_ms`: Connection attempt duration in milliseconds

707* `error_code`: Error code when the connection failed

708* `server_name` (when `OTEL_LOG_TOOL_DETAILS=1`): Configured server name

709* `error` (when `OTEL_LOG_TOOL_DETAILS=1`): Full error message when the connection failed

710 

711#### Internal error event

712 

713Logged when Claude Code catches an unexpected internal error. Only the error class name and an errno-style code are recorded. The error message and stack trace are never included. This event is not emitted when running against Bedrock, Vertex, or Foundry, or when `DISABLE_ERROR_REPORTING` is set.

714 

715**Event Name**: `claude_code.internal_error`

716 

717**Attributes**:

718 

719* All [standard attributes](#standard-attributes)

720* `event.name`: `"internal_error"`

721* `event.timestamp`: ISO 8601 timestamp

722* `event.sequence`: monotonically increasing counter for ordering events within a session

723* `error_name`: Error class name, such as `"TypeError"` or `"SyntaxError"`

724* `error_code`: Node.js errno code such as `"ENOENT"` when present on the error

469 725 

470#### Plugin installed event726#### Plugin installed event

471 727 


479* `event.name`: `"plugin_installed"`735* `event.name`: `"plugin_installed"`

480* `event.timestamp`: ISO 8601 timestamp736* `event.timestamp`: ISO 8601 timestamp

481* `event.sequence`: monotonically increasing counter for ordering events within a session737* `event.sequence`: monotonically increasing counter for ordering events within a session

482* `plugin.name`: Name of the installed plugin

483* `plugin.version`: Plugin version when declared in the marketplace entry

484* `marketplace.name`: Marketplace the plugin was installed from

485* `marketplace.is_official`: `"true"` if the marketplace is an official Anthropic marketplace, `"false"` otherwise738* `marketplace.is_official`: `"true"` if the marketplace is an official Anthropic marketplace, `"false"` otherwise

486* `install.trigger`: `"cli"` or `"ui"`739* `install.trigger`: `"cli"` or `"ui"`

740* `plugin.name`: Name of the installed plugin. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1`

741* `plugin.version`: Plugin version when declared in the marketplace entry. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1`

742* `marketplace.name`: Marketplace the plugin was installed from. For third-party marketplaces this is included only when `OTEL_LOG_TOOL_DETAILS=1`

487 743 

488#### Skill activated event744#### Skill activated event

489 745 

490Logged when a skill is invoked.746Logged when a skill is invoked, whether Claude calls it through the Skill tool or you run it as a `/` command.

491 747 

492**Event Name**: `claude_code.skill_activated`748**Event Name**: `claude_code.skill_activated`

493 749 


497* `event.name`: `"skill_activated"`753* `event.name`: `"skill_activated"`

498* `event.timestamp`: ISO 8601 timestamp754* `event.timestamp`: ISO 8601 timestamp

499* `event.sequence`: monotonically increasing counter for ordering events within a session755* `event.sequence`: monotonically increasing counter for ordering events within a session

500* `skill.name`: Name of the skill756* `skill.name`: Name of the skill. For user-defined and third-party plugin skills the value is the placeholder `"custom_skill"` unless `OTEL_LOG_TOOL_DETAILS=1`

757* `invocation_trigger`: How the skill was triggered (`"user-slash"`, `"claude-proactive"`, or `"nested-skill"`)

501* `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`)758* `skill.source`: Where the skill was loaded from (for example, `"bundled"`, `"userSettings"`, `"projectSettings"`, `"plugin"`)

502* `plugin.name`: Name of the owning plugin when the skill is provided by a plugin759* `plugin.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Name of the owning plugin when the skill is provided by a plugin

503* `marketplace.name`: Marketplace the owning plugin was installed from, when the skill is provided by a plugin760* `marketplace.name` (when `OTEL_LOG_TOOL_DETAILS=1` or the plugin is from an official marketplace): Marketplace the owning plugin was installed from, when the skill is provided by a plugin

761 

762#### At mention event

763 

764Logged when Claude Code resolves an `@`-mention in a prompt. Not every mention emits an event: early-exit paths such as permission denials, oversized files, PDF reference attachments, and directory listing failures return without logging.

765 

766**Event Name**: `claude_code.at_mention`

767 

768**Attributes**:

769 

770* All [standard attributes](#standard-attributes)

771* `event.name`: `"at_mention"`

772* `event.timestamp`: ISO 8601 timestamp

773* `event.sequence`: monotonically increasing counter for ordering events within a session

774* `mention_type`: Type of mention (`"file"`, `"directory"`, `"agent"`, `"mcp_resource"`)

775* `success`: Whether the mention resolved successfully (`"true"` or `"false"`)

776 

777#### API retries exhausted event

778 

779Logged once when an API request fails after more than one attempt. Emitted alongside the final `api_error` event.

780 

781**Event Name**: `claude_code.api_retries_exhausted`

782 

783**Attributes**:

784 

785* All [standard attributes](#standard-attributes)

786* `event.name`: `"api_retries_exhausted"`

787* `event.timestamp`: ISO 8601 timestamp

788* `event.sequence`: monotonically increasing counter for ordering events within a session

789* `model`: Model used

790* `error`: Final error message

791* `status_code`: HTTP status code as a number. Absent for non-HTTP errors.

792* `total_attempts`: Total number of attempts made

793* `total_retry_duration_ms`: Total wall-clock time across all attempts

794* `speed`: `"fast"` or `"normal"`

795 

796#### Hook execution start event

797 

798Logged when one or more hooks begin executing for a hook event.

799 

800**Event Name**: `claude_code.hook_execution_start`

801 

802**Attributes**:

803 

804* All [standard attributes](#standard-attributes)

805* `event.name`: `"hook_execution_start"`

806* `event.timestamp`: ISO 8601 timestamp

807* `event.sequence`: monotonically increasing counter for ordering events within a session

808* `hook_event`: Hook event type, such as `"PreToolUse"` or `"PostToolUse"`

809* `hook_name`: Full hook name including matcher, such as `"PreToolUse:Write"`

810* `num_hooks`: Number of matching hook commands

811* `managed_only`: `"true"` when only managed-policy hooks are permitted

812* `hook_source`: `"policySettings"` or `"merged"`

813* `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled

814 

815#### Hook execution complete event

816 

817Logged when all hooks for a hook event have finished.

818 

819**Event Name**: `claude_code.hook_execution_complete`

820 

821**Attributes**:

822 

823* All [standard attributes](#standard-attributes)

824* `event.name`: `"hook_execution_complete"`

825* `event.timestamp`: ISO 8601 timestamp

826* `event.sequence`: monotonically increasing counter for ordering events within a session

827* `hook_event`: Hook event type

828* `hook_name`: Full hook name including matcher

829* `num_hooks`: Number of matching hook commands

830* `num_success`: Count that completed successfully

831* `num_blocking`: Count that returned a blocking decision

832* `num_non_blocking_error`: Count that failed without blocking

833* `num_cancelled`: Count cancelled before completion

834* `total_duration_ms`: Wall-clock duration of all matching hooks

835* `managed_only`: `"true"` when only managed-policy hooks are permitted

836* `hook_source`: `"policySettings"` or `"merged"`

837* `hook_definitions`: JSON-serialized hook configuration. Included only when both detailed beta tracing and `OTEL_LOG_TOOL_DETAILS=1` are enabled

838 

839#### Compaction event

840 

841Logged when conversation compaction completes.

842 

843**Event Name**: `claude_code.compaction`

844 

845**Attributes**:

846 

847* All [standard attributes](#standard-attributes)

848* `event.name`: `"compaction"`

849* `event.timestamp`: ISO 8601 timestamp

850* `event.sequence`: monotonically increasing counter for ordering events within a session

851* `trigger`: `"auto"` or `"manual"`

852* `success`: `"true"` or `"false"`

853* `duration_ms`: Compaction duration

854* `pre_tokens`: Approximate token count before compaction

855* `post_tokens`: Approximate token count after compaction

856* `error`: Error message when compaction failed

504 857 

505## Interpret metrics and events data858## Interpret metrics and events data

506 859 


523* Identifying high-usage sessions for optimization876* Identifying high-usage sessions for optimization

524 877 

525<Note>878<Note>

526 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).879 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, Amazon Bedrock, or Google Cloud Vertex).

527</Note>880</Note>

528 881 

529### Alerting and segmentation882### Alerting and segmentation


557 910 

558**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.911**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.

559 912 

913## Audit security events

914 

915OpenTelemetry events are the audit data source for Claude Code activity. Every event carries identity attributes that tie tool calls, MCP activity, and permission decisions back to the user who triggered them, and the OTLP logs exporter can deliver these events to any Security Information and Event Management (SIEM) platform with an OTLP receiver or to an OpenTelemetry Collector that forwards to your SIEM.

916 

917### Attribute actions to users

918 

919The [standard attributes](#standard-attributes) on each event include the authenticated user's identity: `user.email`, `user.account_uuid`, `user.account_id`, and `organization.id` when signed in with a Claude account, plus the installation-scoped `user.id` and the per-session `session.id`.

920 

921MCP tool calls, Bash commands, and file edits are therefore attributed to the developer who started the session. Claude Code does not act under a separate service account; the identity recorded on each event is the developer's own Claude account.

922 

923When Claude Code authenticates with a direct API key, or against Bedrock, Vertex AI, or Microsoft Foundry, there is no Claude account in the session and only `user.id` and `session.id` are populated. In these deployments, attach user identity yourself with `OTEL_RESOURCE_ATTRIBUTES`, set per user through the [managed settings](#administrator-configuration) file or a launch wrapper:

924 

925```bash theme={null}

926export OTEL_RESOURCE_ATTRIBUTES="enduser.id=jdoe@example.com,enduser.directory_id=S-1-5-21-..."

927```

928 

929### Audit MCP activity

930 

931To capture MCP server activity with full call detail, enable the logs exporter and set `OTEL_LOG_TOOL_DETAILS=1`. Each MCP operation then produces structured events that carry the server name, tool name, and call arguments alongside the standard identity attributes:

932 

933| Event | What it records for MCP |

934| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

935| `mcp_server_connection` | Server connect, disconnect, and connection failure with `server_name`, `transport_type`, `server_scope`, and error detail |

936| `tool_result` | Each MCP tool call with `tool_name` and `mcp_server_scope`, a `tool_parameters` payload containing `mcp_server_name` and `mcp_tool_name`, and a `tool_input` payload containing the call arguments |

937| `tool_decision` | Whether the call was allowed or denied, and whether the decision came from config, a hook, or the user |

938 

939Without `OTEL_LOG_TOOL_DETAILS`, `tool_result` events still carry `tool_name` and `mcp_server_scope` but omit the `mcp_server_name`/`mcp_tool_name` breakdown and the arguments, and `mcp_server_connection` events omit `server_name` and the error message.

940 

941### Map security questions to events

942 

943When building detection rules, look up the signal you want to monitor and query your backend for the corresponding event and attributes:

944 

945| Signal | Event | Key attributes |

946| ----------------------------------------- | -------------------------------------------- | ------------------------------------------------------------ |

947| Tool call allowed or denied, and by what | `tool_decision` | `decision`, `source`, `tool_name` |

948| Permission mode escalation | `permission_mode_changed` | `from_mode`, `to_mode`, `trigger` |

949| Policy hook blocked an action | `hook_execution_complete` | `hook_event`, `num_blocking` |

950| Login, logout, and authentication failure | `auth` | `action`, `success`, `error_category` |

951| MCP server connect or failure | `mcp_server_connection` | `status`, `server_name`, `error_code` |

952| Plugin installed and its source | `plugin_installed` | `plugin.name`, `marketplace.name`, `marketplace.is_official` |

953| Commands run and files touched | `tool_result` with `OTEL_LOG_TOOL_DETAILS=1` | `tool_parameters`, `tool_input` |

954 

955Claude Code emits the raw event stream only. Anomaly detection, baselining, correlation across sessions, and alerting are the responsibility of your SIEM or observability backend.

956 

957### Send events to a SIEM

958 

959Point `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` at your SIEM's OTLP receiver, or at an OpenTelemetry Collector that forwards to your SIEM's native ingest API. The following managed-settings example exports events only, with full tool detail enabled for MCP and Bash auditing:

960 

961```json theme={null}

962{

963 "env": {

964 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",

965 "OTEL_LOGS_EXPORTER": "otlp",

966 "OTEL_LOG_TOOL_DETAILS": "1",

967 "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL": "http/protobuf",

968 "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "https://siem.example.com:4318/v1/logs",

969 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer your-siem-token"

970 }

971}

972```

973 

560## Backend considerations974## Backend considerations

561 975 

562Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:976Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:


600 1014 

601## Security and privacy1015## Security and privacy

602 1016 

603* Telemetry is opt-in and requires explicit configuration1017* OpenTelemetry export to your backend is opt-in and requires explicit configuration. For Anthropic's separate operational telemetry and how to disable it, see [Data usage](/en/data-usage#telemetry-services)

604* Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below1018* Raw file contents and code snippets are not included in metrics or events. Trace spans are a separate data path: see the `OTEL_LOG_TOOL_CONTENT` bullet below

605* 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 field1019* 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

606* User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`1020* User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`

607* Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to \~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed1021* Tool input arguments and parameters are not logged by default. To include them, set `OTEL_LOG_TOOL_DETAILS=1`. When enabled, `tool_result` events include a `tool_parameters` attribute with Bash commands, MCP server and tool names, and skill names, plus a `tool_input` attribute with file paths, URLs, search patterns, and other arguments. `user_prompt` events include the verbatim `command_name` for custom, plugin, and MCP commands. Trace spans include the same `tool_input` attribute and input-derived attributes such as `file_path`. Individual values over 512 characters are truncated and the total is bounded to \~4 K characters, but the arguments may still contain sensitive values. Configure your telemetry backend to filter or redact these attributes as needed

608* Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed1022* Tool input and output content is not logged in trace spans by default. To include it, set `OTEL_LOG_TOOL_CONTENT=1`. When enabled, span events include full tool input and output content truncated at 60 KB per span. This can include raw file contents from Read tool results and Bash command output. Configure your telemetry backend to filter or redact these attributes as needed

1023* Raw Anthropic Messages API request and response bodies are not logged by default. To include them, set `OTEL_LOG_RAW_API_BODIES`. With `=1`, each API call emits `api_request_body` and `api_response_body` log events whose `body` attribute is the JSON-serialized payload, truncated at 60 KB. With `=file:<dir>`, untruncated bodies are written to `.request.json` and `.response.json` files under that directory and the events carry a `body_ref` path instead of the inline body. Ship the directory with a log collector or sidecar rather than through the telemetry stream. In both modes, bodies contain the full conversation history (system prompt, every prior user and assistant turn, tool results), so enabling this implies consent to everything the other `OTEL_LOG_*` content flags would reveal. Claude's extended-thinking content is always redacted from these bodies regardless of other settings

609 1024 

610## Monitor Claude Code on Amazon Bedrock1025## Monitor Claude Code on Amazon Bedrock

611 1026 

network-config.md +13 −14

Details

57 57 

58By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system's certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store.58By default, Claude Code trusts both its bundled Mozilla CA certificates and your operating system's certificate store. Enterprise TLS-inspection proxies such as CrowdStrike Falcon and Zscaler work without additional configuration when their root certificate is installed in the OS trust store.

59 59 

60<Note>

61 System CA store integration requires the native Claude Code binary distribution. When running on the Node.js runtime, the system CA store is not merged automatically. In that case, set `NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem` to trust an enterprise root CA.

62</Note>

63 

64`CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`.60`CLAUDE_CODE_CERT_STORE` accepts a comma-separated list of sources. Recognized values are `bundled` for the Mozilla CA set shipped with Claude Code and `system` for the operating system trust store. The default is `bundled,system`.

65 61 

66To trust only the bundled Mozilla CA set:62To trust only the bundled Mozilla CA set:


104 100 

105## Network access requirements101## Network access requirements

106 102 

107Claude Code requires access to the following URLs:103Claude Code requires access to the following URLs. Allowlist these in your proxy configuration and firewall rules, especially in containerized or restricted network environments.

108 

109* `api.anthropic.com`: Claude API endpoints

110* `claude.ai`: authentication for claude.ai accounts

111* `platform.claude.com`: authentication for Anthropic Console accounts

112 104 

113Ensure 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.105| URL | Required for |

106| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |

107| `api.anthropic.com` | Claude API requests |

108| `claude.ai` | claude.ai account authentication |

109| `platform.claude.com` | Anthropic Console account authentication |

110| `downloads.claude.ai` | Plugin executable downloads; native installer and native auto-updater |

111| `storage.googleapis.com` | {/* max-version: 2.1.115 */}Native installer and native auto-updater on versions prior to 2.1.116 |

112| `bridge.claudeusercontent.com` | [Claude in Chrome](/en/chrome) extension WebSocket bridge |

113| `raw.githubusercontent.com` | Changelog feed for [`/release-notes`](/en/commands) and the release notes shown after updating; plugin marketplace install counts |

114 114 

115The native installer and update checks also require the following URLs. Allowlist both, since the installer and auto-updater fetch from `storage.googleapis.com` while plugin downloads use `downloads.claude.ai`. If you install Claude Code through npm or manage your own binary distribution, end users may not need access:115If you install Claude Code through npm or manage your own binary distribution, end users may not need access to `downloads.claude.ai` or `storage.googleapis.com`.

116 116 

117* `storage.googleapis.com`: download bucket for the Claude Code binary and auto-updater117Claude Code also sends optional operational telemetry by default, which you can disable with environment variables. See [Telemetry services](/en/data-usage#telemetry-services) for how to disable it before finalizing your allowlist.

118* `downloads.claude.ai`: CDN hosting the install script, version pointers, manifests, signing keys, and plugin executables

119 118 

120The [Chrome integration](/en/chrome) connects to the browser extension over a WebSocket bridge. If you use Claude in Chrome, allowlist `bridge.claudeusercontent.com` for outbound WebSocket connections.119When using [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry), model traffic and authentication go to your provider instead of `api.anthropic.com`, `claude.ai`, or `platform.claude.com`. The WebFetch tool still calls `api.anthropic.com` for its [domain safety check](/en/data-usage#webfetch-domain-safety-check) unless you set `skipWebFetchPreflight: true` in [settings](/en/settings).

121 120 

122[Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review) connect to your repositories from Anthropic-managed infrastructure. If your GitHub Enterprise Cloud organization restricts access by IP address, enable [IP allow list inheritance for installed GitHub Apps](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address) instead, or to configure other firewalls, see the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).121[Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review) connect to your repositories from Anthropic-managed infrastructure. If your GitHub Enterprise Cloud organization restricts access by IP address, enable [IP allow list inheritance for installed GitHub Apps](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#allowing-access-by-github-apps). The Claude GitHub App registers its IP ranges, so enabling this setting allows access without manual configuration. To [add the ranges to your allow list manually](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization#adding-an-allowed-ip-address) instead, or to configure other firewalls, see the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).

123 122 

Details

87[Define how the assistant should behave in this style...]87[Define how the assistant should behave in this style...]

88```88```

89 89 

90You can save these files at the user level (`~/.claude/output-styles`) or90You can save these files at three levels:

91project level (`.claude/output-styles`). [Plugins](/en/plugins-reference) can91 

92also ship output styles in an `output-styles/` directory.92* User: `~/.claude/output-styles`

93* Project: `.claude/output-styles`

94* Managed policy: `.claude/output-styles` inside the [managed settings directory](/en/settings#settings-files)

95 

96[Plugins](/en/plugins-reference) can also ship output styles in an `output-styles/` directory.

93 97 

94### Frontmatter98### Frontmatter

95 99 

96Output style files support frontmatter for specifying metadata:100Output style files support frontmatter for specifying metadata:

97 101 

98| Frontmatter | Purpose | Default |102| Frontmatter | Purpose | Default |

99| :------------------------- | :-------------------------------------------------------------------------- | :---------------------- |103| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------- |

100| `name` | Name of the output style, if not the file name | Inherits from file name |104| `name` | Name of the output style, if not the file name | Inherits from file name |

101| `description` | Description of the output style, shown in the `/config` picker | None |105| `description` | Description of the output style, shown in the `/config` picker | None |

102| `keep-coding-instructions` | Whether to keep the parts of Claude Code's system prompt related to coding. | false |106| `keep-coding-instructions` | Whether to keep the parts of Claude Code's system prompt related to coding. | false |

107| `force-for-plugin` | Plugin output styles only: apply this style automatically whenever the plugin is enabled, without requiring users to select it. Overrides the user's `outputStyle` setting. If multiple enabled plugins set this, the first one loaded wins. | false |

103 108 

104## Comparisons to related features109## Comparisons to related features

105 110 

overview.md +5 −3

Details

40 40 

41 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.41 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

42 42 

43 **Native Windows setups require [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it. WSL setups do not need it.43 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

44 44 

45 <Info>45 <Info>

46 Native installations automatically update in the background to keep you on the latest version.46 Native installations automatically update in the background to keep you on the latest version.


70 </Tab>70 </Tab>

71 </Tabs>71 </Tabs>

72 72 

73 You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

74 

73 Then start Claude Code in any project:75 Then start Claude Code in any project:

74 76 

75 ```bash theme={null}77 ```bash theme={null}


80 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/en/quickstart)82 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/en/quickstart)

81 83 

82 <Tip>84 <Tip>

83 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.85 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [installation troubleshooting](/en/troubleshoot-install) if you hit issues.

84 </Tip>86 </Tip>

85 </Tab>87 </Tab>

86 88 


162 <Accordion title="Customize with instructions, skills, and hooks" icon="sliders">164 <Accordion title="Customize with instructions, skills, and hooks" icon="sliders">

163 [`CLAUDE.md`](/en/memory) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds [auto memory](/en/memory#auto-memory) as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.165 [`CLAUDE.md`](/en/memory) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds [auto memory](/en/memory#auto-memory) as it works, saving learnings like build commands and debugging insights across sessions without you writing anything.

164 166 

165 Create [custom commands](/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.167 Create [skills](/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.

166 168 

167 [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.169 [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.

168 </Accordion>170 </Accordion>

Details

19| [`plan`](#analyze-before-you-edit-with-plan-mode) | Reads only | Exploring a codebase before changing it |19| [`plan`](#analyze-before-you-edit-with-plan-mode) | Reads only | Exploring a codebase before changing it |

20| [`auto`](#eliminate-prompts-with-auto-mode) | Everything, with background safety checks | Long tasks, reducing prompt fatigue |20| [`auto`](#eliminate-prompts-with-auto-mode) | Everything, with background safety checks | Long tasks, reducing prompt fatigue |

21| [`dontAsk`](#allow-only-pre-approved-tools-with-dontask-mode) | Only pre-approved tools | Locked-down CI and scripts |21| [`dontAsk`](#allow-only-pre-approved-tools-with-dontask-mode) | Only pre-approved tools | Locked-down CI and scripts |

22| [`bypassPermissions`](#skip-all-checks-with-bypasspermissions-mode) | Everything except protected paths | Isolated containers and VMs only |22| [`bypassPermissions`](#skip-all-checks-with-bypasspermissions-mode) | Everything | Isolated containers and VMs only |

23 23 

24Regardless of mode, writes to [protected paths](#protected-paths) are never auto-approved, guarding repository state and Claude's own configuration against accidental corruption.24In every mode except `bypassPermissions`, writes to [protected paths](#protected-paths) are never auto-approved, guarding repository state and Claude's own configuration against accidental corruption.

25 25 

26Modes set the baseline. Layer [permission rules](/en/permissions#manage-permissions) on top to pre-approve or block specific tools in any mode except `bypassPermissions`, which skips the permission layer entirely.26Modes set the baseline. Layer [permission rules](/en/permissions#manage-permissions) on top to pre-approve or block specific tools in any mode except `bypassPermissions`, which skips the permission layer entirely.

27 27 


33 <Tab title="CLI">33 <Tab title="CLI">

34 **During a session**: press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Not every mode is in the default cycle:34 **During a session**: press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Not every mode is in the default cycle:

35 35 

36 * `auto`: appears after you opt in with `--enable-auto-mode` or the persisted equivalent in settings36 * `auto`: appears when your account meets the [auto mode requirements](#eliminate-prompts-with-auto-mode); cycling to auto shows an opt-in prompt until you accept it, or select **No, don't ask again** to remove auto from the cycle

37 * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it37 * `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it

38 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`38 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`

39 39 


108 108 

109In addition to file edits, `acceptEdits` mode auto-approves common filesystem Bash commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, and `sed`. These commands are also auto-approved when prefixed with safe environment variables such as `LANG=C` or `NO_COLOR=1`, or process wrappers such as `timeout`, `nice`, or `nohup`. Like file edits, auto-approval applies only to paths inside your working directory or `additionalDirectories`. Paths outside that scope, writes to [protected paths](#protected-paths), and all other Bash commands still prompt.109In addition to file edits, `acceptEdits` mode auto-approves common filesystem Bash commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, and `sed`. These commands are also auto-approved when prefixed with safe environment variables such as `LANG=C` or `NO_COLOR=1`, or process wrappers such as `timeout`, `nice`, or `nohup`. Like file edits, auto-approval applies only to paths inside your working directory or `additionalDirectories`. Paths outside that scope, writes to [protected paths](#protected-paths), and all other Bash commands still prompt.

110 110 

111When the [PowerShell tool](/en/tools-reference#powershell-tool) is enabled, `acceptEdits` mode also auto-approves `Set-Content`, `Add-Content`, `Clear-Content`, and `Remove-Item` on in-scope paths, along with their common aliases. The same scope and protected-path rules apply.

112 

111Use `acceptEdits` when you want to review changes in your editor or via `git diff` after the fact rather than approving each edit inline. Press `Shift+Tab` once from default mode to enter it, or start with it directly:113Use `acceptEdits` when you want to review changes in your editor or via `git diff` after the fact rather than approving each edit inline. Press `Shift+Tab` once from default mode to enter it, or start with it directly:

112 114 

113```bash theme={null}115```bash theme={null}


126 128 

127Press `Shift+Tab` again to leave plan mode without approving a plan.129Press `Shift+Tab` again to leave plan mode without approving a plan.

128 130 

131### Review and approve a plan

132 

129When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:133When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:

130 134 

131* Approve and start in auto mode135* Approve and start in auto mode


134* Keep planning with feedback138* Keep planning with feedback

135* Refine with [Ultraplan](/en/ultraplan) for browser-based review139* Refine with [Ultraplan](/en/ultraplan) for browser-based review

136 140 

137Each approve option also offers to clear the planning context first.141Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When [`showClearContextOnPlanAccept`](/en/settings#available-settings) is enabled, each approve option also offers to clear the planning context first.

142 

143Accepting a plan also names the session from the plan content automatically, unless you've already set a name with `--name` or `/rename`.

144 

145### Set plan mode as the default

146 

147To make plan mode the default for a project, set `defaultMode` in `.claude/settings.json`:

148 

149```json theme={null}

150{

151 "permissions": {

152 "defaultMode": "plan"

153 }

154}

155```

138 156 

139## Eliminate prompts with auto mode157## Eliminate prompts with auto mode

140 158 


150 168 

151Auto mode is available only when your account meets all of these requirements:169Auto mode is available only when your account meets all of these requirements:

152 170 

153* **Plan**: Team, Enterprise, or API. Not available on Pro or Max.171* **Plan**: Max, Team, Enterprise, or API. Not available on Pro.

154* **Admin**: on Team and Enterprise, an admin must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Admins can also lock it off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/en/permissions#managed-settings).172* **Admin**: on Team and Enterprise, an admin must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code) before users can turn it on. Admins can also lock it off by setting `permissions.disableAutoMode` to `"disable"` in [managed settings](/en/permissions#managed-settings).

155* **Model**: Claude Sonnet 4.6 or Opus 4.6. Not available on Haiku or claude-3 models.173* **Model**: Claude Sonnet 4.6, Opus 4.6, or Opus 4.7 on Team, Enterprise, and API plans; Claude Opus 4.7 only on Max plans. Other models, including Haiku and claude-3 models, are not supported.

156* **Provider**: Anthropic API only. Not available on Bedrock, Vertex, or Foundry.174* **Provider**: Anthropic API only. Not available on Bedrock, Vertex, or Foundry.

157 175 

158If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage.176If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode "cannot determine the safety" of an action is a transient classifier outage; see the [error reference](/en/errors#auto-mode-cannot-determine-the-safety-of-an-action).

159 

160Once enabled, start with the flag and `auto` joins the `Shift+Tab` cycle:

161 

162```bash theme={null}

163claude --enable-auto-mode

164```

165 177 

166### What the classifier blocks by default178### What the classifier blocks by default

167 179 

168The classifier trusts your working directory and your repo's configured remotes. Everything else is treated as external until you [configure trusted infrastructure](/en/permissions#configure-the-auto-mode-classifier).180The classifier trusts your working directory and your repo's configured remotes. Everything else is treated as external until you [configure trusted infrastructure](/en/auto-mode-config).

169 181 

170**Blocked by default**:182**Blocked by default**:

171 183 


185* Reading `.env` and sending credentials to their matching API197* Reading `.env` and sending credentials to their matching API

186* Read-only HTTP requests198* Read-only HTTP requests

187* Pushing to the branch you started on or one Claude created199* Pushing to the branch you started on or one Claude created

188* Sandbox network access requests

189 200 

190Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure the auto mode classifier](/en/permissions#configure-the-auto-mode-classifier).201Sandbox network access requests are routed through the classifier rather than allowed by default. Run `claude auto-mode defaults` to see the full rule lists. If routine actions get blocked, an administrator can add trusted repos, buckets, and services via the `autoMode.environment` setting: see [Configure auto mode](/en/auto-mode-config).

202 

203### Boundaries you state in conversation

204 

205The classifier treats boundaries you state in the conversation as a block signal. If you tell Claude "don't push" or "wait until I review before deploying", the classifier blocks matching actions even when the default rules would allow them. A boundary stays in force until you lift it in a later message. Claude's own judgment that a condition was met does not lift it.

206 

207Boundaries are not stored as rules. The classifier re-reads them from the transcript on each check, so a boundary can be lost if [context compaction](/en/costs#reduce-token-usage) removes the message that stated it. For a hard guarantee, add a [deny rule](/en/permissions#permission-rule-syntax) instead.

191 208 

192### When auto mode falls back209### When auto mode falls back

193 210 


197 214 

198In [non-interactive mode](/en/headless) with the `-p` flag, repeated blocks abort the session since there is no user to prompt.215In [non-interactive mode](/en/headless) with the `-p` flag, repeated blocks abort the session since there is no user to prompt.

199 216 

200Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator [configure trusted infrastructure](/en/permissions#configure-the-auto-mode-classifier).217Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator [configure trusted infrastructure](/en/auto-mode-config).

201 218 

202<AccordionGroup>219<AccordionGroup>

203 <Accordion title="How the classifier evaluates actions">220 <Accordion title="How the classifier evaluates actions">


210 227 

211 On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:228 On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:

212 229 

213 * Blanket `Bash(*)`230 * Blanket `Bash(*)` or `PowerShell(*)`

214 * Wildcarded interpreters like `Bash(python*)`231 * Wildcarded interpreters like `Bash(python*)`

215 * Package-manager run commands232 * Package-manager run commands

216 * `Agent` allow rules233 * `Agent` allow rules


229 </Accordion>246 </Accordion>

230 247 

231 <Accordion title="Cost and latency">248 <Accordion title="Cost and latency">

232 The classifier currently runs on Claude Sonnet 4.6 regardless of your main session model. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations.249 The classifier runs on a server-configured model that is independent of your `/model` selection, so switching models does not change classifier availability. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations.

233 </Accordion>250 </Accordion>

234</AccordionGroup>251</AccordionGroup>

235 252 

236## Allow only pre-approved tools with dontAsk mode253## Allow only pre-approved tools with dontAsk mode

237 254 

238`dontAsk` mode auto-denies every tool that is not explicitly allowed. Only actions matching your `permissions.allow` rules can execute; explicit `ask` rules are also denied rather than prompting. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do.255`dontAsk` mode auto-denies every tool call that would otherwise prompt. Only actions matching your `permissions.allow` rules and [read-only Bash commands](/en/permissions#read-only-commands) can execute; explicit `ask` rules are denied rather than prompting. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do.

239 256 

240Set it at startup with the flag:257Set it at startup with the flag:

241 258 


245 262 

246## Skip all checks with bypassPermissions mode263## Skip all checks with bypassPermissions mode

247 264 

248`bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately. Writes to [protected paths](#protected-paths) are the only actions that still prompt. Only use this mode in isolated environments like containers, VMs, or devcontainers without internet access, where Claude Code cannot damage your host system.265`bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately. As of v2.1.126 this includes writes to [protected paths](#protected-paths), which earlier versions still prompted for. Removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system.

249 266 

250You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:267You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:

251 268 


261 278 

262## Protected paths279## Protected paths

263 280 

264Writes to a small set of paths are never auto-approved, in every mode. This prevents accidental corruption of repository state and Claude's own configuration. In `default`, `acceptEdits`, `plan`, and `bypassPermissions` these writes prompt; in `auto` they route to the classifier; in `dontAsk` they are denied.281Writes to a small set of paths are never auto-approved, in every mode except `bypassPermissions`. This prevents accidental corruption of repository state and Claude's own configuration. In `default`, `acceptEdits`, and `plan` these writes prompt; in `auto` they route to the classifier; in `dontAsk` they are denied; in `bypassPermissions` they are allowed.

265 282 

266Protected directories:283Protected directories:

267 284 


280 297 

281## See also298## See also

282 299 

283* [Permissions](/en/permissions): allow, ask, and deny rules; auto mode classifier configuration; managed policies300* [Permissions](/en/permissions): allow, ask, and deny rules; managed policies

301* [Configure auto mode](/en/auto-mode-config): tell the classifier which infrastructure your organization trusts

284* [Hooks](/en/hooks): custom permission logic via `PreToolUse` and `PermissionRequest` hooks302* [Hooks](/en/hooks): custom permission logic via `PreToolUse` and `PermissionRequest` hooks

285* [Ultraplan](/en/ultraplan): run plan mode in a Claude Code on the web session with browser-based review303* [Ultraplan](/en/ultraplan): run plan mode in a Claude Code on the web session with browser-based review

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

permissions.md +60 −125

Details

36| :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |36| :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |

37| `default` | Standard behavior: prompts for permission on first use of each tool |37| `default` | Standard behavior: prompts for permission on first use of each tool |

38| `acceptEdits` | Automatically accepts file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) for paths in the working directory or `additionalDirectories` |38| `acceptEdits` | Automatically accepts file edits and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) for paths in the working directory or `additionalDirectories` |

39| `plan` | Plan Mode: Claude can analyze but not modify files or execute commands |39| `plan` | Plan Mode: Claude reads files and runs read-only shell commands to explore but does not edit your source files |

40| `auto` | Auto-approves tool calls with background safety checks that verify actions align with your request. Currently a research preview |40| `auto` | Auto-approves tool calls with background safety checks that verify actions align with your request. Currently a research preview |

41| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules |41| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules |

42| `bypassPermissions` | Skips permission prompts except for writes to protected directories (see warning below) |42| `bypassPermissions` | Skips all permission prompts. Root and home directory removals such as `rm -rf /` still prompt as a circuit breaker |

43 43 

44<Warning>44<Warning>

45 `bypassPermissions` mode skips permission prompts. Writes to `.git`, `.claude`, `.vscode`, `.idea`, and `.husky` directories still prompt for confirmation to prevent accidental corruption of repository state, editor configuration, and git hooks. Writes to `.claude/commands`, `.claude/agents`, and `.claude/skills` are exempt and do not prompt, because Claude routinely writes there when creating skills, subagents, and commands. Only use this mode in isolated environments like containers or VMs where Claude Code cannot cause damage. Administrators can prevent this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](#managed-settings).45 `bypassPermissions` mode skips all permission prompts, including writes to `.git`, `.claude`, `.vscode`, `.idea`, and `.husky`. Removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. Only use this mode in isolated environments like containers or VMs where Claude Code cannot cause damage. Administrators can prevent this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](#managed-settings).

46</Warning>46</Warning>

47 47 

48To prevent `bypassPermissions` or `auto` mode from being used, set `permissions.disableBypassPermissionsMode` or `permissions.disableAutoMode` to `"disable"` in any [settings file](/en/settings#settings-files). These are most useful in [managed settings](#managed-settings) where they cannot be overridden.48To prevent `bypassPermissions` or `auto` mode from being used, set `permissions.disableBypassPermissionsMode` or `permissions.disableAutoMode` to `"disable"` in any [settings file](/en/settings#settings-files). These are most useful in [managed settings](#managed-settings) where they cannot be overridden.


96 96 

97The space before `*` matters: `Bash(ls *)` matches `ls -la` but not `lsof`, while `Bash(ls*)` matches both. The `:*` suffix is an equivalent way to write a trailing wildcard, so `Bash(ls:*)` matches the same commands as `Bash(ls *)`.97The space before `*` matters: `Bash(ls *)` matches `ls -la` but not `lsof`, while `Bash(ls*)` matches both. The `:*` suffix is an equivalent way to write a trailing wildcard, so `Bash(ls:*)` matches the same commands as `Bash(ls *)`.

98 98 

99The permission dialog writes the `:*` form when you select "Yes, don't ask again" for a command prefix. This form is only recognized at the end of a pattern. In a pattern like `Bash(git:* push)`, the colon is treated as a literal character and won't match git commands.99The permission dialog writes the space-separated form when you select "Yes, don't ask again" for a command prefix. The `:*` form is only recognized at the end of a pattern. In a pattern like `Bash(git:* push)`, the colon is treated as a literal character and won't match git commands.

100 100 

101## Tool-specific permission rules101## Tool-specific permission rules

102 102 


110* `Bash(* install)` matches any command ending with ` install`110* `Bash(* install)` matches any command ending with ` install`

111* `Bash(git * main)` matches commands like `git checkout main` and `git log --oneline main`111* `Bash(git * main)` matches commands like `git checkout main` and `git log --oneline main`

112 112 

113A single `*` matches any sequence of characters including spaces, so one wildcard can span multiple arguments. `Bash(git:*)` matches `git log --oneline --all`, and `Bash(git * main)` matches `git push origin main` as well as `git merge main`.113A single `*` matches any sequence of characters including spaces, so one wildcard can span multiple arguments. `Bash(git *)` matches `git log --oneline --all`, and `Bash(git * main)` matches `git push origin main` as well as `git merge main`.

114 114 

115When `*` 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.115When `*` 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.

116 116 


130 130 

131This wrapper list is built in and is not configurable. Development environment runners such as `direnv exec`, `devbox run`, `mise exec`, `npx`, and `docker exec` are not in the list. Because these tools execute their arguments as a command, a rule like `Bash(devbox run *)` matches whatever comes after `run`, including `devbox run rm -rf .`. To approve work inside an environment runner, write a specific rule that includes both the runner and the inner command, such as `Bash(devbox run npm test)`. Add one rule per inner command you want to allow.131This wrapper list is built in and is not configurable. Development environment runners such as `direnv exec`, `devbox run`, `mise exec`, `npx`, and `docker exec` are not in the list. Because these tools execute their arguments as a command, a rule like `Bash(devbox run *)` matches whatever comes after `run`, including `devbox run rm -rf .`. To approve work inside an environment runner, write a specific rule that includes both the runner and the inner command, such as `Bash(devbox run npm test)`. Add one rule per inner command you want to allow.

132 132 

133Exec wrappers such as `watch`, `setsid`, `ionice`, and `flock` always prompt and cannot be auto-approved by a prefix rule like `Bash(watch *)`. The same applies to `find` with `-exec` or `-delete`: a `Bash(find *)` rule does not cover these forms. To approve a specific invocation, write an exact-match rule for the full command string.

134 

135#### Read-only commands

136 

137Claude Code recognizes a built-in set of Bash commands as read-only and runs them without a permission prompt in every mode. These include `ls`, `cat`, `head`, `tail`, `grep`, `find`, `wc`, `diff`, `stat`, `du`, `cd`, and read-only forms of `git`. The set is not configurable; to require a prompt for one of these commands, add an `ask` or `deny` rule for it.

138 

139Unquoted glob patterns are permitted for commands whose every flag is read-only, so `ls *.ts` and `wc -l src/*.py` run without a prompt. Commands with write-capable or exec-capable flags, such as `find`, `sort`, `sed`, and `git`, still prompt when an unquoted glob is present because the glob could expand to a flag like `-delete`.

140 

141A `cd` into a path inside your working directory or an [additional directory](#working-directories) is also read-only. A compound command like `cd packages/api && ls` runs without a prompt when each part qualifies on its own. Combining `cd` with `git` in one compound command always prompts, regardless of the target directory.

142 

133<Warning>143<Warning>

134 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:144 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:

135 145 


148 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.158 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.

149</Warning>159</Warning>

150 160 

161### PowerShell

162 

163PowerShell permission rules use the same shape as Bash rules. Wildcards with `*` match at any position, the `:*` suffix is equivalent to a trailing ` *`, and a bare `PowerShell` or `PowerShell(*)` matches every command. This configuration allows `Get-ChildItem` and `git commit` commands while blocking `Remove-Item`:

164 

165```json theme={null}

166{

167 "permissions": {

168 "allow": [

169 "PowerShell(Get-ChildItem *)",

170 "PowerShell(git commit *)"

171 ],

172 "deny": [

173 "PowerShell(Remove-Item *)"

174 ]

175 }

176}

177```

178 

179Common aliases are canonicalized before matching. A rule written for the cmdlet name also matches its aliases, so `PowerShell(Get-ChildItem *)` matches `gci`, `ls`, and `dir` as well. Matching is case-insensitive.

180 

181Claude Code parses the PowerShell AST and checks each command in a compound command independently. Pipeline operators `|`, statement separators `;`, and on PowerShell 7+ the chain operators `&&` and `||` split a compound command into subcommands. A rule must match every subcommand for the compound command to be allowed.

182 

151### Read and Edit183### Read and Edit

152 184 

153`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.185`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.


178* `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt`210* `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt`

179* `Read(src/**)`: reads from `<current-directory>/src/`211* `Read(src/**)`: reads from `<current-directory>/src/`

180 212 

213A rule only matches files under its anchor, so the anchor determines how far a deny rule reaches. Bare filenames follow gitignore semantics and match at any depth, so `Read(.env)` and `Read(**/.env)` are equivalent:

214 

215| Deny rule | Blocks | Does not block |

216| ------------------------------- | -------------------------------------------- | ---------------------------------------------------- |

217| `Read(.env)` or `Read(**/.env)` | any `.env` at or under the current directory | `.env` in a parent directory or another project |

218| `Read(//**/.env)` | any `.env` anywhere on the filesystem | nothing; the rule is anchored at the filesystem root |

219 

181<Note>220<Note>

182 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`.221 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`.

183</Note>222</Note>

184 223 

224When Claude accesses a symlink, permission rules check two paths: the symlink itself and the file it resolves to. Allow and deny rules treat that pair differently: allow rules fall back to prompting you, while deny rules block outright.

225 

226* **Allow rules**: apply only when both the symlink path and its target match. A symlink inside an allowed directory that points outside it still prompts you.

227* **Deny rules**: apply when either the symlink path or its target matches. A symlink that points to a denied file is itself denied.

228 

229For example, with `Read(./project/**)` allowed and `Read(~/.ssh/**)` denied, a symlink at `./project/key` pointing to `~/.ssh/id_rsa` is blocked: the target fails the allow rule and matches the deny rule.

230 

185### WebFetch231### WebFetch

186 232 

187* `WebFetch(domain:example.com)` matches fetch requests to example.com233* `WebFetch(domain:example.com)` matches fetch requests to example.com


257 303 

258* Permission deny rules block Claude from even attempting to access restricted resources304* Permission deny rules block Claude from even attempting to access restricted resources

259* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making305* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making

260* Filesystem restrictions in the sandbox use Read and Edit deny rules, not separate sandbox configuration306* Filesystem restrictions in the sandbox combine the [`sandbox.filesystem`](/en/sandboxing) settings with Read and Edit deny rules; both are merged into the final sandbox boundary

261* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` list307* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` and `deniedDomains` lists

262 308 

263When sandboxing is enabled with `autoAllowBashIfSandboxed: true`, which is the default, sandboxed Bash commands run without prompting even if your permissions include `ask: Bash(*)`. The sandbox boundary substitutes for the per-command prompt. See [sandbox modes](/en/sandboxing#sandbox-modes) to change this behavior.309When sandboxing is enabled with `autoAllowBashIfSandboxed: true`, which is the default, sandboxed Bash commands run without prompting even if your permissions include `ask: Bash(*)`. The sandbox boundary substitutes for the per-command prompt. Explicit deny rules still apply, and `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a prompt. See [sandbox modes](/en/sandboxing#sandbox-modes) to change this behavior.

264 310 

265## Managed settings311## Managed settings

266 312 


271The following settings are only read from managed settings. Placing them in user or project settings files has no effect.317The following settings are only read from managed settings. Placing them in user or project settings files has no effect.

272 318 

273| Setting | Description |319| Setting | Description |

274| :--------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |320| :--------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

275| `allowedChannelPlugins` | Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](/en/channels#restrict-which-channel-plugins-can-run) |321| `allowedChannelPlugins` | Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](/en/channels#restrict-which-channel-plugins-can-run) |

276| `allowManagedHooksOnly` | When `true`, only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked |322| `allowManagedHooksOnly` | When `true`, only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked |

277| `allowManagedMcpServersOnly` | When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) |323| `allowManagedMcpServersOnly` | When `true`, only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) |

278| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |324| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |

279| `blockedMarketplaces` | Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |325| `blockedMarketplaces` | Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

280| `channelsEnabled` | Allow [channels](/en/channels) for Team and Enterprise users. Unset or `false` blocks channel message delivery regardless of what users pass to `--channels` |326| `channelsEnabled` | Allow [channels](/en/channels) for the organization. See [enterprise controls](/en/channels#enterprise-controls) for the default on each plan |

281| `forceRemoteSettingsRefresh` | When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](/en/server-managed-settings#enforce-fail-closed-startup) |327| `forceRemoteSettingsRefresh` | When `true`, blocks CLI startup until remote managed settings are freshly fetched and exits if the fetch fails. See [fail-closed enforcement](/en/server-managed-settings#enforce-fail-closed-startup) |

282| `pluginTrustMessage` | Custom message appended to the plugin trust warning shown before installation |328| `pluginTrustMessage` | Custom message appended to the plugin trust warning shown before installation |

283| `sandbox.filesystem.allowManagedReadPathsOnly` | When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources |329| `sandbox.filesystem.allowManagedReadPathsOnly` | When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources |

284| `sandbox.network.allowManagedDomainsOnly` | When `true`, only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Non-allowed domains are blocked automatically without prompting the user. Denied domains still merge from all sources |330| `sandbox.network.allowManagedDomainsOnly` | When `true`, only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Non-allowed domains are blocked automatically without prompting the user. Denied domains still merge from all sources |

285| `strictKnownMarketplaces` | Controls which plugin marketplaces users can add. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |331| `strictKnownMarketplaces` | Controls which plugin marketplace sources users can add and install plugins from. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

332| `wslInheritsWindowsSettings` | When `true` in the Windows HKLM registry key or `C:\Program Files\ClaudeCode\managed-settings.json`, WSL reads managed settings from the Windows policy chain in addition to `/etc/claude-code`. See [Settings files](/en/settings#settings-files) |

286 333 

287`disableBypassPermissionsMode` is typically placed in managed settings to enforce organizational policy, but it works from any scope. A user can set it in their own settings to lock themselves out of bypass mode.334`disableBypassPermissionsMode` is typically placed in managed settings to enforce organizational policy, but it works from any scope. A user can set it in their own settings to lock themselves out of bypass mode.

288 335 

289<Note>336<Note>

290 Access to [Remote Control](/en/remote-control) and [web sessions](/en/claude-code-on-the-web) is not controlled by a managed settings key. On Team and Enterprise plans, an admin enables or disables these features in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).337 On Team and Enterprise plans, an admin enables or disables [Remote Control](/en/remote-control) and [web sessions](/en/claude-code-on-the-web) organization-wide in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code). Remote Control can additionally be disabled per device with the [`disableRemoteControl`](/en/settings#available-settings) managed setting. Web sessions have no per-device managed settings key.

291</Note>338</Note>

292 339 

293## Review auto mode denials

294 

295When [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) denies a tool call, a notification appears and the denied action is recorded in `/permissions` under the Recently denied tab. Press `r` on a denied action to mark it for retry: when you exit the dialog, Claude Code sends a message telling the model it may retry that tool call and resumes the conversation.

296 

297To react to denials programmatically, use the [`PermissionDenied` hook](/en/hooks#permissiondenied).

298 

299## Configure the auto mode classifier

300 

301[Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) uses a classifier model to decide whether each action is safe to run without prompting. Out of the box it trusts only the working directory and, if present, the current repo's remotes. Actions like pushing to your company's source control org or writing to a team cloud bucket will be blocked as potential data exfiltration. The `autoMode` settings block lets you tell the classifier which infrastructure your organization trusts.

302 

303The classifier reads `autoMode` from user settings, `.claude/settings.local.json`, and managed settings. It does not read from shared project settings in `.claude/settings.json`, because a checked-in repo could otherwise inject its own allow rules.

304 

305| Scope | File | Use for |

306| :------------------------- | :---------------------------- | :-------------------------------------------------- |

307| One developer | `~/.claude/settings.json` | Personal trusted infrastructure |

308| One project, one developer | `.claude/settings.local.json` | Per-project trusted buckets or services, gitignored |

309| Organization-wide | Managed settings | Trusted infrastructure enforced for all developers |

310 

311Entries from each scope are combined. A developer can extend `environment`, `allow`, and `soft_deny` with personal entries but cannot remove entries that managed settings provide. Because allow rules act as exceptions to block rules inside the classifier, a developer-added `allow` entry can override an organization `soft_deny` entry: the combination is additive, not a hard policy boundary. If you need a rule that developers cannot work around, use `permissions.deny` in managed settings instead, which blocks actions before the classifier is consulted.

312 

313### Define trusted infrastructure

314 

315For most organizations, `autoMode.environment` is the only field you need to set. It tells the classifier which repos, buckets, and domains are trusted, without touching the built-in block and allow rules. The classifier uses `environment` to decide what "external" means: any destination not listed is a potential exfiltration target.

316 

317```json theme={null}

318{

319 "autoMode": {

320 "environment": [

321 "Source control: github.example.com/acme-corp and all repos under it",

322 "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",

323 "Trusted internal domains: *.corp.example.com, api.internal.example.com",

324 "Key internal services: Jenkins at ci.example.com, Artifactory at artifacts.example.com"

325 ]

326 }

327}

328```

329 

330Entries are prose, not regex or tool patterns. The classifier reads them as natural-language rules. Write them the way you would describe your infrastructure to a new engineer. A thorough environment section covers:

331 

332* **Organization**: your company name and what Claude Code is primarily used for, like software development, infrastructure automation, or data engineering

333* **Source control**: every GitHub, GitLab, or Bitbucket org your developers push to

334* **Cloud providers and trusted buckets**: bucket names or prefixes that Claude should be able to read from and write to

335* **Trusted internal domains**: hostnames for APIs, dashboards, and services inside your network, like `*.internal.example.com`

336* **Key internal services**: CI, artifact registries, internal package indexes, incident tooling

337* **Additional context**: regulated-industry constraints, multi-tenant infrastructure, or compliance requirements that affect what the classifier should treat as risky

338 

339A useful starting template: fill in the bracketed fields and remove any lines that don't apply:

340 

341```json theme={null}

342{

343 "autoMode": {

344 "environment": [

345 "Organization: {COMPANY_NAME}. Primary use: {PRIMARY_USE_CASE, e.g. software development, infrastructure automation}",

346 "Source control: {SOURCE_CONTROL, e.g. GitHub org github.example.com/acme-corp}",

347 "Cloud provider(s): {CLOUD_PROVIDERS, e.g. AWS, GCP, Azure}",

348 "Trusted cloud buckets: {TRUSTED_BUCKETS, e.g. s3://acme-builds, gs://acme-datasets}",

349 "Trusted internal domains: {TRUSTED_DOMAINS, e.g. *.internal.example.com, api.example.com}",

350 "Key internal services: {SERVICES, e.g. Jenkins at ci.example.com, Artifactory at artifacts.example.com}",

351 "Additional context: {EXTRA, e.g. regulated industry, multi-tenant infrastructure, compliance requirements}"

352 ]

353 }

354}

355```

356 

357The more specific context you give, the better the classifier can distinguish routine internal operations from exfiltration attempts.

358 

359You don't need to fill everything in at once. A reasonable rollout: start with the defaults and add your source control org and key internal services, which resolves the most common false positives like pushing to your own repos. Add trusted domains and cloud buckets next. Fill the rest as blocks come up.

360 

361### Override the block and allow rules

362 

363Two additional fields let you replace the classifier's built-in rule lists: `autoMode.soft_deny` controls what gets blocked, and `autoMode.allow` controls which exceptions apply. Each is an array of prose descriptions, read as natural-language rules.

364 

365Inside the classifier, the precedence is: `soft_deny` rules block first, then `allow` rules override as exceptions, then explicit user intent overrides both. If the user's message directly and specifically describes the exact action Claude is about to take, the classifier allows it even if a `soft_deny` rule matches. General requests don't count: asking Claude to "clean up the repo" does not authorize force-pushing, but asking Claude to "force-push this branch" does.

366 

367To loosen: remove rules from `soft_deny` when the defaults block something your pipeline already guards against with PR review, CI, or staging environments, or add to `allow` when the classifier repeatedly flags a routine pattern the default exceptions don't cover. To tighten: add to `soft_deny` for risks specific to your environment that the defaults miss, or remove from `allow` to hold a default exception to the block rules. In all cases, run `claude auto-mode defaults` to get the full default lists, then copy and edit: never start from an empty list.

368 

369```json theme={null}

370{

371 "autoMode": {

372 "environment": [

373 "Source control: github.example.com/acme-corp and all repos under it"

374 ],

375 "allow": [

376 "Deploying to the staging namespace is allowed: staging is isolated from production and resets nightly",

377 "Writing to s3://acme-scratch/ is allowed: ephemeral bucket with a 7-day lifecycle policy"

378 ],

379 "soft_deny": [

380 "Never run database migrations outside the migrations CLI, even against dev databases",

381 "Never modify files under infra/terraform/prod/: production infrastructure changes go through the review workflow",

382 "...copy full default soft_deny list here first, then add your rules..."

383 ]

384 }

385}

386```

387 

388<Danger>

389 Setting `allow` or `soft_deny` replaces the entire default list for that section. If you set `soft_deny` with a single entry, every built-in block rule is discarded: force push, data exfiltration, `curl | bash`, production deploys, and all other default block rules become allowed. To customize safely, run `claude auto-mode defaults` to print the built-in rules, copy them into your settings file, then review each rule against your own pipeline and risk tolerance. Only remove rules for risks your infrastructure already mitigates.

390</Danger>

391 

392The three sections are evaluated independently, so setting `environment` alone leaves the default `allow` and `soft_deny` lists intact.

393 

394### Inspect the defaults and your effective config

395 

396Because setting `allow` or `soft_deny` replaces the defaults, start any customization by copying the full default lists. Three CLI subcommands help you inspect and validate:

397 

398```bash theme={null}

399claude auto-mode defaults # the built-in environment, allow, and soft_deny rules

400claude auto-mode config # what the classifier actually uses: your settings where set, defaults otherwise

401claude auto-mode critique # get AI feedback on your custom allow and soft_deny rules

402```

403 

404Save the output of `claude auto-mode defaults` to a file, edit the lists to match your policy, and paste the result into your settings file. After saving, run `claude auto-mode config` to confirm the effective rules are what you expect. If you've written custom rules, `claude auto-mode critique` reviews them and flags entries that are ambiguous, redundant, or likely to cause false positives.

405 

406## Settings precedence340## Settings precedence

407 341 

408Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings:342Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings:


424## See also358## See also

425 359 

426* [Settings](/en/settings): complete configuration reference including the permission settings table360* [Settings](/en/settings): complete configuration reference including the permission settings table

361* [Configure auto mode](/en/auto-mode-config): tell the auto mode classifier which infrastructure your organization trusts

427* [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands362* [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands

428* [Authentication](/en/authentication): set up user access to Claude Code363* [Authentication](/en/authentication): set up user access to Claude Code

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

platforms.md +1 −1

Details

21| [Web](/en/claude-code-on-the-web) | Long-running tasks that don't need much steering, or work that should continue when you're offline | Anthropic-managed cloud, continues after you disconnect |21| [Web](/en/claude-code-on-the-web) | Long-running tasks that don't need much steering, or work that should continue when you're offline | Anthropic-managed cloud, continues after you disconnect |

22| Mobile | Starting and monitoring tasks while away from your computer | Cloud sessions from the Claude app for iOS and Android, [Remote Control](/en/remote-control) for local sessions, [Dispatch](/en/desktop#sessions-from-dispatch) to Desktop on Pro and Max |22| Mobile | Starting and monitoring tasks while away from your computer | Cloud sessions from the Claude app for iOS and Android, [Remote Control](/en/remote-control) for local sessions, [Dispatch](/en/desktop#sessions-from-dispatch) to Desktop on Pro and Max |

23 23 

24The CLI is the most complete surface for terminal-native work: scripting, third-party providers, and the Agent SDK are CLI-only. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic's cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch.24The CLI is the most complete surface for terminal-native work: scripting and the Agent SDK are CLI-only. Third-party providers also work in [VS Code](/en/vs-code#use-third-party-providers). Enterprise [Desktop](/en/desktop) deployments support Vertex AI and gateway providers; for Bedrock or Foundry, use the CLI or VS Code instead of Desktop. Desktop and the IDE extensions trade some CLI-only features for visual review and tighter editor integration. The web runs in Anthropic's cloud, so tasks keep going after you disconnect. Mobile is a thin client into those same cloud sessions or into a local session via Remote Control, and can send tasks to Desktop with Dispatch.

25 25 

26You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.26You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.

27 27 

plugin-dependencies.md +153 −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# Constrain plugin dependency versions

6 

7> Declare version constraints on plugin dependencies so your plugin keeps working when an upstream plugin ships a breaking change.

8 

9A plugin can depend on other plugins by listing them in `plugin.json` or in its marketplace entry. By default, a dependency tracks the latest available version, so an upstream release can change the dependency under your plugin without warning. Version constraints let you hold a dependency at a tested version range until you choose to move.

10 

11When you install a plugin that declares dependencies, Claude Code resolves and installs them automatically and lists which dependencies were added at the end of the install output. If a dependency later goes missing, `/reload-plugins` and the background plugin auto-update reinstall it, provided its marketplace is already in your configured marketplaces. Re-running `claude plugin install` on the dependent plugin, or adding a marketplace with `claude plugin marketplace add`, also resolves any outstanding missing dependencies. Dependencies from a marketplace you have not added are left unresolved.

12 

13This guide is for plugin authors who declare dependencies in `plugin.json` and for marketplace maintainers who tag releases. To install plugins that have dependencies, see [Discover and install plugins](/en/discover-plugins). For the full manifest schema, see the [Plugins reference](/en/plugins-reference).

14 

15<Note>

16 Dependency version constraints require Claude Code v2.1.110 or later.

17</Note>

18 

19## Why constrain dependency versions

20 

21Consider an internal marketplace where two teams publish plugins. The platform team maintains `secrets-vault`, an MCP server that wraps a secrets backend. The deploy team maintains `deploy-kit`, which calls `secrets-vault` to fetch credentials during deploys.

22 

23`deploy-kit` is tested against `secrets-vault` v2.1.0. Without a version constraint, the next time the platform team tags a release that renames an MCP tool, auto-update moves every engineer's `secrets-vault` to the new version and `deploy-kit` breaks.

24 

25With a version constraint, `deploy-kit` declares that it needs `secrets-vault` in the `~2.1.0` range. Engineers with `deploy-kit` installed stay on the highest matching `2.1.x` patch. The deploy team upgrades on their own schedule by publishing a new `deploy-kit` version with a wider constraint.

26 

27## Declare a dependency with a version constraint

28 

29List dependencies in the `dependencies` array of your plugin's `.claude-plugin/plugin.json`. Each entry is either a plugin name or an object with a version constraint.

30 

31The following manifest declares one unversioned dependency and one constrained dependency:

32 

33```json .claude-plugin/plugin.json theme={null}

34{

35 "name": "deploy-kit",

36 "version": "3.1.0",

37 "dependencies": [

38 "audit-logger",

39 { "name": "secrets-vault", "version": "~2.1.0" }

40 ]

41}

42```

43 

44An entry can be a bare string with only the plugin name, like `"audit-logger"` in the example above, which depends on whatever version that plugin's marketplace provides. For more control, use an object with these fields:

45 

46| Field | Type | Description |

47| :------------ | :----- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

48| `name` | string | Plugin name. Resolves within the same marketplace as the declaring plugin. Required. |

49| `version` | string | A [semver range](https://github.com/npm/node-semver#ranges) such as `~2.1.0`, `^2.0`, `>=1.4`, or `=2.1.0`. The dependency is fetched at the highest tagged version that satisfies this range. |

50| `marketplace` | string | A different marketplace to resolve `name` in. Cross-marketplace dependencies are blocked unless the target marketplace is listed in [`allowCrossMarketplaceDependenciesOn`](#depend-on-a-plugin-from-another-marketplace) in the root marketplace's `marketplace.json`. |

51 

52The `version` field accepts any expression supported by Node's `semver` package, including caret, tilde, hyphen, and comparator ranges. Pre-release versions such as `2.0.0-beta.1` are excluded unless your range opts in with a pre-release suffix like `^2.0.0-0`.

53 

54## Depend on a plugin from another marketplace

55 

56By default, Claude Code refuses to auto-install a dependency that lives in a different marketplace than the plugin declaring it. This prevents one marketplace from silently pulling in plugins from a source you have not reviewed.

57 

58To allow it, the maintainer of the root marketplace adds the target marketplace name to `allowCrossMarketplaceDependenciesOn` in `marketplace.json`. The root marketplace is the one that hosts the plugin the user is installing; only its allowlist is consulted, so trust does not chain through intermediate marketplaces.

59 

60The following `marketplace.json` allows `deploy-kit` to depend on a plugin from `acme-shared`:

61 

62```json .claude-plugin/marketplace.json theme={null}

63{

64 "name": "acme-tools",

65 "owner": { "name": "Acme" },

66 "allowCrossMarketplaceDependenciesOn": ["acme-shared"],

67 "plugins": [

68 {

69 "name": "deploy-kit",

70 "source": "./deploy-kit",

71 "dependencies": [

72 { "name": "audit-logger", "marketplace": "acme-shared" }

73 ]

74 }

75 ]

76}

77```

78 

79If the field is missing or does not include the target marketplace, install fails with a `cross-marketplace` error naming the field to set. Users can still install the dependency manually first, which satisfies the constraint without changing the allowlist.

80 

81## Tag plugin releases for version resolution

82 

83Version constraints resolve against git tags on the marketplace repository. For Claude Code to find a dependency's available versions, the upstream plugin's releases must be tagged using a specific naming convention.

84 

85Tag each release as `{plugin-name}--v{version}`, where `{version}` matches the `version` field in that commit's `plugin.json`. From the plugin directory, run:

86 

87```bash theme={null}

88claude plugin tag --push

89```

90 

91The `claude plugin tag` command derives the tag name from the plugin's manifest and the enclosing marketplace entry. Before creating the tag, it validates the plugin contents, checks that `plugin.json` and the marketplace entry agree on the version, requires a clean working tree under the plugin directory, and refuses if the tag already exists. Add `--dry-run` to see what would be tagged without creating it. Running `git tag secrets-vault--v2.1.0` directly is equivalent if you keep `plugin.json` and the marketplace entry in sync yourself.

92 

93The plugin name prefix lets one marketplace repository host multiple plugins with independent version lines. The `--v` separator is parsed as a prefix match on the full plugin name, so plugin names that contain hyphens are handled correctly.

94 

95When you install a plugin that declares `{ "name": "secrets-vault", "version": "~2.1.0" }`, Claude Code lists the marketplace's tags, filters to those starting with `secrets-vault--v`, and fetches the highest version satisfying `~2.1.0`. If no matching tag exists, the dependent plugin is disabled with an error listing the available versions.

96 

97The resolved tag's semver is recorded separately from `plugin.json`'s `version`, so constraint checks use the tag that was actually fetched even if `plugin.json` at that commit has a stale value. The cache directory name for a tag-resolved install includes a 12-character commit-SHA suffix, so if a maintainer force-moves a tag to a different commit, the next install gets a fresh cache directory instead of reusing stale content.

98 

99<Note>

100 For `npm` marketplace sources, the constraint does not control which version is fetched, since tag-based resolution applies only to git-backed sources. The constraint is still checked at load time, and the dependent plugin is disabled with `dependency-version-unsatisfied` if the installed version does not satisfy it.

101</Note>

102 

103## How constraints interact

104 

105When several installed plugins constrain the same dependency, Claude Code intersects their ranges and resolves the dependency to the highest version that satisfies all of them. The table below shows how common combinations resolve.

106 

107| Plugin A requires | Plugin B requires | Result |

108| :---------------- | :---------------- | :---------------------------------------------------------------------------------------------- |

109| `^2.0` | `>=2.1` | One install at the highest `2.x` tag at or above `2.1.0`. Both plugins load. |

110| `~2.1` | `~3.0` | Install of plugin B fails with `range-conflict`. Plugin A and the dependency stay as they were. |

111| `=2.1.0` | none | The dependency stays at `2.1.0`. Auto-update skips newer versions while plugin A is installed. |

112 

113Auto-update fetches a constrained dependency at the highest git tag that satisfies every installed plugin's range, rather than at the marketplace's latest version, so the dependency continues to receive updates within its allowed range. If no tag satisfies all ranges, the update is skipped and the skip appears in `/doctor` and the `/plugin` Errors tab, naming the constraining plugin.

114 

115When you uninstall the last plugin that constrains a dependency, the dependency is no longer held and resumes tracking its marketplace entry on the next update.

116 

117## Remove orphaned auto-installed dependencies

118 

119Auto-installed dependencies stay on disk after the plugins that installed them are uninstalled, in case you reinstall a dependent plugin or want to keep using the dependency directly. To clean them up, run `claude plugin prune` to list the auto-installed dependencies that no longer have any installed plugin requiring them and remove them after a confirmation prompt. This requires Claude Code v2.1.121 or later.

120 

121```bash theme={null}

122claude plugin prune

123```

124 

125By default, prune operates at user scope. Use `--scope project` or `--scope local` to target a different scope. Pass `--dry-run` to list what would be removed without changing anything. Pass `-y` to skip the confirmation prompt. When stdin or stdout is not a terminal, prune lists the orphans and exits without removing them unless `-y` is passed.

126 

127To prune as part of an uninstall, pass `--prune` to `claude plugin uninstall`. After removing the named plugin, Claude Code scans for and removes any auto-installed dependencies that are now orphaned. Plugins you installed yourself are never pruned, only those installed automatically through another plugin's `dependencies` array.

128 

129For example, to uninstall `deploy-kit` and clean up the dependencies it leaves behind:

130 

131```bash theme={null}

132claude plugin uninstall deploy-kit --prune

133```

134 

135## Resolve dependency errors

136 

137Dependency problems surface in `claude plugin list`, in the `/plugin` interface, and in `/doctor`. The affected plugin is disabled until you resolve the error. The most common errors and their fixes are listed below.

138 

139| Error | Meaning | How to resolve |

140| :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

141| `dependency-unsatisfied` | A declared dependency is not installed, or it is installed but disabled. | Run the `claude plugin install` command shown in the error message. If the dependency's marketplace is not yet configured, add it with `claude plugin marketplace add` and Claude Code resolves the dependency automatically. If the dependency is disabled, enable it. |

142| `range-conflict` | The version requirements for a dependency cannot be combined. The error message names the cause: no version satisfies all of the ranges, a range is not valid semver syntax, or the combined ranges are too complex to intersect. | Uninstall or update one of the conflicting plugins, fix any invalid `version` string, simplify long `\|\|` chains, or ask the upstream author to widen its constraint. |

143| `dependency-version-unsatisfied` | The installed dependency's version is outside this plugin's declared range. | Run `claude plugin install <dependency>@<marketplace>` to re-resolve the dependency against all current constraints. |

144| `no-matching-tag` | The dependency's repository has no `{name}--v*` tag satisfying the range. | Check that the upstream has tagged releases using the convention above, or relax your range. |

145 

146To check for these errors programmatically, run `claude plugin list --json` and read the `errors` field on each plugin.

147 

148## See also

149 

150* [Create plugins](/en/plugins): build plugins with skills, agents, and hooks

151* [Create and distribute a plugin marketplace](/en/plugin-marketplaces): host plugins for your team

152* [Plugins reference](/en/plugins-reference#plugin-manifest-schema): the full `plugin.json` schema

153* [Version management](/en/plugins-reference#version-management): how a plugin's own version is resolved and used as the cache key

Details

23 23 

24## Walkthrough: create a local marketplace24## Walkthrough: create a local marketplace

25 25 

26This example creates a marketplace with one plugin: a `/quality-review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.26This example creates a marketplace with one plugin: a `quality-review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.

27 27 

28<Steps>28<Steps>

29 <Step title="Create the directory structure">29 <Step title="Create the directory structure">


35 </Step>35 </Step>

36 36 

37 <Step title="Create the skill">37 <Step title="Create the skill">

38 Create a `SKILL.md` file that defines what the `/quality-review` skill does.38 Create a `SKILL.md` file that defines what the `quality-review` skill does.

39 39 

40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}

41 ---41 ---


59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}

60 {60 {

61 "name": "quality-review-plugin",61 "name": "quality-review-plugin",

62 "description": "Adds a /quality-review skill for quick code reviews",62 "description": "Adds a quality-review skill for quick code reviews",

63 "version": "1.0.0"63 "version": "1.0.0"

64 }64 }

65 ```65 ```

66 

67 <Note>

68 Setting `version` means users only receive updates when you change this field, so bump it on every release. If you omit `version` and host this marketplace in git, every commit automatically counts as a new version. See [Version resolution](#version-resolution-and-release-channels) to choose the right approach.

69 </Note>

66 </Step>70 </Step>

67 71 

68 <Step title="Create the marketplace file">72 <Step title="Create the marketplace file">


78 {82 {

79 "name": "quality-review-plugin",83 "name": "quality-review-plugin",

80 "source": "./plugins/quality-review-plugin",84 "source": "./plugins/quality-review-plugin",

81 "description": "Adds a /quality-review skill for quick code reviews"85 "description": "Adds a quality-review skill for quick code reviews"

82 }86 }

83 ]87 ]

84 }88 }


95 </Step>99 </Step>

96 100 

97 <Step title="Try it out">101 <Step title="Try it out">

98 Select some code in your editor and run your new skill.102 Select some code in your editor and run your new skill. Plugin skills are namespaced with the plugin name.

99 103 

100 ```shell theme={null}104 ```shell theme={null}

101 /quality-review105 /quality-review-plugin:quality-review

102 ```106 ```

103 </Step>107 </Step>

104</Steps>108</Steps>


167| `name` | string | Yes | Name of the maintainer or team |171| `name` | string | Yes | Name of the maintainer or team |

168| `email` | string | No | Contact email for the maintainer |172| `email` | string | No | Contact email for the maintainer |

169 173 

170### Optional metadata174### Optional fields

171 175 

172| Field | Type | Description |176| Field | Type | Description |

173| :--------------------- | :----- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |177| :------------------------------------ | :----- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

174| `metadata.description` | string | Brief marketplace description |178| `$schema` | string | JSON Schema URL for editor autocomplete and validation. Claude Code ignores this field at load time. |

175| `metadata.version` | string | Marketplace version |179| `description` | string | Brief marketplace description |

180| `version` | string | Marketplace manifest version |

176| `metadata.pluginRoot` | string | Base directory prepended to relative plugin source paths (for example, `"./plugins"` lets you write `"source": "formatter"` instead of `"source": "./plugins/formatter"`) |181| `metadata.pluginRoot` | string | Base directory prepended to relative plugin source paths (for example, `"./plugins"` lets you write `"source": "formatter"` instead of `"source": "./plugins/formatter"`) |

182| `allowCrossMarketplaceDependenciesOn` | array | Other marketplaces that plugins in this marketplace may depend on. Dependencies from a marketplace not listed here are blocked at install. See [Depend on a plugin from another marketplace](/en/plugin-dependencies#depend-on-a-plugin-from-another-marketplace). |

183 

184`description` and `version` are also accepted under `metadata` for backward compatibility.

177 185 

178## Plugin entries186## Plugin entries

179 187 


191**Standard metadata fields:**199**Standard metadata fields:**

192 200 

193| Field | Type | Description |201| Field | Type | Description |

194| :------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------- |202| :------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

195| `description` | string | Brief plugin description |203| `description` | string | Brief plugin description |

196| `version` | string | Plugin version |204| `version` | string | Plugin version. If set (here or in `plugin.json`), the plugin is pinned to this string and users only receive updates when it changes. Omit to fall back to the git commit SHA. See [Version resolution](#version-resolution-and-release-channels). |

197| `author` | object | Plugin author information (`name` required, `email` optional) |205| `author` | object | Plugin author information (`name` required, `email` optional) |

198| `homepage` | string | Plugin homepage or documentation URL |206| `homepage` | string | Plugin homepage or documentation URL |

199| `repository` | string | Source code repository URL |207| `repository` | string | Source code repository URL |


497 505 

498### Private repositories506### Private repositories

499 507 

500Claude Code supports installing plugins from private repositories. For manual installation and updates, Claude Code uses your existing git credential helpers. If `git clone` works for a private repository in your terminal, it works in Claude Code too. Common credential helpers include `gh auth login` for GitHub, macOS Keychain, and `git-credential-store`.508Claude Code supports installing plugins from private repositories. For manual installation and updates, Claude Code uses your existing git credential helpers, so HTTPS access via `gh auth login`, macOS Keychain, or `git-credential-store` works the same as in your terminal. SSH access works as long as the host is already in your `known_hosts` file and the key is loaded in `ssh-agent`, since Claude Code suppresses interactive SSH prompts for the host fingerprint and key passphrase.

501 509 

502Background auto-updates run at startup without credential helpers, since interactive prompts would block Claude Code from starting. To enable auto-updates for private marketplaces, set the appropriate authentication token in your environment:510Background 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:

503 511 


676 684 

677#### How restrictions work685#### How restrictions work

678 686 

679Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.687Restrictions are checked before any network or filesystem operation. The check runs on marketplace add and on plugin install, update, refresh, and auto-update. If a marketplace was added before the policy was configured and its source no longer matches the allowlist, Claude Code refuses to install or update plugins from it. The same enforcement applies to `blockedMarketplaces`.

680 688 

681The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly:689The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly:

682 690 


685* For `hostPattern` sources: the marketplace host is matched against the regex pattern693* For `hostPattern` sources: the marketplace host is matched against the regex pattern

686* For `pathPattern` sources: the marketplace's filesystem path is matched against the regex pattern694* For `pathPattern` sources: the marketplace's filesystem path is matched against the regex pattern

687 695 

696Exact matching does not normalize URLs: a trailing slash, `.git` suffix, or `ssh://` versus `https://` form are treated as different values. If your organization's marketplace can be cloned by more than one URL form, prefer a `hostPattern` entry over a literal URL so all forms match.

697 

688Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.698Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.

689 699 

690For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).700For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).

691 701 

692### Version resolution and release channels702### Version resolution and release channels

693 703 

694Plugin 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`).704Plugin versions determine cache paths and update detection: if the resolved version matches what a user already has, `/plugin update` and auto-update skip the plugin.

705 

706Claude Code resolves a plugin's version from the first of these that is set:

707 

7081. `version` in the plugin's `plugin.json`

7092. `version` in the plugin's marketplace entry

7103. The git commit SHA of the plugin's source

711 

712For the git-based source types `github`, `url`, `git-subdir`, and relative paths inside a git-hosted marketplace, you can omit `version` entirely and every new commit is treated as a new version. This is the simplest setup for internal or actively-developed plugins.

695 713 

696<Warning>714<Warning>

697 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.715 Setting `version` pins the plugin. If `plugin.json` declares `"version": "1.0.0"`, pushing new commits without changing that string does nothing for existing users, because Claude Code sees the same version and keeps the cached copy. Bump the field on every release, or omit it to use the commit SHA.

716 

717 Avoid setting `version` in both `plugin.json` and the marketplace entry. The `plugin.json` value always wins silently, so a stale manifest version can mask a version you set in `marketplace.json`.

698</Warning>718</Warning>

699 719 

700#### Set up release channels720#### Set up release channels


702To 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).722To 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).

703 723 

704<Warning>724<Warning>

705 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.725 Each channel must resolve to a different version. If you use explicit versions, `plugin.json` must declare a different `version` at each pinned ref. If you omit `version`, the distinct commit SHAs already distinguish the channels. If two refs resolve to the same version string, Claude Code treats them as identical and skips the update.

706</Warning>726</Warning>

707 727 

708##### Example728##### Example


771}791}

772```792```

773 793 

794#### Pin dependency versions

795 

796A plugin can constrain its dependencies to a semver range so that updates to a dependency do not break the dependent plugin. See [Constrain plugin dependency versions](/en/plugin-dependencies) for the `{plugin-name}--v{version}` git-tag convention, range syntax, and how multiple constraints on the same dependency are combined.

797 

774## Validation and testing798## Validation and testing

775 799 

776Test your marketplace before sharing.800Test your marketplace before sharing.


939**Warnings** (non-blocking):963**Warnings** (non-blocking):

940 964 

941* `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array965* `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array

942* `No marketplace description provided`: add `metadata.description` to help users understand your marketplace966* `No marketplace description provided`: add a top-level `description` to help users understand your marketplace

943* `Plugin name "x" is not kebab-case`: the plugin name contains uppercase letters, spaces, or special characters. Rename to lowercase letters, digits, and hyphens only (for example, `my-plugin`). Claude Code accepts other forms, but the Claude.ai marketplace sync rejects them.967* `Plugin name "x" is not kebab-case`: the plugin name contains uppercase letters, spaces, or special characters. Rename to lowercase letters, digits, and hyphens only (for example, `my-plugin`). Claude Code accepts other forms, but the Claude.ai marketplace sync rejects them.

944 968 

945### Plugin installation failures969### Plugin installation failures

plugins.md +40 −5

Details

84 ```84 ```

85 85 

86 | Field | Purpose |86 | Field | Purpose |

87 | :------------ | :----------------------------------------------------------------------------------------------------- |87 | :------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

88 | `name` | Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). |88 | `name` | Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). |

89 | `description` | Shown in the plugin manager when browsing or installing plugins. |89 | `description` | Shown in the plugin manager when browsing or installing plugins. |

90 | `version` | Track releases using [semantic versioning](/en/plugins-reference#version-management). |90 | `version` | Optional. If set, users only receive updates when you bump this field. If omitted and your plugin is distributed via git, the commit SHA is used and every commit counts as a new version. See [version management](/en/plugins-reference#version-management). |

91 | `author` | Optional. Helpful for attribution. |91 | `author` | Optional. Helpful for attribution. |

92 92 

93 For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema).93 For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema).


173 173 

174## Plugin structure overview174## Plugin structure overview

175 175 

176You've created a plugin with a skill, but plugins can include much more: custom agents, hooks, MCP servers, and LSP servers.176You've created a plugin with a skill, but plugins can include much more: custom agents, hooks, MCP servers, LSP servers, and background monitors.

177 177 

178<Warning>178<Warning>

179 **Common mistake**: Don't put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.179 **Common mistake**: Don't put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.


188| `hooks/` | Plugin root | Event handlers in `hooks.json` |188| `hooks/` | Plugin root | Event handlers in `hooks.json` |

189| `.mcp.json` | Plugin root | MCP server configurations |189| `.mcp.json` | Plugin root | MCP server configurations |

190| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |190| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |

191| `monitors/` | Plugin root | Background monitor configurations in `monitors.json` |

191| `bin/` | Plugin root | Executables added to the Bash tool's `PATH` while the plugin is enabled |192| `bin/` | Plugin root | Executables added to the Bash tool's `PATH` while the plugin is enabled |

192| `settings.json` | Plugin root | Default [settings](/en/settings) applied when the plugin is enabled |193| `settings.json` | Plugin root | Default [settings](/en/settings) applied when the plugin is enabled |

193 194 


254 255 

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

256 257 

258### Add background monitors to your plugin

259 

260Background monitors let your plugin watch logs, files, or external status in the background and notify Claude as events arrive. Claude Code starts each monitor automatically when the plugin is active, so you don't need to instruct Claude to start the watch.

261 

262Add a `monitors/monitors.json` file at the plugin root with an array of monitor entries:

263 

264```json monitors/monitors.json theme={null}

265[

266 {

267 "name": "error-log",

268 "command": "tail -F ./logs/error.log",

269 "description": "Application error log"

270 }

271]

272```

273 

274Each stdout line from `command` is delivered to Claude as a notification during the session. For the full schema, including the `when` trigger and variable substitution, see [Monitors](/en/plugins-reference#monitors).

275 

257### Ship default settings with your plugin276### Ship default settings with your plugin

258 277 

259Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` and `subagentStatusLine` keys are supported.278Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` and `subagentStatusLine` keys are supported.


296 ```315 ```

297</Tip>316</Tip>

298 317 

318To test a plugin that is already packaged as a `.zip` archive and hosted at a URL, such as a CI build artifact, use `--plugin-url` instead. Claude Code fetches the archive at startup and loads it for that session only. If the fetch fails or the archive is invalid, Claude Code reports a plugin load error and starts without it. The same [trust considerations](/en/discover-plugins#security) apply as for any plugin source: only point this flag at archives you control or trust.

319 

320To load multiple plugins, repeat the flag for each URL:

321 

322```bash theme={null}

323claude --plugin-url https://example.com/my-plugin.zip --plugin-url https://example.com/other.zip

324```

325 

326Or pass space-separated URLs as one quoted argument:

327 

328```bash theme={null}

329claude --plugin-url "https://example.com/my-plugin.zip https://example.com/other.zip"

330```

331 

299### Debug plugin issues332### Debug plugin issues

300 333 

301If your plugin isn't working as expected:334If your plugin isn't working as expected:


309When your plugin is ready to share:342When your plugin is ready to share:

310 343 

3111. **Add documentation**: Include a `README.md` with installation and usage instructions3441. **Add documentation**: Include a `README.md` with installation and usage instructions

3122. **Version your plugin**: Use [semantic versioning](/en/plugins-reference#version-management) in your `plugin.json`3452. **Choose a versioning strategy**: Decide whether to set an explicit `version` or rely on the git commit SHA. See [version management](/en/plugins-reference#version-management)

3133. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation3463. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation

3144. **Test with others**: Have team members test the plugin before wider distribution3474. **Test with others**: Have team members test the plugin before wider distribution

315 348 

316Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins).349Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins). To keep a plugin internal to your team, host the marketplace in a [private repository](/en/plugin-marketplaces#private-repositories).

317 350 

318### Submit your plugin to the official marketplace351### Submit your plugin to the official marketplace

319 352 


322* **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)355* **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

323* **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)356* **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

324 357 

358Once your plugin is listed, you can have your own CLI prompt Claude Code users to install it. See [Recommend your plugin from your CLI](/en/plugin-hints).

359 

325<Note>360<Note>

326 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).361 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).

327</Note>362</Note>

Details

12 12 

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

14 14 

15A **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.15A **plugin** is a self-contained directory of components that extends Claude Code with custom functionality. Plugin components include skills, agents, hooks, MCP servers, LSP servers, and monitors.

16 16 

17## Plugin components reference17## Plugin components reference

18 18 


109Plugin hooks respond to the same lifecycle events as [user-defined hooks](/en/hooks):109Plugin hooks respond to the same lifecycle events as [user-defined hooks](/en/hooks):

110 110 

111| Event | When it fires |111| Event | When it fires |

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

113| `SessionStart` | When a session begins or resumes |113| `SessionStart` | When a session begins or resumes |

114| `Setup` | When you start Claude Code with `--init-only`, or with `--init` or `--maintenance` in `-p` mode. For one-time preparation in CI or scripts |

114| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |115| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

116| `UserPromptExpansion` | When a user-typed command expands into a prompt, before it reaches Claude. Can block the expansion |

115| `PreToolUse` | Before a tool call executes. Can block it |117| `PreToolUse` | Before a tool call executes. Can block it |

116| `PermissionRequest` | When a permission dialog appears |118| `PermissionRequest` | When a permission dialog appears |

117| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |119| `PermissionDenied` | When a tool call is denied by the auto mode classifier. Return `{retry: true}` to tell the model it may retry the denied tool call |

118| `PostToolUse` | After a tool call succeeds |120| `PostToolUse` | After a tool call succeeds |

119| `PostToolUseFailure` | After a tool call fails |121| `PostToolUseFailure` | After a tool call fails |

122| `PostToolBatch` | After a full batch of parallel tool calls resolves, before the next model call |

120| `Notification` | When Claude Code sends a notification |123| `Notification` | When Claude Code sends a notification |

121| `SubagentStart` | When a subagent is spawned |124| `SubagentStart` | When a subagent is spawned |

122| `SubagentStop` | When a subagent finishes |125| `SubagentStop` | When a subagent finishes |


141 144 

142* `command`: execute shell commands or scripts145* `command`: execute shell commands or scripts

143* `http`: send the event JSON as a POST request to a URL146* `http`: send the event JSON as a POST request to a URL

147* `mcp_tool`: call a tool on a configured [MCP server](/en/mcp)

144* `prompt`: evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context)148* `prompt`: evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context)

145* `agent`: run an agentic verifier with tools for complex verification tasks149* `agent`: run an agentic verifier with tools for complex verification tasks

146 150 


258**Available LSP plugins:**262**Available LSP plugins:**

259 263 

260| Plugin | Language server | Install command |264| Plugin | Language server | Install command |

261| :--------------- | :------------------------- | :----------------------------------------------------------------------------------------- |265| :------------------ | :------------------------- | :----------------------------------------------------------------------------------------- |

262| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |266| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |

263| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |267| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |

264| `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |268| `rust-analyzer-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |

265 269 

266Install the language server first, then install the plugin from the marketplace.270Install the language server first, then install the plugin from the marketplace.

267 271 

272### Monitors

273 

274Plugins can declare background monitors that Claude Code starts automatically when the plugin is active. Each monitor runs a shell command for the lifetime of the session and delivers every stdout line to Claude as a notification, so Claude can react to log entries, status changes, or polled events without being asked to start the watch itself.

275 

276Plugin monitors use the same mechanism as the [Monitor tool](/en/tools-reference#monitor-tool) and share its availability constraints. They run only in interactive CLI sessions, run unsandboxed at the same trust level as [hooks](#hooks), and are skipped on hosts where the Monitor tool is unavailable.

277 

278<Note>

279 Plugin monitors require Claude Code v2.1.105 or later.

280</Note>

281 

282**Location**: `monitors/monitors.json` in the plugin root, or inline in `plugin.json`

283 

284**Format**: JSON array of monitor entries

285 

286The following `monitors/monitors.json` watches a deployment status endpoint and a local error log:

287 

288```json theme={null}

289[

290 {

291 "name": "deploy-status",

292 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/poll-deploy.sh ${user_config.api_endpoint}",

293 "description": "Deployment status changes"

294 },

295 {

296 "name": "error-log",

297 "command": "tail -F ./logs/error.log",

298 "description": "Application error log",

299 "when": "on-skill-invoke:debug"

300 }

301]

302```

303 

304To declare monitors inline, set `experimental.monitors` in `plugin.json` to the same array. To load from a non-default path, set `experimental.monitors` to a relative path string such as `"./config/monitors.json"`. Monitors are an [experimental component](#experimental-components).

305 

306**Required fields:**

307 

308| Field | Description |

309| :------------ | :-------------------------------------------------------------------------------------------------------------------- |

310| `name` | Identifier unique within the plugin. Prevents duplicate processes when the plugin reloads or a skill is invoked again |

311| `command` | Shell command run as a persistent background process in the session working directory |

312| `description` | Short summary of what is being watched. Shown in the task panel and in notification summaries |

313 

314**Optional fields:**

315 

316| Field | Description |

317| :----- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

318| `when` | Controls when the monitor starts. `"always"` starts it at session start and on plugin reload, and is the default. `"on-skill-invoke:<skill-name>"` starts it the first time the named skill in this plugin is dispatched |

319 

320The `command` value supports the same [variable substitutions](#environment-variables) as MCP and LSP server configs: `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${user_config.*}`, and any `${ENV_VAR}` from the environment. Prefix the command with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs to run from the plugin's own directory.

321 

322Disabling a plugin mid-session does not stop monitors that are already running. They stop when the session ends.

323 

324### Themes

325 

326Plugins can ship color themes that appear in `/theme` alongside the built-in presets and the user's local themes. A theme is a JSON file in `themes/` with a `base` preset and a sparse `overrides` map of color tokens. Themes are an [experimental component](#experimental-components).

327 

328```json theme={null}

329{

330 "name": "Dracula",

331 "base": "dark",

332 "overrides": {

333 "claude": "#bd93f9",

334 "error": "#ff5555",

335 "success": "#50fa7b"

336 }

337}

338```

339 

340Selecting a plugin theme persists `custom:<plugin-name>:<slug>` in the user's config. Plugin themes are read-only; pressing `Ctrl+E` on one in `/theme` copies it into `~/.claude/themes/` so the user can edit the copy.

341 

268***342***

269 343 

270## Plugin installation scopes344## Plugin installation scopes


306 "keywords": ["keyword1", "keyword2"],380 "keywords": ["keyword1", "keyword2"],

307 "skills": "./custom/skills/",381 "skills": "./custom/skills/",

308 "commands": ["./custom/commands/special.md"],382 "commands": ["./custom/commands/special.md"],

309 "agents": "./custom/agents/",383 "agents": ["./custom/agents/reviewer.md"],

310 "hooks": "./config/hooks.json",384 "hooks": "./config/hooks.json",

311 "mcpServers": "./mcp-config.json",385 "mcpServers": "./mcp-config.json",

312 "outputStyles": "./styles/",386 "outputStyles": "./styles/",

313 "lspServers": "./.lsp.json",387 "lspServers": "./.lsp.json",

388 "experimental": {

389 "themes": "./themes/",

314 "monitors": "./monitors.json"390 "monitors": "./monitors.json"

391 },

392 "dependencies": [

393 "helper-lib",

394 { "name": "secrets-vault", "version": "~2.1.0" }

395 ]

315}396}

316```397```

317 398 


330### Metadata fields411### Metadata fields

331 412 

332| Field | Type | Description | Example |413| Field | Type | Description | Example |

333| :------------ | :----- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |414| :------------ | :----- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------- |

334| `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"` |415| `$schema` | string | JSON Schema URL for editor autocomplete and validation. Claude Code ignores this field at load time. | `"https://json.schemastore.org/claude-code-plugin-manifest.json"` |

416| `version` | string | Optional. Semantic version. Setting this pins the plugin to that version string, so users only receive updates when you bump it. If omitted, Claude Code falls back to the git commit SHA, so every commit is treated as a new version. If also set in the marketplace entry, `plugin.json` wins. See [Version management](#version-management). | `"2.1.0"` |

335| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |417| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |

336| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |418| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |

337| `homepage` | string | Documentation URL | `"https://docs.example.com"` |419| `homepage` | string | Documentation URL | `"https://docs.example.com"` |


342### Component path fields424### Component path fields

343 425 

344| Field | Type | Description | Example |426| Field | Type | Description | Example |

345| :------------- | :-------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------- |427| :---------------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------- |

346| `skills` | string\|array | Custom skill directories containing `<name>/SKILL.md` (replaces default `skills/`) | `"./custom/skills/"` |428| `skills` | string\|array | Custom skill directories containing `<name>/SKILL.md` (in addition to default `skills/`) | `"./custom/skills/"` |

347| `commands` | string\|array | Custom flat `.md` skill files or directories (replaces default `commands/`) | `"./custom/cmd.md"` or `["./cmd1.md"]` |429| `commands` | string\|array | Custom flat `.md` skill files or directories (replaces default `commands/`) | `"./custom/cmd.md"` or `["./cmd1.md"]` |

348| `agents` | string\|array | Custom agent files (replaces default `agents/`) | `"./custom/agents/reviewer.md"` |430| `agents` | string\|array | Custom agent files (replaces default `agents/`) | `"./custom/agents/reviewer.md"` |

349| `hooks` | string\|array\|object | Hook config paths or inline config | `"./my-extra-hooks.json"` |431| `hooks` | string\|array\|object | Hook config paths or inline config | `"./my-extra-hooks.json"` |

350| `mcpServers` | string\|array\|object | MCP config paths or inline config | `"./my-extra-mcp-config.json"` |432| `mcpServers` | string\|array\|object | MCP config paths or inline config | `"./my-extra-mcp-config.json"` |

351| `outputStyles` | string\|array | Custom output style files/directories (replaces default `output-styles/`) | `"./styles/"` |433| `outputStyles` | string\|array | Custom output style files/directories (replaces default `output-styles/`) | `"./styles/"` |

352| `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"` |434| `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"` |

353| `monitors` | string\|array\|object | Background [Monitor](/en/tools-reference#monitor-tool) configurations that auto-arm when the plugin is enabled at session start or when a skill in this plugin is invoked | `"./monitors.json"` |435| `experimental.themes` | string\|array | Color theme files/directories (replaces default `themes/`). See [Themes](#themes) | `"./themes/"` |

436| `experimental.monitors` | string\|array | Background [Monitor](/en/tools-reference#monitor-tool) configurations that start automatically when the plugin is active. See [Monitors](#monitors) | `"./monitors.json"` |

354| `userConfig` | object | User-configurable values prompted at enable time. See [User configuration](#user-configuration) | See below |437| `userConfig` | object | User-configurable values prompted at enable time. See [User configuration](#user-configuration) | See below |

355| `channels` | array | Channel declarations for message injection (Telegram, Slack, Discord style). See [Channels](#channels) | See below |438| `channels` | array | Channel declarations for message injection (Telegram, Slack, Discord style). See [Channels](#channels) | See below |

439| `dependencies` | array | Other plugins this plugin requires, optionally with semver version constraints. See [Constrain plugin dependency versions](/en/plugin-dependencies) | `[{ "name": "secrets-vault", "version": "~2.1.0" }]` |

440 

441### Experimental components

442 

443Components under the `experimental` key, `themes` and `monitors`, have a manifest schema that may change between releases while they stabilize. Where you declare them is a separate migration: the top level still works, `claude plugin validate` warns, and a future release will require `experimental.*`.

356 444 

357### User configuration445### User configuration

358 446 


362{450{

363 "userConfig": {451 "userConfig": {

364 "api_endpoint": {452 "api_endpoint": {

365 "description": "Your team's API endpoint",453 "type": "string",

366 "sensitive": false454 "title": "API endpoint",

455 "description": "Your team's API endpoint"

367 },456 },

368 "api_token": {457 "api_token": {

458 "type": "string",

459 "title": "API token",

369 "description": "API authentication token",460 "description": "API authentication token",

370 "sensitive": true461 "sensitive": true

371 }462 }


373}464}

374```465```

375 466 

376Keys must be valid identifiers. Each value is available for substitution as `${user_config.KEY}` in MCP and LSP server configs, hook commands, and (for non-sensitive values only) skill and agent content. Values are also exported to plugin subprocesses as `CLAUDE_PLUGIN_OPTION_<KEY>` environment variables.467Keys must be valid identifiers. Each option supports these fields:

468 

469| Field | Required | Description |

470| :------------ | :------- | :--------------------------------------------------------------------------------------- |

471| `type` | Yes | One of `string`, `number`, `boolean`, `directory`, or `file` |

472| `title` | Yes | Label shown in the configuration dialog |

473| `description` | Yes | Help text shown beneath the field |

474| `sensitive` | No | If `true`, masks input and stores the value in secure storage instead of `settings.json` |

475| `required` | No | If `true`, validation fails when the field is empty |

476| `default` | No | Value used when the user provides nothing |

477| `multiple` | No | For `string` type, allow an array of strings |

478| `min` / `max` | No | Bounds for `number` type |

479 

480Each value is available for substitution as `${user_config.KEY}` in MCP and LSP server configs, hook commands, and monitor commands. Non-sensitive values can also be substituted in skill and agent content. All values are exported to plugin subprocesses as `CLAUDE_PLUGIN_OPTION_<KEY>` environment variables.

377 481 

378Non-sensitive values are stored in `settings.json` under `pluginConfigs[<plugin-id>].options`. Sensitive values go to the system keychain (or `~/.claude/.credentials.json` where the keychain is unavailable). Keychain storage is shared with OAuth tokens and has an approximately 2 KB total limit, so keep sensitive values small.482Non-sensitive values are stored in `settings.json` under `pluginConfigs[<plugin-id>].options`. Sensitive values go to the system keychain (or `~/.claude/.credentials.json` where the keychain is unavailable). Keychain storage is shared with OAuth tokens and has an approximately 2 KB total limit, so keep sensitive values small.

379 483 


387 {491 {

388 "server": "telegram",492 "server": "telegram",

389 "userConfig": {493 "userConfig": {

390 "bot_token": { "description": "Telegram bot token", "sensitive": true },494 "bot_token": {

391 "owner_id": { "description": "Your Telegram user ID", "sensitive": false }495 "type": "string",

496 "title": "Bot token",

497 "description": "Telegram bot token",

498 "sensitive": true

499 },

500 "owner_id": {

501 "type": "string",

502 "title": "Owner ID",

503 "description": "Your Telegram user ID"

504 }

392 }505 }

393 }506 }

394 ]507 ]


399 512 

400### Path behavior rules513### Path behavior rules

401 514 

402For `skills`, `commands`, `agents`, `outputStyles`, and `monitors`, a custom path replaces the default. If the manifest specifies `skills`, the default `skills/` directory is not scanned; if it specifies `monitors`, the default `monitors/monitors.json` is not loaded. [Hooks](#hooks), [MCP servers](#mcp-servers), and [LSP servers](#lsp-servers) have different semantics for handling multiple sources.515Whether a custom path replaces or extends the plugin's default directory depends on the field:

516 

517* **Replaces the default**: `commands`, `agents`, `outputStyles`, `experimental.themes`, `experimental.monitors`. For example, when the manifest specifies `commands`, the default `commands/` directory is not scanned. To keep the default and add more, list it explicitly: `"commands": ["./commands/", "./extras/"]`

518* **Adds to the default**: `skills`. The default `skills/` directory is always scanned, and directories listed in `skills` are loaded alongside it

519* **Own merge rules**: [hooks](#hooks), [MCP servers](#mcp-servers), and [LSP servers](#lsp-servers). See each section for how multiple sources combine

520 

521For all path fields:

403 522 

404* All paths must be relative to the plugin root and start with `./`523* All paths must be relative to the plugin root and start with `./`

405* Components from custom paths use the same naming and namespacing rules524* Components from custom paths use the same naming and namespacing rules

406* Multiple paths can be specified as arrays525* Multiple paths can be specified as arrays

407* To keep the default directory and add more paths for skills, commands, agents, or output styles, include the default in your array: `"skills": ["./skills/", "./extras/"]`

408* When a skill path points to a directory that contains a `SKILL.md` directly, for example `"skills": ["./"]` pointing to the plugin root, the frontmatter `name` field in `SKILL.md` determines the skill's invocation name. This gives a stable name regardless of the install directory. If `name` is not set in the frontmatter, the directory basename is used as a fallback.526* When a skill path points to a directory that contains a `SKILL.md` directly, for example `"skills": ["./"]` pointing to the plugin root, the frontmatter `name` field in `SKILL.md` determines the skill's invocation name. This gives a stable name regardless of the install directory. If `name` is not set in the frontmatter, the directory basename is used as a fallback.

409 527 

410**Path examples**:528**Path examples**:


424 542 

425### Environment variables543### Environment variables

426 544 

427Claude Code provides two variables for referencing plugin paths. Both are substituted inline anywhere they appear in skill content, agent content, hook commands, and MCP or LSP server configs. Both are also exported as environment variables to hook processes and MCP or LSP server subprocesses.545Claude Code provides two variables for referencing plugin paths. Both are substituted inline anywhere they appear in skill content, agent content, hook commands, monitor commands, and MCP or LSP server configs. Both are also exported as environment variables to hook processes and MCP or LSP server subprocesses.

428 546 

429**`${CLAUDE_PLUGIN_ROOT}`**: the absolute path to your plugin's installation directory. Use this to reference scripts, binaries, and config files bundled with the plugin. This path changes when the plugin updates, so files you write here do not survive an update.547**`${CLAUDE_PLUGIN_ROOT}`**: the absolute path to your plugin's installation directory. Use this to reference scripts, binaries, and config files bundled with the plugin. This path changes when the plugin updates. The previous version's directory remains on disk for about seven days after an update before cleanup, but treat it as ephemeral and do not write state here.

548 

549When a plugin updates mid-session, hook commands, monitors, MCP servers, and LSP servers keep using the previous version's path. Run `/reload-plugins` to switch hooks, MCP servers, and LSP servers to the new path; monitors require a session restart.

430 550 

431**`${CLAUDE_PLUGIN_DATA}`**: a persistent directory for plugin state that survives updates. Use this for installed dependencies such as `node_modules` or Python virtual environments, generated code, caches, and any other files that should persist across plugin versions. The directory is created automatically the first time this variable is referenced.551**`${CLAUDE_PLUGIN_DATA}`**: a persistent directory for plugin state that survives updates. Use this for installed dependencies such as `node_modules` or Python virtual environments, generated code, caches, and any other files that should persist across plugin versions. The directory is created automatically the first time this variable is referenced.

432 552 


498 618 

499Plugins are specified in one of two ways:619Plugins are specified in one of two ways:

500 620 

501* Through `claude --plugin-dir`, for the duration of a session.621* Through `claude --plugin-dir` or `claude --plugin-url`, for the duration of a session.

502* Through a marketplace, installed for future sessions.622* Through a marketplace, installed for future sessions.

503 623 

504For 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.624For 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.


548│ └── compliance-checker.md668│ └── compliance-checker.md

549├── output-styles/ # Output style definitions669├── output-styles/ # Output style definitions

550│ └── terse.md670│ └── terse.md

671├── themes/ # Color theme definitions

672│ └── dracula.json

551├── monitors/ # Background monitor configurations673├── monitors/ # Background monitor configurations

552│ └── monitors.json674│ └── monitors.json

553├── hooks/ # Hook configurations675├── hooks/ # Hook configurations


567```689```

568 690 

569<Warning>691<Warning>

570 The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, output-styles/, monitors/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.692 The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, output-styles/, themes/, monitors/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.

571</Warning>693</Warning>

572 694 

695A `CLAUDE.md` file at the plugin root is not loaded as project context. Plugins contribute context through skills, agents, and hooks rather than CLAUDE.md. To ship instructions that load into Claude's context, put them in a [skill](#skills).

696 

573### File locations reference697### File locations reference

574 698 

575| Component | Default Location | Purpose |699| Component | Default Location | Purpose |


579| **Commands** | `commands/` | Skills as flat Markdown files. Use `skills/` for new plugins |703| **Commands** | `commands/` | Skills as flat Markdown files. Use `skills/` for new plugins |

580| **Agents** | `agents/` | Subagent Markdown files |704| **Agents** | `agents/` | Subagent Markdown files |

581| **Output styles** | `output-styles/` | Output style definitions |705| **Output styles** | `output-styles/` | Output style definitions |

706| **Themes** | `themes/` | Color theme definitions |

582| **Hooks** | `hooks/hooks.json` | Hook configuration |707| **Hooks** | `hooks/hooks.json` | Hook configuration |

583| **MCP servers** | `.mcp.json` | MCP server definitions |708| **MCP servers** | `.mcp.json` | MCP server definitions |

584| **LSP servers** | `.lsp.json` | Language server configurations |709| **LSP servers** | `.lsp.json` | Language server configurations |


641**Options:**766**Options:**

642 767 

643| Option | Description | Default |768| Option | Description | Default |

644| :-------------------- | :---------------------------------------------------------------------------- | :------ |769| :-------------------- | :------------------------------------------------------------------------------------------------------- | :------ |

645| `-s, --scope <scope>` | Uninstall from scope: `user`, `project`, or `local` | `user` |770| `-s, --scope <scope>` | Uninstall from scope: `user`, `project`, or `local` | `user` |

646| `--keep-data` | Preserve the plugin's [persistent data directory](#persistent-data-directory) | |771| `--keep-data` | Preserve the plugin's [persistent data directory](#persistent-data-directory) | |

772| `--prune` | Also remove auto-installed dependencies that no other plugin requires. See [plugin prune](#plugin-prune) | |

773| `-y, --yes` | Skip the `--prune` confirmation prompt. Required when stdin is not a TTY | |

647| `-h, --help` | Display help for command | |774| `-h, --help` | Display help for command | |

648 775 

649**Aliases:** `remove`, `rm`776**Aliases:** `remove`, `rm`

650 777 

651By default, uninstalling from the last remaining scope also deletes the plugin's `${CLAUDE_PLUGIN_DATA}` directory. Use `--keep-data` to preserve it, for example when reinstalling after testing a new version.778By default, uninstalling from the last remaining scope also deletes the plugin's `${CLAUDE_PLUGIN_DATA}` directory. Use `--keep-data` to preserve it, for example when reinstalling after testing a new version.

652 779 

780### plugin prune

781 

782Remove auto-installed plugin dependencies that are no longer required by any installed plugin. Dependencies that Claude Code pulled in to satisfy another plugin's [`dependencies`](/en/plugin-dependencies) field are removed; plugins you installed directly are never touched.

783 

784```bash theme={null}

785claude plugin prune [options]

786```

787 

788**Options:**

789 

790| Option | Description | Default |

791| :-------------------- | :------------------------------------------------------------- | :------ |

792| `-s, --scope <scope>` | Prune at scope: `user`, `project`, or `local` | `user` |

793| `--dry-run` | List what would be removed without removing anything | |

794| `-y, --yes` | Skip the confirmation prompt. Required when stdin is not a TTY | |

795| `-h, --help` | Display help for command | |

796 

797**Aliases:** `autoremove`

798 

799The command lists orphaned dependencies and asks for confirmation before removing them. To remove a plugin and clean up its dependencies in one step, run `claude plugin uninstall <plugin> --prune`.

800 

801<Note>

802 `claude plugin prune` requires Claude Code v2.1.121 or later.

803</Note>

804 

653### plugin enable805### plugin enable

654 806 

655Enable a disabled plugin.807Enable a disabled plugin.


709 861 

710***862***

711 863 

864### plugin list

865 

866List installed plugins with their version, source marketplace, and enable status.

867 

868```bash theme={null}

869claude plugin list [options]

870```

871 

872**Options:**

873 

874| Option | Description | Default |

875| :------------ | :------------------------------------------------------------- | :------ |

876| `--json` | Output as JSON | |

877| `--available` | Include available plugins from marketplaces. Requires `--json` | |

878| `-h, --help` | Display help for command | |

879 

880### plugin tag

881 

882Create a release git tag for the plugin in the current directory. Run from inside the plugin's folder. See [Tag plugin releases](/en/plugin-dependencies#tag-plugin-releases-for-version-resolution).

883 

884```bash theme={null}

885claude plugin tag [options]

886```

887 

888**Options:**

889 

890| Option | Description | Default |

891| :------------ | :------------------------------------------------------------------------- | :------ |

892| `--push` | Push the tag to the remote after creating it | |

893| `--dry-run` | Print what would be tagged without creating the tag | |

894| `-f, --force` | Create the tag even if the working tree is dirty or the tag already exists | |

895| `-h, --help` | Display help for command | |

896 

897***

898 

712## Debugging and development tools899## Debugging and development tools

713 900 

714### Debugging commands901### Debugging commands


760 947 

7611. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse`9481. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse`

7622. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations9492. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations

7633. Confirm the hook type is valid: `command`, `http`, `prompt`, or `agent`9503. Confirm the hook type is valid: `command`, `http`, `mcp_tool`, `prompt`, or `agent`

764 951 

765### MCP server troubleshooting952### MCP server troubleshooting

766 953 


806 993 

807### Version management994### Version management

808 995 

809Follow semantic versioning for plugin releases:996Claude Code uses the plugin's version as the cache key that determines whether an update is available. When you run `/plugin update` or auto-update fires, Claude Code computes the current version and skips the update if it matches what's already installed.

810 997 

811```json theme={null}998The version is resolved from the first of these that is set:

812{

813 "name": "my-plugin",

814 "version": "2.1.0"

815}

816```

817 

818**Version format**: `MAJOR.MINOR.PATCH`

819 999 

820* **MAJOR**: Breaking changes (incompatible API changes)10001. The `version` field in the plugin's `plugin.json`

821* **MINOR**: New features (backward-compatible additions)10012. The `version` field in the plugin's marketplace entry in `marketplace.json`

822* **PATCH**: Bug fixes (backward-compatible fixes)10023. The git commit SHA of the plugin's source, for `github`, `url`, `git-subdir`, and relative-path sources in a git-hosted marketplace

10034. `unknown`, for `npm` sources or local directories not inside a git repository

823 1004 

824**Best practices**:1005This gives you two ways to version a plugin:

825 1006 

826* Start at `1.0.0` for your first stable release1007| Approach | How | Update behavior | Best for |

827* Update the version in `plugin.json` before distributing changes1008| :--------------------- | :--------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------ |

828* Document changes in a `CHANGELOG.md` file1009| **Explicit version** | Set `"version": "2.1.0"` in `plugin.json` | Users get updates only when you bump this field. Pushing new commits without bumping it has no effect, and `/plugin update` reports "already at the latest version". | Published plugins with stable release cycles |

829* Use pre-release versions like `2.0.0-beta.1` for testing1010| **Commit-SHA version** | Omit `version` from both `plugin.json` and the marketplace entry | Users get updates on every new commit to the plugin's git source | Internal or team plugins under active development |

830 1011 

831<Warning>1012<Warning>

832 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.1013 If you set `version` in `plugin.json`, you must bump it every time you want users to receive changes. Pushing new commits alone is not enough, because Claude Code sees the same version string and keeps the cached copy. If you're iterating quickly, leave `version` unset so the git commit SHA is used instead.

833 

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

835</Warning>1014</Warning>

836 1015 

1016If you use explicit versions, follow [semantic versioning](https://semver.org) (`MAJOR.MINOR.PATCH`): bump MAJOR for breaking changes, MINOR for new features, PATCH for bug fixes. Document changes in a `CHANGELOG.md`.

1017 

837***1018***

838 1019 

839## See also1020## See also

quickstart.md +3 −5

Details

6 6 

7> Welcome to Claude Code!7> Welcome to Claude Code!

8 8 

9 

10 

11This quickstart guide will have you using AI-powered coding assistance in a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.9This quickstart guide will have you using AI-powered coding assistance in a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.

12 10 

13<Experiment flag="quickstart-install-configurator" treatment={<InstallConfigurator />} />

14 

15## Before you begin11## Before you begin

16 12 

17Make sure you have:13Make sure you have:


51 47 

52 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.48 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

53 49 

54 **Native Windows setups require [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it. WSL setups do not need it.50 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

55 51 

56 <Info>52 <Info>

57 Native installations automatically update in the background to keep you on the latest version.53 Native installations automatically update in the background to keep you on the latest version.


81 </Tab>77 </Tab>

82</Tabs>78</Tabs>

83 79 

80You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

81 

84## Step 2: Log in to your account82## Step 2: Log in to your account

85 83 

86Claude Code requires an account to use. When you start an interactive session with the `claude` command, you'll need to log in:84Claude Code requires an account to use. When you start an interactive session with the `claude` command, you'll need to log in:

Details

7> Continue a local Claude Code session from your phone, tablet, or any browser using Remote Control. Works with claude.ai/code and the Claude mobile app.7> Continue a local Claude Code session from your phone, tablet, or any browser using Remote Control. Works with claude.ai/code and the Claude mobile app.

8 8 

9<Note>9<Note>

10 Remote Control is available on all plans. On Team and Enterprise, it is off by default until an admin enables the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).10 Remote Control is in research preview and available on all plans. On Team and Enterprise, it is off by default until an admin enables the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).

11</Note>11</Note>

12 12 

13Remote Control connects [claude.ai/code](https://claude.ai/code) or the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer.13Remote Control connects [claude.ai/code](https://claude.ai/code) or the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer.

14 14 

15When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so nothing moves to the cloud. With Remote Control you can:15When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so nothing moves to the cloud. With Remote Control you can:

16 16 

17* **Use your full local environment remotely**: your filesystem, [MCP servers](/en/mcp), tools, and project configuration all stay available17* **Use your full local environment remotely**: your filesystem, [MCP servers](/en/mcp), tools, and project configuration all stay available, and typing `@` autocompletes file paths from your local project

18* **Work from both surfaces at once**: the conversation stays in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably18* **Work from both surfaces at once**: the conversation stays in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably

19* **Survive interruptions**: if your laptop sleeps or your network drops, the session reconnects automatically when your machine comes back online19* **Survive interruptions**: if your laptop sleeps or your network drops, the session reconnects automatically when your machine comes back online

20 20 


51 Available flags:51 Available flags:

52 52 

53 | Flag | Description |53 | Flag | Description |

54 | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |54 | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

55 | `--name "My Project"` | Set a custom session title visible in the session list at claude.ai/code. |55 | `--name "My Project"` | Set a custom session title visible in the session list at claude.ai/code. |

56 | `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect. |56 | `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect. |

57 | `--spawn <mode>` | How the server creates sessions.<br />• `same-dir` (default): all sessions share the current working directory, so they can conflict if editing the same files.<br />• `worktree`: each on-demand session gets its own [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Requires a git repository.<br />• `session`: single-session mode. Serves exactly one session and rejects additional connections. Set at startup only.<br />Press `w` at runtime to toggle between `same-dir` and `worktree`. |57 | `--spawn <mode>` | How the server creates sessions.<br />• `same-dir` (default): all sessions share the current working directory, so they can conflict if editing the same files.<br />• `worktree`: each on-demand session gets its own [git worktree](/en/worktrees). Requires a git repository.<br />• `session`: single-session mode. Serves exactly one session and rejects additional connections. Set at startup only.<br />Press `w` at runtime to toggle between `same-dir` and `worktree`. |

58 | `--capacity <N>` | Maximum number of concurrent sessions. Default is 32. Cannot be used with `--spawn=session`. |58 | `--capacity <N>` | Maximum number of concurrent sessions. Default is 32. Cannot be used with `--spawn=session`. |

59 | `--verbose` | Show detailed connection and session logs. |59 | `--verbose` | Show detailed connection and session logs. |

60 | `--sandbox` / `--no-sandbox` | Enable or disable [sandboxing](/en/sandboxing) for filesystem and network isolation. Off by default. |60 | `--sandbox` / `--no-sandbox` | Enable or disable [sandboxing](/en/sandboxing) for filesystem and network isolation. Off by default. |


113 113 

114* **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code).114* **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code).

115* **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.115* **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.

116* **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. Remote Control sessions show a computer icon with a green status dot when online.116* **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. In the Claude mobile app, tap **Code** in the navigation to reach the session list. Remote Control sessions show a computer icon with a green status dot when online.

117 117 

118The remote session title is chosen in this order:118The remote session title is chosen in this order:

119 119 


146 146 

147Use Remote Control when you're in the middle of local work and want to keep going from another device. Use Claude Code on the web when you want to kick off a task without any local setup, work on a repo you don't have cloned, or run multiple tasks in parallel.147Use Remote Control when you're in the middle of local work and want to keep going from another device. Use Claude Code on the web when you want to kick off a task without any local setup, work on a repo you don't have cloned, or run multiple tasks in parallel.

148 148 

149## Mobile push notifications

150 

151When Remote Control is active, Claude can send push notifications to your phone.

152 

153Claude decides when to push. It typically sends one when a long-running task finishes or when it needs a decision from you to continue. You can also request a push in your prompt, for example `notify me when the tests finish`. Beyond the on/off toggle below, there is no per-event configuration.

154 

155<Note>

156 Mobile push notifications require Claude Code v2.1.110 or later.

157</Note>

158 

159To set up mobile push notifications:

160 

161<Steps>

162 <Step title="Install the Claude mobile app">

163 Download the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude).

164 </Step>

165 

166 <Step title="Sign in with your Claude Code account">

167 Use the same account and organization you use for Claude Code in the terminal.

168 </Step>

169 

170 <Step title="Allow notifications">

171 Accept the notification permission prompt from the operating system.

172 </Step>

173 

174 <Step title="Enable push in Claude Code">

175 In your terminal, run `/config` and enable **Push when Claude decides**.

176 </Step>

177</Steps>

178 

179If notifications don't arrive:

180 

181* If `/config` shows **No mobile registered**, open the Claude app on your phone so it can refresh its push token. The warning clears the next time Remote Control connects.

182* On iOS, Focus modes and notification summaries can suppress or delay pushes. Check Settings → Notifications → Claude.

183* On Android, aggressive battery optimization can delay delivery. Exempt the Claude app from battery optimization in system settings.

184 

149## Limitations185## Limitations

150 186 

151* **One remote session per interactive process**: outside of server mode, each Claude Code instance supports one remote session at a time. Use [server mode](#start-a-remote-control-session) to run multiple concurrent sessions from a single process.187* **One remote session per interactive process**: outside of server mode, each Claude Code instance supports one remote session at a time. Use [server mode](#start-a-remote-control-session) to run multiple concurrent sessions from a single process.

152* **Local process must keep running**: Remote Control runs as a local process. If you close the terminal, quit VS Code, or otherwise stop the `claude` process, the session ends.188* **Local process must keep running**: Remote Control runs as a local process. If you close the terminal, quit VS Code, or otherwise stop the `claude` process, the session ends.

153* **Extended network outage**: if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session.189* **Extended network outage**: if your machine is awake but unable to reach the network for more than roughly 10 minutes, the session times out and the process exits. Run `claude remote-control` again to start a new session.

154* **Ultraplan disconnects Remote Control**: starting an [ultraplan](/en/ultraplan) session disconnects any active Remote Control session because both features occupy the claude.ai/code interface and only one can be connected at a time.190* **Ultraplan disconnects Remote Control**: starting an [ultraplan](/en/ultraplan) session disconnects any active Remote Control session because both features occupy the claude.ai/code interface and only one can be connected at a time.

191* **Some commands are local-only**: commands that open an interactive picker in the terminal, such as `/mcp`, `/plugin`, or `/resume`, work only from the local CLI. Commands that produce text output, including `/compact`, `/clear`, `/context`, `/usage`, `/exit`, `/extra-usage`, `/recap`, and `/reload-plugins`, work from mobile and web.

155 192 

156## Troubleshooting193## Troubleshooting

157 194 


178 215 

179### "Remote Control is disabled by your organization's policy"216### "Remote Control is disabled by your organization's policy"

180 217 

181This error has three distinct causes. Run `/status` first to see which login method and subscription you're using.218This error has four distinct causes. Run `/status` first to see which login method and subscription you're using.

182 219 

183* **You're authenticated with an API key or Console account**: Remote Control requires claude.ai OAuth. Run `/login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it.220* **You're authenticated with an API key or Console account**: Remote Control requires claude.ai OAuth. Run `/login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it.

184* **Your Team or Enterprise admin hasn't enabled it**: Remote Control is off by default on these plans. An admin can enable it at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) by turning on the **Remote Control** toggle. This is a server-side organization setting, not a [managed settings](/en/permissions#managed-only-settings) key.221* **Your Team or Enterprise admin hasn't enabled it**: Remote Control is off by default on these plans. An admin can enable it at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) by turning on the **Remote Control** toggle. This toggle is a server-side organization setting.

185* **The admin toggle is grayed out**: your organization has a data retention or compliance configuration that is incompatible with Remote Control. This cannot be changed from the admin panel. Contact Anthropic support to discuss options.222* **The admin toggle is grayed out**: your organization has a data retention or compliance configuration that is incompatible with Remote Control. This cannot be changed from the admin panel. Contact Anthropic support to discuss options.

223* **The error mentions `disableRemoteControl`**: your IT administrator has disabled Remote Control on this device through [managed settings](/en/settings#settings-files), independent of the organization-wide toggle.

186 224 

187### "Remote credentials fetch failed"225### "Remote credentials fetch failed"

188 226 

routines.md +85 −39

Details

14 14 

15Each routine can have one or more triggers attached to it:15Each routine can have one or more triggers attached to it:

16 16 

17* **Scheduled**: run on a recurring cadence like hourly, nightly, or weekly17* **Scheduled**: run on a recurring cadence like hourly, nightly, or weekly, or once at a specific future time

18* **API**: trigger on demand by sending an HTTP POST to a per-routine endpoint with a bearer token18* **API**: trigger on demand by sending an HTTP POST to a per-routine endpoint with a bearer token

19* **GitHub**: run automatically in response to repository events such as pull requests, pushes, issues, or workflow runs19* **GitHub**: run automatically in response to repository events such as pull requests or releases

20 20 

21A single routine can combine triggers. For example, a PR review routine can run nightly, trigger from a deploy script, and also react to every new PR.21A single routine can combine triggers. For example, a PR review routine can run nightly, trigger from a deploy script, and also react to every new PR.

22 22 

23Routines are available on Pro, Max, Team, and Enterprise plans with [Claude Code on the web](/en/claude-code-on-the-web) enabled. Create and manage them at [claude.ai/code/routines](https://claude.ai/code/routines), or from the CLI with `/schedule`.23Routines are available on Pro, Max, Team, and Enterprise plans with [Claude Code on the web](/en/claude-code-on-the-web) enabled. Create and manage them at [claude.ai/code/routines](https://claude.ai/code/routines), or from the CLI with `/schedule`.

24 24 

25Team and Enterprise admins can disable routines for all members with the Routines toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code). When disabled, existing routines stop running and members cannot create new ones.

26 

25This page covers creating a routine, configuring each trigger type, managing runs, and how usage limits apply.27This page covers creating a routine, configuring each trigger type, managing runs, and how usage limits apply.

26 28 

27## Example use cases29## Example use cases


44 46 

45## Create a routine47## Create a routine

46 48 

47Create a routine from the web, the Desktop app, or the CLI. All three surfaces write to the same cloud account, so a routine you create in the CLI shows up at claude.ai/code/routines immediately. In the Desktop app, click **New task** and choose **New remote task**; choosing **New local task** instead creates a [local Desktop scheduled task](/en/desktop-scheduled-tasks), which runs on your machine and is not a routine.49Create a routine from the web at [claude.ai/code/routines](https://claude.ai/code/routines), from the Desktop app, or from the CLI. All three surfaces write to the same cloud account, so a routine you create in one shows up in the others immediately. In the Desktop app, click **Routines** in the sidebar, then **New routine**, and choose **Remote**; choosing **Local** instead creates a [Desktop scheduled task](/en/desktop-scheduled-tasks), which runs on your machine rather than in the cloud.

48 50 

49The creation form sets up the routine's prompt, repositories, environment, connectors, and triggers.51The creation form sets up the routine's prompt, repositories, environment, connectors, and triggers.

50 52 


66 </Step>68 </Step>

67 69 

68 <Step title="Select repositories">70 <Step title="Select repositories">

69 Add one or more GitHub repositories for Claude to work in. Each repository is cloned at the start of a run, starting from the default branch. Claude creates `claude/`-prefixed branches for its changes. To allow pushes to any branch, enable **Allow unrestricted branch pushes** for that repository.71 Add one or more GitHub repositories for Claude to work in. Each repository is cloned at the start of a run, starting from the default branch. Claude creates `claude/`-prefixed branches for its changes.

70 </Step>72 </Step>

71 73 

72 <Step title="Select an environment">74 <Step title="Select an environment">


74 76 

75 * **Network access**: set the level of internet access available during each run77 * **Network access**: set the level of internet access available during each run

76 * **Environment variables**: provide API keys, tokens, or other secrets Claude can use78 * **Environment variables**: provide API keys, tokens, or other secrets Claude can use

77 * **Setup script**: run install commands before each session starts, like installing dependencies or configuring tools79 * **Setup script**: install dependencies and tools the routine needs. The result is [cached](/en/claude-code-on-the-web#environment-caching), so the script doesn't re-run on every session

78 80 

79 A **Default** environment is provided. To use a custom environment, [create one](/en/claude-code-on-the-web#the-cloud-environment) before creating the routine.81 A **Default** environment is provided with **Trusted** network access, which allows the [default set](/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains, but blocks everything else. If your routine needs to reach your own services or a domain outside that list, edit the environment's [network access](/en/claude-code-on-the-web#network-access) before running. To use a separate environment, [create one](/en/claude-code-on-the-web#configure-your-environment) first.

80 </Step>82 </Step>

81 83 

82 <Step title="Select a trigger">84 <Step title="Select a trigger">


84 86 

85 <Tabs>87 <Tabs>

86 <Tab title="Schedule">88 <Tab title="Schedule">

87 Pick a preset frequency: hourly, daily, weekdays, or weekly. See [Add a schedule trigger](#add-a-schedule-trigger) for timezone handling, stagger, and custom cron intervals.89 Pick a preset frequency for a recurring run, or schedule a single one-off run at a specific timestamp. See [Add a schedule trigger](#add-a-schedule-trigger) for timezone handling, stagger, custom cron intervals, and one-off runs.

88 </Tab>90 </Tab>

89 91 

90 <Tab title="GitHub event">92 <Tab title="GitHub event">


97 </Tabs>99 </Tabs>

98 </Step>100 </Step>

99 101 

100 <Step title="Review connectors">102 <Step title="Review connectors and permissions">

101 All of your connected [MCP connectors](/en/mcp) are included by default. Remove any that the routine doesn't need. Connectors give Claude access to external services like Slack, Linear, or Google Drive during each run.103 The **Connectors** and **Permissions** tabs at the bottom of the form control what the routine can reach.

104 

105 Under Connectors, all of your connected [MCP connectors](/en/mcp) are included by default. Remove any the routine doesn't need. Claude can use every tool from an included connector, including writes, without asking for permission during a run.

106 

107 Under Permissions, enable **Allow unrestricted branch pushes** for any repository where Claude should be able to push to existing branches instead of only `claude/`-prefixed ones.

102 </Step>108 </Step>

103 109 

104 <Step title="Create the routine">110 <Step title="Create the routine">


110 116 

111### Create from the CLI117### Create from the CLI

112 118 

113Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, as in `/schedule daily PR review at 9am`. Claude walks through the same information the web form collects, then saves the routine to your account.119Run `/schedule` in any session to create a scheduled routine conversationally. You can also pass a description directly, for a recurring routine like `/schedule daily PR review at 9am` or a one-off like `/schedule clean up feature flag in one week`. Claude walks through the same information the web form collects, then saves the routine to your account.

114 120 

115`/schedule` in the CLI creates scheduled routines only. To add an API or GitHub trigger, edit the routine on the web at [claude.ai/code/routines](https://claude.ai/code/routines).121`/schedule` in the CLI creates scheduled routines only. To add an API or GitHub trigger, edit the routine on the web at [claude.ai/code/routines](https://claude.ai/code/routines).

116 122 

117The CLI also supports managing existing routines. Run `/schedule list` to see all routines, `/schedule update` to change one, or `/schedule run` to trigger it immediately.123The CLI also supports managing existing routines. Run `/schedule list` to see all routines, `/schedule update` to change one, or `/schedule run` to trigger it immediately.

118 124 

119### Create from the Desktop app

120 

121Open the **Schedule** page in the Desktop app, click **New task**, and choose **New remote task**. The Desktop app shows both local scheduled tasks and routines in the same grid. See [Desktop scheduled tasks](/en/desktop-scheduled-tasks) for details on the local option.

122 

123## Configure triggers125## Configure triggers

124 126 

125A routine starts when one of its triggers matches. You can attach any combination of schedule, API, and GitHub triggers to the same routine, and add or remove them at any time from the **Select a trigger** section of the routine's edit form.127A routine starts when one of its triggers matches. You can attach any combination of schedule, API, and GitHub triggers to the same routine, and add or remove them at any time from the **Select a trigger** section of the routine's edit form.

126 128 

127### Add a schedule trigger129### Add a schedule trigger

128 130 

129A schedule trigger runs the routine on a recurring cadence. Pick a preset frequency in the **Select a trigger** section: hourly, daily, weekdays, or weekly. Times are entered in your local zone and converted automatically, so the routine runs at that wall-clock time regardless of where the cloud infrastructure is located.131A schedule trigger runs the routine on a recurring cadence, or once at a specific future time. Pick a preset frequency in the **Select a trigger** section: hourly, daily, weekdays, or weekly. Times are entered in your local zone and converted automatically, so the routine runs at that wall-clock time regardless of where the cloud infrastructure is located.

130 132 

131Runs may start a few minutes after the scheduled time due to stagger. The offset is consistent for each routine.133Runs may start a few minutes after the scheduled time due to stagger. The offset is consistent for each routine.

132 134 

133For a custom interval such as every two hours or the first of each month, pick the closest preset in the form, then run `/schedule update` in the CLI to set a specific cron expression. The minimum interval is one hour; expressions that run more frequently are rejected.135For a custom interval such as every two hours or the first of each month, pick the closest preset in the form, then run `/schedule update` in the CLI to set a specific cron expression. The minimum interval is one hour; expressions that run more frequently are rejected.

134 136 

137#### Schedule a one-off run

138 

139A one-off schedule fires the routine a single time at a specific timestamp. Use it to remind yourself later in the week, to open a cleanup PR after a rollout finishes, or to kick off a follow-up task when an upstream change lands. After the routine fires, it auto-disables and the web UI marks it as **Ran**. To run it again, edit the routine and set a new one-off time.

140 

141Create a one-off run from the CLI by describing the time in natural language. Claude resolves the phrase against the current time and confirms the absolute timestamp before saving.

142 

143```text theme={null}

144/schedule tomorrow at 9am, summarize yesterday's merged PRs

145```

146 

147```text theme={null}

148/schedule in 2 weeks, open a cleanup PR that removes the feature flag

149```

150 

151The same local-to-UTC conversion as recurring schedules applies to one-off timestamps.

152 

153One-off runs do not count against the daily routine run cap. They consume your plan's regular subscription usage like any other session. See [Usage and limits](#usage-and-limits) for details.

154 

135### Add an API trigger155### Add an API trigger

136 156 

137An API trigger gives a routine a dedicated HTTP endpoint. POSTing to the endpoint with the routine's bearer token starts a new session and returns a session URL. Use this to wire Claude Code into alerting systems, deploy pipelines, internal tools, or anywhere you can make an authenticated HTTP request.157An API trigger gives a routine a dedicated HTTP endpoint. POSTing to the endpoint with the routine's bearer token starts a new session and returns a session URL. Use this to wire Claude Code into alerting systems, deploy pipelines, internal tools, or anywhere you can make an authenticated HTTP request.


144 </Step>164 </Step>

145 165 

146 <Step title="Add an API trigger">166 <Step title="Add an API trigger">

147 Scroll to the **Select a trigger** section below the prompt, click **Add another trigger**, and choose **API**.167 Scroll to the **Select a trigger** section below the **Instructions** box, click **Add another trigger**, and choose **API**.

148 </Step>168 </Step>

149 169 

150 <Step title="Copy the URL and generate a token">170 <Step title="Copy the URL and generate a token">


229 249 

230#### Supported events250#### Supported events

231 251 

232GitHub triggers can subscribe to any of the following event categories. Within each category you can pick a specific action, such as `pull_request.opened`, or react to all actions in the category.252GitHub triggers can subscribe to either of the following event categories. Within each category you can pick a specific action, such as `pull_request.opened`, or react to all actions in the category.

233 253 

234| Event | Triggers when |254| Event | Triggers when |

235| :-------------------------- | :---------------------------------------------------------------------------- |255| :----------- | :---------------------------------------------------------------------------- |

236| Pull request | A PR is opened, closed, assigned, labeled, synchronized, or otherwise updated |256| Pull request | A PR is opened, closed, assigned, labeled, synchronized, or otherwise updated |

237| Pull request review | A PR review is submitted, edited, or dismissed |

238| Pull request review comment | A comment on a PR diff is created, edited, or deleted |

239| Push | Commits are pushed to a branch |

240| Release | A release is created, published, edited, or deleted |257| Release | A release is created, published, edited, or deleted |

241| Issues | An issue is opened, edited, closed, labeled, or otherwise updated |

242| Issue comment | A comment on an issue or PR is created, edited, or deleted |

243| Sub issues | A sub-issue or parent issue is added or removed |

244| Commit comment | A commit or diff is commented on |

245| Discussion | A discussion is created, edited, answered, or otherwise updated |

246| Discussion comment | A discussion comment is created, edited, or deleted |

247| Check run | A check run is created, requested, rerequested, or completed |

248| Check suite | A check suite completes or is requested |

249| Merge queue entry | A PR enters or leaves the merge queue |

250| Workflow run | A GitHub Actions workflow run starts or completes |

251| Workflow job | A GitHub Actions job is queued or completes |

252| Workflow dispatch | A workflow is manually triggered |

253| Repository dispatch | A custom repository\_dispatch event is sent |

254 258 

255#### Filter pull requests259#### Filter pull requests

256 260 


266| Labels | Labels applied to the PR |270| Labels | Labels applied to the PR |

267| Is draft | Whether the PR is in draft state |271| Is draft | Whether the PR is in draft state |

268| Is merged | Whether the PR has been merged |272| Is merged | Whether the PR has been merged |

269| From fork | Whether the PR comes from a fork |273 

274Each filter pairs a field with an operator: equals, contains, starts with, is one of, is not one of, or matches regex.

275 

276The `matches regex` operator tests the entire field value, not a substring within it. To match any title containing `hotfix`, write `.*hotfix.*`. Without the surrounding `.*`, the filter matches only a title that is exactly `hotfix` with nothing before or after. For literal substring matching without regex syntax, use the `contains` operator instead.

270 277 

271A few example filter combinations:278A few example filter combinations:

272 279 

273* **Auth module review**: base branch `main`, head branch contains `auth-provider`. Sends any PR that touches authentication to a focused reviewer.280* **Auth module review**: base branch `main`, head branch contains `auth-provider`. Sends any PR that touches authentication to a focused reviewer.

274* **External contributor triage**: from fork is `true`. Routes every fork-based PR through an extra security and style review before a human looks at it.

275* **Ready-for-review only**: is draft is `false`. Skips drafts so the routine only runs when the PR is ready for review.281* **Ready-for-review only**: is draft is `false`. Skips drafts so the routine only runs when the PR is ready for review.

276* **Label-gated backport**: labels include `needs-backport`. Triggers a port-to-another-branch routine only when a maintainer tags the PR.282* **Label-gated backport**: labels include `needs-backport`. Triggers a port-to-another-branch routine only when a maintainer tags the PR.

277 283 

278#### How sessions map to events284#### How sessions map to events

279 285 

280Each matching GitHub event starts a new session. Session reuse across events is not available for GitHub-triggered routines, so two pushes or two PR updates produce two independent sessions.286Each matching GitHub event starts a new session. Session reuse across events is not available for GitHub-triggered routines, so two PR updates produce two independent sessions.

281 287 

282## Manage routines288## Manage routines

283 289 


287 293 

288Click any run to open it as a full session. From there you can see what Claude did, review changes, create a pull request, or continue the conversation. Each run session works like any other session: use the dropdown menu next to the session title to rename, archive, or delete it.294Click any run to open it as a full session. From there you can see what Claude did, review changes, create a pull request, or continue the conversation. Each run session works like any other session: use the dropdown menu next to the session title to rename, archive, or delete it.

289 295 

296<Note>

297 A green status in the run list means the session started and exited without an infrastructure error. It does not mean the task in your prompt succeeded. Open the run to read the transcript and confirm what Claude actually did. Blocked network requests, missing connector tools, and task-level failures all surface there rather than in the status indicator.

298</Note>

299 

290### Edit and control routines300### Edit and control routines

291 301 

292From the routine detail page you can:302From the routine detail page you can:


312 322 

313To manage or add connectors outside of the routine form, visit **Settings > Connectors** on claude.ai or use `/schedule update` in the CLI.323To manage or add connectors outside of the routine form, visit **Settings > Connectors** on claude.ai or use `/schedule update` in the CLI.

314 324 

315### Environments325### Environments and network access

326 

327Each routine runs in a [cloud environment](/en/claude-code-on-the-web#the-cloud-environment) that controls network access, environment variables, and setup scripts. The routine inherits the environment's network policy on every run.

316 328 

317Each routine runs in a [cloud environment](/en/claude-code-on-the-web#the-cloud-environment) that controls network access, environment variables, and setup scripts. Configure environments before creating a routine to give Claude access to APIs, install dependencies, or restrict network scope. See [cloud environment](/en/claude-code-on-the-web#the-cloud-environment) for the full setup guide.329The **Default** environment uses **Trusted** network access: the [default allowlist](/en/claude-code-on-the-web#default-allowed-domains) of package registries, cloud provider APIs, container registries, and common development domains is reachable, but arbitrary domains are not. Outbound requests to other hosts fail with `403` and `x-deny-reason: host_not_allowed`. MCP connector traffic is routed through Anthropic's servers, so the connectors you add to the routine work without adding their hosts to **Allowed domains**. Remove any connectors you don't need under [Connectors](#connectors).

330 

331To allow additional domains:

332 

333<Steps>

334 <Step title="Open the routine for editing">

335 On the routine's detail page, click the pencil icon to open **Edit routine**.

336 </Step>

337 

338 <Step title="Open the environment selector">

339 Below the **Instructions** box, select the cloud icon showing your environment's name, such as **Default**.

340 </Step>

341 

342 <Step title="Open the environment settings">

343 Hover over the environment in the list and click the settings icon that appears on the right.

344 </Step>

345 

346 <Step title="Change the network access level">

347 In the **Update cloud environment** dialog, change **Network access** to **Custom** and enter your domains in **Allowed domains**. Check **Also include default list of common package managers** to keep the [default allowlist](/en/claude-code-on-the-web#default-allowed-domains) alongside your custom domains. Select **Full** instead for unrestricted access.

348 </Step>

349 

350 <Step title="Save">

351 Click **Save changes**. The new policy applies from the next run.

352 </Step>

353</Steps>

354 

355See [Network access](/en/claude-code-on-the-web#network-access) for details on access levels and the default allowlist.

318 356 

319## Usage and limits357## Usage and limits

320 358 


322 360 

323When a routine hits the daily cap or your subscription usage limit, organizations with extra usage enabled can keep running routines on metered overage. Without extra usage, additional runs are rejected until the window resets. Enable extra usage from **Settings > Billing** on claude.ai.361When a routine hits the daily cap or your subscription usage limit, organizations with extra usage enabled can keep running routines on metered overage. Without extra usage, additional runs are rejected until the window resets. Enable extra usage from **Settings > Billing** on claude.ai.

324 362 

363One-off runs do not count against the daily routine cap. They draw down your regular subscription usage like any other session, but they are exempt from the per-account daily routine run allowance.

364 

365## Troubleshooting

366 

367### "Routines are disabled by your organization's policy"

368 

369Your Team or Enterprise admin has likely turned off the **Routines** toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code). This is a server-side organization setting, so it cannot be overridden from your local configuration. Contact your admin to request that routines be enabled for your organization.

370 

325## Related resources371## Related resources

326 372 

327* [`/loop` and in-session scheduling](/en/scheduled-tasks): schedule local tasks within an open CLI session373* [`/loop` and in-session scheduling](/en/scheduled-tasks): schedule local tasks within an open CLI session

sandboxing.md +14 −5

Details

53* **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic53* **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic

54* **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands54* **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands

55 55 

56<Note>

57 The built-in proxy enforces the allowlist based on the requested hostname and does not terminate or inspect TLS traffic. See [Security limitations](#security-limitations) for the implications of this design, and [Custom proxy configuration](#custom-proxy-configuration) if your threat model requires TLS inspection.

58</Note>

59 

56### OS-level enforcement60### OS-level enforcement

57 61 

58The sandboxed bash tool leverages operating system security primitives:62The sandboxed bash tool leverages operating system security primitives:


87 </Tab>91 </Tab>

88</Tabs>92</Tabs>

89 93 

94WSL1 does not support sandboxing because it lacks the required Linux namespace primitives. If you see `Sandboxing requires WSL2`, upgrade your distribution to WSL2 or run Claude Code without sandboxing.

95 

96On WSL2, sandboxed commands cannot launch Windows binaries such as `cmd.exe`, `powershell.exe`, or anything under `/mnt/c/`. WSL hands these off to the Windows host over a Unix socket, which the sandbox blocks. If a command needs to invoke a Windows binary, add it to [`excludedCommands`](/en/settings#sandbox-settings) so it runs outside the sandbox.

97 

90### Enable sandboxing98### Enable sandboxing

91 99 

92You can enable sandboxing by running the `/sandbox` command:100You can enable sandboxing by running the `/sandbox` command:


97 105 

98This opens a menu where you can choose between sandbox modes. If required dependencies are missing (such as `bubblewrap` or `socat` on Linux), the menu displays installation instructions for your platform.106This 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.

99 107 

100By default, if the sandbox cannot start (missing dependencies, unsupported platform, or platform restrictions), Claude Code shows a warning and runs commands without sandboxing. To make this a hard failure instead, set [`sandbox.failIfUnavailable`](/en/settings#sandbox-settings) to `true`. This is intended for managed deployments that require sandboxing as a security gate.108By default, if the sandbox cannot start (missing dependencies or unsupported platform), Claude Code shows a warning and runs commands without sandboxing. To make this a hard failure instead, set [`sandbox.failIfUnavailable`](/en/settings#sandbox-settings) to `true`. This is intended for managed deployments that require sandboxing as a security gate.

101 109 

102### Sandbox modes110### Sandbox modes

103 111 

104Claude Code offers two sandbox modes:112Claude Code offers two sandbox modes:

105 113 

106**Auto-allow mode**: Bash commands will attempt to run inside the sandbox and are automatically allowed without requiring permission. Commands that cannot be sandboxed (such as those needing network access to non-allowed hosts) fall back to the regular permission flow. Explicit deny rules are always respected. Ask rules apply only to commands that fall back to the regular permission flow.114**Auto-allow mode**: Bash commands will attempt to run inside the sandbox and are automatically allowed without requiring permission. Commands that cannot be sandboxed (such as those needing network access to non-allowed hosts) fall back to the regular permission flow. Explicit deny rules are always respected, and `rm` or `rmdir` commands that target `/`, your home directory, or other critical system paths still trigger a permission prompt. Ask rules apply only to commands that fall back to the regular permission flow.

107 115 

108**Regular permissions mode**: All bash commands go through the standard permission flow, even when sandboxed. This provides more control but requires more approvals.116**Regular permissions mode**: All bash commands go through the standard permission flow, even when sandboxed. This provides more control but requires more approvals.

109 117 


225 233 

226## Security Limitations234## Security Limitations

227 235 

228* Network Sandboxing Limitations: The network filtering system operates by restricting the domains that processes are allowed to connect to. It does not otherwise inspect the traffic passing through the proxy and users are responsible for ensuring they only allow trusted domains in their policy.236* Network Sandboxing Limitations: The network filtering system operates by restricting the domains that processes are allowed to connect to. The built-in proxy does not terminate or perform TLS inspection on outbound traffic, so the contents of encrypted connections are not examined. You are responsible for ensuring that only trusted domains are allowed in your policy.

229 237 

230<Warning>238<Warning>

231 Users should be aware of potential risks that come from allowing broad domains like `github.com` that may allow for data exfiltration. Also, in some cases it may be possible to bypass the network filtering through [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting).239 Allowing broad domains such as `github.com` can create paths for data exfiltration. Because the proxy makes its allow decision from the client-supplied hostname without inspecting TLS, code running inside the sandbox can potentially use [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting) or similar techniques to reach hosts outside the allowlist. If your threat model requires stronger guarantees, configure a [custom proxy](#custom-proxy-configuration) that terminates TLS and inspects traffic, and install its CA certificate inside the sandbox. Stronger TLS-aware network isolation is an active area of development.

232</Warning>240</Warning>

233 241 

234* Privilege Escalation via Unix Sockets: The `allowUnixSockets` configuration can inadvertently grant access to powerful system services that could lead to sandbox bypasses. For example, if it is used to allow access to `/var/run/docker.sock` this would effectively grant access to the host system through exploiting the docker socket. Users are encouraged to carefully consider any unix sockets that they allow through the sandbox.242* Privilege Escalation via Unix Sockets: The `allowUnixSockets` configuration can inadvertently grant access to powerful system services that could lead to sandbox bypasses. For example, if it is used to allow access to `/var/run/docker.sock` this would effectively grant access to the host system through exploiting the docker socket. Users are encouraged to carefully consider any unix sockets that they allow through the sandbox.


250* Use `Read` and `Edit` deny rules to block access to specific files or directories258* Use `Read` and `Edit` deny rules to block access to specific files or directories

251* Use `WebFetch` allow/deny rules to control domain access259* Use `WebFetch` allow/deny rules to control domain access

252* Use sandbox `allowedDomains` to control which domains Bash commands can reach260* Use sandbox `allowedDomains` to control which domains Bash commands can reach

261* Use sandbox `deniedDomains` to block specific domains even when a broader `allowedDomains` wildcard would otherwise permit them

253 262 

254Paths from both `sandbox.filesystem` settings and permission rules are merged together into the final sandbox configuration.263Paths from both `sandbox.filesystem` settings and permission rules are merged together into the final sandbox configuration.

255 264 


282The sandboxed bash tool works alongside:291The sandboxed bash tool works alongside:

283 292 

284* **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth293* **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth

285* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation294* **Development containers**: Use with [dev containers](/en/devcontainer) for additional isolation

286* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)295* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)

287 296 

288## Best practices297## Best practices

Details

12 12 

13Scheduled tasks let Claude re-run a prompt automatically on an interval. Use them to poll a deployment, babysit a PR, check back on a long-running build, or remind yourself to do something later in the session. To react to events as they happen instead of polling, see [Channels](/en/channels): your CI can push the failure into the session directly.13Scheduled tasks let Claude re-run a prompt automatically on an interval. Use them to poll a deployment, babysit a PR, check back on a long-running build, or remind yourself to do something later in the session. To react to events as they happen instead of polling, see [Channels](/en/channels): your CI can push the failure into the session directly.

14 14 

15Tasks are session-scoped: they live in the current Claude Code process and are gone when you exit. For durable scheduling that survives restarts, use [Routines](/en/routines), [Desktop scheduled tasks](/en/desktop-scheduled-tasks), or [GitHub Actions](/en/github-actions).15Tasks are session-scoped: they live in the current conversation and stop when you start a new one. Resuming with `--resume` or `--continue` brings back any task that hasn't [expired](#seven-day-expiry): a recurring task created within the last 7 days, or a one-shot whose scheduled time hasn't passed yet. For scheduling that survives independently of any session, use [Routines](/en/routines), [Desktop scheduled tasks](/en/desktop-scheduled-tasks), or [GitHub Actions](/en/github-actions).

16 16 

17## Compare scheduling options17## Compare scheduling options

18 18 

19Claude Code offers three ways to schedule recurring work:19Claude Code offers three ways to schedule recurring or one-off work:

20 20 

21| | [Cloud](/en/routines) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |21| | [Cloud](/en/routines) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |

22| :------------------------- | :----------------------------- | :------------------------------------- | :----------------------------- |22| :------------------------- | :----------------------------- | :------------------------------------- | :---------------------------------- |

23| Runs on | Anthropic cloud | Your machine | Your machine |23| Runs on | Anthropic cloud | Your machine | Your machine |

24| Requires machine on | No | Yes | Yes |24| Requires machine on | No | Yes | Yes |

25| Requires open session | No | No | Yes |25| Requires open session | No | No | Yes |

26| Persistent across restarts | Yes | Yes | No (session-scoped) |26| Persistent across restarts | Yes | Yes | Restored on `--resume` if unexpired |

27| Access to local files | No (fresh clone) | Yes | Yes |27| Access to local files | No (fresh clone) | Yes | Yes |

28| MCP servers | Connectors configured per task | [Config files](/en/mcp) and connectors | Inherits from session |28| MCP servers | Connectors configured per task | [Config files](/en/mcp) and connectors | Inherits from session |

29| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |29| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |


118 118 

119Edits to `loop.md` take effect on the next iteration, so you can refine the instructions while a loop is running. When no `loop.md` exists in either location, the loop falls back to the built-in maintenance prompt. Keep the file concise: content beyond 25,000 bytes is truncated.119Edits to `loop.md` take effect on the next iteration, so you can refine the instructions while a loop is running. When no `loop.md` exists in either location, the loop falls back to the built-in maintenance prompt. Keep the file concise: content beyond 25,000 bytes is truncated.

120 120 

121### Stop a loop

122 

123To stop a `/loop` while it is waiting for the next iteration, press `Esc`. This clears the pending wakeup so the loop does not fire again. Tasks you scheduled by [asking Claude directly](#manage-scheduled-tasks) are not affected by `Esc` and stay in place until you delete them.

124 

121## Set a one-time reminder125## Set a one-time reminder

122 126 

123For one-shot reminders, describe what you want in natural language instead of using `/loop`. Claude schedules a single-fire task that deletes itself after running.127For one-shot reminders, describe what you want in natural language instead of using `/loop`. Claude schedules a single-fire task that deletes itself after running.


162 166 

163### Jitter167### Jitter

164 168 

165To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a small deterministic offset to fire times:169To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a deterministic offset to fire times:

166 170 

167* Recurring tasks fire up to 10% of their period late, capped at 15 minutes. An hourly job might fire anywhere from `:00` to `:06`.171* Recurring tasks fire up to 30 minutes after the scheduled time (or up to half the interval, for tasks that run more often than hourly). An hourly job scheduled for `:00` may fire anywhere up to `:30`.

168* One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.172* One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.

169 173 

170The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not `:00` or `:30`, for example `3 9 * * *` instead of `0 9 * * *`, and the one-shot jitter will not apply.174The offset is derived from the task ID, so the same task always gets the same offset. If exact timing matters, pick a minute that is not `:00` or `:30`, for example `3 9 * * *` instead of `0 9 * * *`, and the one-shot jitter will not apply.


198 202 

199Session-scoped scheduling has inherent constraints:203Session-scoped scheduling has inherent constraints:

200 204 

201* Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit cancels everything.205* Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit stops them firing.

202* No catch-up for missed fires. If a task's scheduled time passes while Claude is busy on a long-running request, it fires once when Claude becomes idle, not once per missed interval.206* No catch-up for missed fires. If a task's scheduled time passes while Claude is busy on a long-running request, it fires once when Claude becomes idle, not once per missed interval.

203* No persistence across restarts. Restarting Claude Code clears all session-scoped tasks.207* Starting a fresh conversation clears all session-scoped tasks. Resuming with `claude --resume` or `claude --continue` restores tasks that have not expired: recurring tasks within seven days of creation, and one-shot tasks whose scheduled time has not yet passed. Background Bash and monitor tasks are never restored on resume.

204 208 

205For cron-driven automation that needs to run unattended:209For cron-driven automation that needs to run unattended:

206 210 

security.md +4 −4

Details

27* **Sandboxed bash tool**: [Sandbox](/en/sandboxing) bash commands with filesystem and network isolation, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries where Claude Code can work autonomously27* **Sandboxed bash tool**: [Sandbox](/en/sandboxing) bash commands with filesystem and network isolation, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries where Claude Code can work autonomously

28* **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary28* **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary

29* **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization29* **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization

30* **Accept Edits mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects30* **Accept Edits mode**: Auto-approves file edits and a fixed set of filesystem Bash commands like `mkdir`, `touch`, `rm`, `mv`, `cp`, and `sed` for paths in the working directory. Other Bash commands and out-of-scope paths still prompt

31 31 

32### User responsibility32### User responsibility

33 33 


59* **Network request approval**: Tools that make network requests require user approval by default59* **Network request approval**: Tools that make network requests require user approval by default

60* **Isolated context windows**: Web fetch uses a separate context window to avoid injecting potentially malicious prompts60* **Isolated context windows**: Web fetch uses a separate context window to avoid injecting potentially malicious prompts

61* **Trust verification**: First-time codebase runs and new MCP servers require trust verification61* **Trust verification**: First-time codebase runs and new MCP servers require trust verification

62 * Note: Trust verification is disabled when running non-interactively with the `-p` flag62 * Note: Trust verification is disabled when running non-interactively with the `-p` flag. The exception is [`--worktree`](/en/worktrees), which still requires that trust has been accepted for the directory

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

64* **Fail-closed matching**: Unmatched commands default to requiring manual approval64* **Fail-closed matching**: Unmatched commands default to requiring manual approval

65* **Natural language descriptions**: Complex bash commands include explanations for user understanding65* **Natural language descriptions**: Complex bash commands include explanations for user understanding


114 114 

115* Review all suggested changes before approval115* Review all suggested changes before approval

116* Use project-specific permission settings for sensitive repositories116* Use project-specific permission settings for sensitive repositories

117* Consider using [devcontainers](/en/devcontainer) for additional isolation117* Consider using [dev containers](/en/devcontainer) for additional isolation

118* Regularly audit your permission settings with `/permissions`118* Regularly audit your permission settings with `/permissions`

119 119 

120### Team security120### Team security


130If you discover a security vulnerability in Claude Code:130If you discover a security vulnerability in Claude Code:

131 131 

1321. Do not disclose it publicly1321. Do not disclose it publicly

1332. Report it through our [HackerOne program](https://hackerone.com/anthropic-vdp/reports/new?type=team\&report_type=vulnerability)1332. Report it through our [HackerOne program](https://hackerone.com/4f1f16ba-10d3-4d09-9ecc-c721aad90f24/embedded_submissions/new)

1343. Include detailed reproduction steps1343. Include detailed reproduction steps

1354. Allow time for us to address the issue before public disclosure1354. Allow time for us to address the issue before public disclosure

136 136 

Details

41 </Step>41 </Step>

42 42 

43 <Step title="Define your settings">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 [hooks](/en/hooks), [environment variables](/en/env-vars), and [managed-only settings](/en/permissions#managed-only-settings) like `allowManagedPermissionRulesOnly`.44 Add your configuration as JSON. All [settings available in `settings.json`](/en/settings#available-settings) are supported except those restricted to OS-level policy delivery; see [Current limitations](#current-limitations) for that short list. This includes [hooks](/en/hooks), [environment variables](/en/env-vars), and [managed-only settings](/en/permissions#managed-only-settings) like `allowManagedPermissionRulesOnly`.

45 45 

46 This example enforces a permission deny list, prevents users from bypassing permissions, and restricts permission rules to those defined in managed settings:46 This example enforces a permission deny list, prevents users from bypassing permissions, and restricts permission rules to those defined in managed settings:

47 47 


93 }93 }

94 ```94 ```

95 95 

96 Because hooks execute shell commands, users see a [security approval dialog](#security-approval-dialogs) before they're applied. See [Configure the auto mode classifier](/en/permissions#configure-the-auto-mode-classifier) for how the `autoMode` entries affect what the classifier blocks and important warnings about the `allow` and `soft_deny` fields.96 Because hooks execute shell commands, users see a [security approval dialog](#security-approval-dialogs) before they're applied. See [Configure auto mode](/en/auto-mode-config) for how the `autoMode` entries affect what the classifier blocks and important warnings about the `environment`, `allow`, `soft_deny`, and `hard_deny` fields.

97 </Step>97 </Step>

98 98 

99 <Step title="Save and deploy">99 <Step title="Save and deploy">


124 124 

125* Settings apply uniformly to all users in the organization. Per-group configurations are not yet supported.125* Settings apply uniformly to all users in the organization. Per-group configurations are not yet supported.

126* [MCP server configurations](/en/mcp#managed-mcp-configuration) cannot be distributed through server-managed settings.126* [MCP server configurations](/en/mcp#managed-mcp-configuration) cannot be distributed through server-managed settings.

127* Settings restricted to OS-level policy sources, such as `policyHelper` and `wslInheritsWindowsSettings`, are not honored. Deploy them through MDM or a system `managed-settings.json` file instead.

127 128 

128## Settings delivery129## Settings delivery

129 130 


203Server-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.204Server-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.

204 205 

205| Scenario | Behavior |206| Scenario | Behavior |

206| :----------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |207| :--------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

207| User edits the cached settings file | Tampered file applies at startup, but correct settings restore on the next server fetch |208| User edits the cached settings file | Tampered file applies at startup, but correct settings restore on the next server fetch |

208| User deletes the cached settings file | First-launch behavior occurs: settings fetch asynchronously with a brief unenforced window |209| User deletes the cached settings file | First-launch behavior occurs: settings fetch asynchronously with a brief unenforced window |

209| API is unavailable | Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch. With `forceRemoteSettingsRefresh: true`, the CLI exits instead of continuing |210| API is unavailable | Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch. With `forceRemoteSettingsRefresh: true`, the CLI exits instead of continuing |

210| User authenticates with a different organization | Settings are not delivered for accounts outside the managed organization |211| User authenticates with a different organization | Settings are not delivered for accounts outside the managed organization |

211| User sets a non-default `ANTHROPIC_BASE_URL` | Server-managed settings are bypassed when using third-party API providers |212| User configures a [third-party model provider](#platform-availability) | Server-managed settings are bypassed. This includes setting `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_MANTLE`, `CLAUDE_CODE_USE_VERTEX`, `CLAUDE_CODE_USE_FOUNDRY`, or a non-default `ANTHROPIC_BASE_URL` |

212 213 

213To detect runtime configuration changes, use [`ConfigChange` hooks](/en/hooks#configchange) to log modifications or block unauthorized changes before they take effect.214To detect runtime configuration changes, use [`ConfigChange` hooks](/en/hooks#configchange) to log modifications or block unauthorized changes before they take effect.

214 215 

settings.md +120 −43

Details

71| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |71| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

72| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` |72| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` |

73 73 

74On Windows, paths shown as `~/.claude` resolve to `%USERPROFILE%\.claude`.

75 

74***76***

75 77 

76## Settings files78## Settings files


87 89 

88 * **Server-managed settings**: delivered from Anthropic's servers via the Claude.ai admin console. See [server-managed settings](/en/server-managed-settings).90 * **Server-managed settings**: delivered from Anthropic's servers via the Claude.ai admin console. See [server-managed settings](/en/server-managed-settings).

89 * **MDM/OS-level policies**: delivered through native device management on macOS and Windows:91 * **MDM/OS-level policies**: delivered through native device management on macOS and Windows:

90 * macOS: `com.anthropic.claudecode` managed preferences domain (deployed via configuration profiles in Jamf, Iru (Kandji), or other MDM tools)92 * macOS: `com.anthropic.claudecode` managed preferences domain. The plist's top-level keys mirror `managed-settings.json`, with nested settings as dictionaries and arrays as plist arrays. Deploy via configuration profiles in Jamf, Iru (Kandji), or similar MDM tools.

91 * Windows: `HKLM\SOFTWARE\Policies\ClaudeCode` registry key with a `Settings` value (REG\_SZ or REG\_EXPAND\_SZ) containing JSON (deployed via Group Policy or Intune)93 * Windows: `HKLM\SOFTWARE\Policies\ClaudeCode` registry key with a `Settings` value (REG\_SZ or REG\_EXPAND\_SZ) containing JSON (deployed via Group Policy or Intune)

92 * Windows (user-level): `HKCU\SOFTWARE\Policies\ClaudeCode` (lowest policy priority, only used when no admin-level source exists)94 * Windows (user-level): `HKCU\SOFTWARE\Policies\ClaudeCode` (lowest policy priority, only used when no admin-level source exists)

93 * **File-based**: `managed-settings.json` and `managed-mcp.json` deployed to system directories:95 * **File-based**: `managed-settings.json` and `managed-mcp.json` deployed to system directories:


114 Managed deployments can also restrict **plugin marketplace additions** using116 Managed deployments can also restrict **plugin marketplace additions** using

115 `strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).117 `strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).

116 </Note>118 </Note>

117* **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`.119* **Other configuration** is stored in `~/.claude.json`. This file contains your 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`.

118 120 

119<Note>121<Note>

120 Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.122 Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.


150 152 

151The `$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.153The `$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.

152 154 

155The published schema is updated periodically and may not include settings added in the most recent CLI releases, so a validation warning on a recently documented field does not necessarily mean your configuration is invalid.

156 

153### Available settings157### Available settings

154 158 

155`settings.json` supports a number of options:159`settings.json` supports a number of options:

156 160 

157| Key | Description | Example |161| Key | Description | Example |

158| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |162| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |

159| `agent` | Run the main thread as a named subagent. Applies that subagent's system prompt, tool restrictions, and model. See [Invoke subagents explicitly](/en/sub-agents#invoke-subagents-explicitly) | `"code-reviewer"` |163| `agent` | Run the main thread as a named subagent. Applies that subagent's system prompt, tool restrictions, and model. See [Invoke subagents explicitly](/en/sub-agents#invoke-subagents-explicitly) | `"code-reviewer"` |

160| `allowedChannelPlugins` | (Managed settings only) Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Undefined = fall back to the default, empty array = block all channel plugins. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](/en/channels#restrict-which-channel-plugins-can-run) | `[{ "marketplace": "claude-plugins-official", "plugin": "telegram" }]` |164| `allowedChannelPlugins` | (Managed settings only) Allowlist of channel plugins that may push messages. Replaces the default Anthropic allowlist when set. Undefined = fall back to the default, empty array = block all channel plugins. Requires `channelsEnabled: true`. See [Restrict which channel plugins can run](/en/channels#restrict-which-channel-plugins-can-run) | `[{ "marketplace": "claude-plugins-official", "plugin": "telegram" }]` |

161| `allowedHttpHookUrls` | Allowlist of URL patterns that HTTP hooks may target. Supports `*` as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See [Hook configuration](#hook-configuration) | `["https://hooks.example.com/*"]` |165| `allowedHttpHookUrls` | Allowlist of URL patterns that HTTP hooks may target. Supports `*` as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See [Hook configuration](#hook-configuration) | `["https://hooks.example.com/*"]` |


163| `allowManagedHooksOnly` | (Managed settings only) Only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked. See [Hook configuration](#hook-configuration) | `true` |167| `allowManagedHooksOnly` | (Managed settings only) Only managed hooks, SDK hooks, and hooks from plugins force-enabled in managed settings `enabledPlugins` are loaded. User, project, and all other plugin hooks are blocked. See [Hook configuration](#hook-configuration) | `true` |

164| `allowManagedMcpServersOnly` | (Managed settings only) Only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. Users can still add MCP servers, but only the admin-defined allowlist applies. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `true` |168| `allowManagedMcpServersOnly` | (Managed settings only) Only `allowedMcpServers` from managed settings are respected. `deniedMcpServers` still merges from all sources. Users can still add MCP servers, but only the admin-defined allowlist applies. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `true` |

165| `allowManagedPermissionRulesOnly` | (Managed settings only) Prevent user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. See [Managed-only settings](/en/permissions#managed-only-settings) | `true` |169| `allowManagedPermissionRulesOnly` | (Managed settings only) Prevent user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. See [Managed-only settings](/en/permissions#managed-only-settings) | `true` |

166| `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` |170| `alwaysThinkingEnabled` | Enable [extended thinking](/en/model-config#extended-thinking) by default for all sessions. Typically configured via the `/config` command rather than editing directly. To force thinking off regardless of this setting, set [`CLAUDE_CODE_DISABLE_THINKING`](/en/env-vars) in `env` | `true` |

167| `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` |171| `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. Set the refresh interval with [`CLAUDE_CODE_API_KEY_HELPER_TTL_MS`](/en/env-vars) | `/bin/generate_temp_api_key.sh` |

168| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |172| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |

169| `autoMemoryDirectory` | Custom directory for [auto memory](/en/memory#storage-location) storage. Accepts `~/`-expanded paths. Not accepted in project settings (`.claude/settings.json`) to prevent shared repos from redirecting memory writes to sensitive locations. Accepted from policy, local, and user settings | `"~/my-memory-dir"` |173| `autoMemoryDirectory` | Custom directory for [auto memory](/en/memory#storage-location) storage. Accepts an absolute path or a `~/`-prefixed path. Accepted from policy and user settings, and from the `--settings` flag. Not accepted from project or local settings, since a cloned repository could supply either file to redirect memory writes to sensitive locations | `"~/my-memory-dir"` |

170| `autoMode` | Customize what the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier blocks and allows. Contains `environment`, `allow`, and `soft_deny` arrays of prose rules. See [Configure the auto mode classifier](/en/permissions#configure-the-auto-mode-classifier). Not read from shared project settings | `{"environment": ["Trusted repo: github.example.com/acme"]}` |174| `autoMemoryEnabled` | Enable [auto memory](/en/memory#enable-or-disable-auto-memory). When `false`, Claude does not read from or write to the auto memory directory. Default: `true`. You can also toggle this with `/memory` during a session. To disable via environment variable, set [`CLAUDE_CODE_DISABLE_AUTO_MEMORY`](/en/env-vars) in `env` | `false` |

171| `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"` |175| `autoMode` | Customize what the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier blocks and allows. Contains `environment`, `allow`, `soft_deny`, and `hard_deny` arrays of prose rules. Include the literal string `"$defaults"` in an array to inherit the built-in rules at that position. See [Configure auto mode](/en/auto-mode-config). Not read from shared project settings | `{"soft_deny": ["$defaults", "Never run terraform apply"]}` |

172| `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"]` |176| `autoScrollEnabled` | In [fullscreen rendering](/en/fullscreen), follow new output to the bottom of the conversation. Default: `true`. Appears in `/config` as **Auto-scroll**. Permission prompts still scroll into view when this is off | `false` |

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. To disable auto-updates entirely, set [`DISABLE_AUTOUPDATER`](/en/setup#disable-auto-updates) in `env` | `"stable"` |

178| `availableModels` | Restrict which models users can select via `/model`, `--model`, or `ANTHROPIC_MODEL`. Does not affect the Default option. See [Restrict model selection](/en/model-config#restrict-model-selection) | `["sonnet", "haiku"]` |

179| `awaySummaryEnabled` | Show a one-line session recap when you return to the terminal after a few minutes away. Set to `false` or turn off Session recap in `/config` to disable. Same as [`CLAUDE_CODE_ENABLE_AWAY_SUMMARY`](/en/env-vars) | `true` |

173| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |180| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |

174| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |181| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |

175| `blockedMarketplaces` | (Managed settings only) Blocklist of marketplace sources. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "untrusted/plugins" }]` |182| `blockedMarketplaces` | (Managed settings only) Blocklist of marketplace sources. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. Blocked sources are checked before downloading, so they never touch the filesystem. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "untrusted/plugins" }]` |

176| `channelsEnabled` | (Managed settings only) Allow [channels](/en/channels) for Team and Enterprise users. Unset or `false` blocks channel message delivery regardless of what users pass to `--channels` | `true` |183| `channelsEnabled` | (Managed settings only) Allow [channels](/en/channels) for the organization. On claude.ai Team and Enterprise plans, channels are blocked when this is unset or `false`. For [Anthropic Console](/en/authentication#claude-console-authentication) accounts using API key authentication, channels are allowed by default unless your organization deploys managed settings, in which case this key must be set to `true` | `true` |

177| `cleanupPeriodDays` | Session files older than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](/en/common-workflows#worktree-cleanup) at startup. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/en/env-vars) environment variable, or in non-interactive mode (`-p`) use the `--no-session-persistence` flag or the `persistSession: false` SDK option. | `20` |184| `claudeMdExcludes` | Glob patterns or absolute paths of `CLAUDE.md` files to skip when loading [memory](/en/memory). Patterns match against absolute file paths. Only applies to user, project, and local memory; managed policy files cannot be excluded | `["**/vendor/**/CLAUDE.md"]` |

185| `cleanupPeriodDays` | Session files older than this period are deleted at startup (default: 30 days, minimum 1). Setting to `0` is rejected with a validation error. Also controls the age cutoff for automatic removal of [orphaned subagent worktrees](/en/worktrees#clean-up-worktrees) at startup. To disable transcript writes entirely, set the [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](/en/env-vars) environment variable, or in non-interactive mode (`-p`) use the `--no-session-persistence` flag or the `persistSession: false` SDK option. | `20` |

178| `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"]` |186| `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"]` |

179| `defaultShell` | Default shell for input-box `!` commands. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](/en/tools-reference#powershell-tool) | `"powershell"` |187| `defaultShell` | Default shell for input-box `!` commands. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` routes interactive `!` commands through PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. See [PowerShell tool](/en/tools-reference#powershell-tool) | `"powershell"` |

180| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` |188| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` |

181| `disableAllHooks` | Disable all [hooks](/en/hooks) and any custom [status line](/en/statusline) | `true` |189| `disableAllHooks` | Disable all [hooks](/en/hooks) and any custom [status line](/en/statusline) | `true` |

182| `disableAutoMode` | Set to `"disable"` to prevent [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) from being activated. Removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `"disable"` |190| `disableAutoMode` | Set to `"disable"` to prevent [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) from being activated. Removes `auto` from the `Shift+Tab` cycle and rejects `--permission-mode auto` at startup. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `"disable"` |

183| `disableDeepLinkRegistration` | Set to `"disable"` to prevent Claude Code from registering the `claude-cli://` protocol handler with the operating system on startup. Deep links let external tools open a Claude Code session with a pre-filled prompt via `claude-cli://open?q=...`. The `q` parameter supports multi-line prompts using URL-encoded newlines (`%0A`). Useful in environments where protocol handler registration is restricted or managed separately | `"disable"` |191| `disableDeepLinkRegistration` | Set to `"disable"` to prevent Claude Code from registering the `claude-cli://` protocol handler with the operating system on startup. [Deep links](/en/deep-links) let external tools open a Claude Code session with a pre-filled prompt. Useful in environments where protocol handler registration is restricted or managed separately | `"disable"` |

184| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |192| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |

193| `disableRemoteControl` | {/* min-version: 2.1.128 */}Disable [Remote Control](/en/remote-control): blocks `claude remote-control`, the `--remote-control` flag, auto-start, and the in-session toggle. Typically placed in [managed settings](/en/permissions#managed-settings) for per-device MDM enforcement, but works from any scope. Requires Claude Code v2.1.128 or later | `true` |

185| `disableSkillShellExecution` | Disable inline shell execution for `` !`...` `` and ` ```! ` blocks in [skills](/en/skills) and custom commands from user, project, plugin, or additional-directory sources. Commands are replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `true` |194| `disableSkillShellExecution` | Disable inline shell execution for `` !`...` `` and ` ```! ` blocks in [skills](/en/skills) and custom commands from user, project, plugin, or additional-directory sources. Commands are replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. Most useful in [managed settings](/en/permissions#managed-settings) where users cannot override it | `true` |

186| `effortLevel` | Persist the [effort level](/en/model-config#adjust-effort-level) across sessions. Accepts `"low"`, `"medium"`, or `"high"`. Written automatically when you run `/effort low`, `/effort medium`, or `/effort high`. Supported on Opus 4.6 and Sonnet 4.6 | `"medium"` |195| `editorMode` | Key binding mode for the input prompt: `"normal"` or `"vim"`. Default: `"normal"`. Appears in `/config` as **Editor mode** | `"vim"` |

196| `effortLevel` | Persist the [effort level](/en/model-config#adjust-effort-level) across sessions. Accepts `"low"`, `"medium"`, `"high"`, or `"xhigh"`. Written automatically when you run `/effort` with one of those values. `--effort` and [`CLAUDE_CODE_EFFORT_LEVEL`](/en/env-vars) override this for one session. See [Adjust effort level](/en/model-config#adjust-effort-level) for supported models | `"xhigh"` |

187| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |197| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |

188| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |198| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |

189| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |199| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |

190| `fastModePerSessionOptIn` | When `true`, fast mode does not persist across sessions. Each session starts with fast mode off, requiring users to enable it with `/fast`. The user's fast mode preference is still saved. See [Require per-session opt-in](/en/fast-mode#require-per-session-opt-in) | `true` |200| `fastModePerSessionOptIn` | When `true`, fast mode does not persist across sessions. Each session starts with fast mode off, requiring users to enable it with `/fast`. The user's fast mode preference is still saved. See [Require per-session opt-in](/en/fast-mode#require-per-session-opt-in) | `true` |

191| `feedbackSurveyRate` | Probability (0–1) that the [session quality survey](/en/data-usage#session-quality-surveys) appears when eligible. Set to `0` to suppress entirely. Useful when using Bedrock, Vertex, or Foundry where the default sample rate does not apply | `0.05` |201| `feedbackSurveyRate` | Probability (0–1) that the [session quality survey](/en/data-usage#session-quality-surveys) appears when eligible. Set to `0` to suppress entirely, or set [`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY`](/en/env-vars) in `env`. Useful when using Bedrock, Vertex, or Foundry where the default sample rate does not apply | `0.05` |

192| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |202| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |

193| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |203| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |

194| `forceLoginOrgUUID` | Require login to belong to a specific organization. Accepts a single UUID string, which also pre-selects that organization during login, or an array of UUIDs where any listed organization is accepted without pre-selection. When set in managed settings, login fails if the authenticated account does not belong to a listed organization; an empty array fails closed and blocks login with a misconfiguration message | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` or `["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"]` |204| `forceLoginOrgUUID` | Require login to belong to a specific organization. Accepts a single UUID string, which also pre-selects that organization during login, or an array of UUIDs where any listed organization is accepted without pre-selection. When set in managed settings, login fails if the authenticated account does not belong to a listed organization; an empty array fails closed and blocks login with a misconfiguration message | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` or `["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"]` |

195| `forceRemoteSettingsRefresh` | (Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits rather than continuing with cached or no settings. When not set, startup continues without waiting for remote settings. See [fail-closed enforcement](/en/server-managed-settings#enforce-fail-closed-startup) | `true` |205| `forceRemoteSettingsRefresh` | (Managed settings only) Block CLI startup until remote managed settings are freshly fetched from the server. If the fetch fails, the CLI exits rather than continuing with cached or no settings. When not set, startup continues without waiting for remote settings. See [fail-closed enforcement](/en/server-managed-settings#enforce-fail-closed-startup) | `true` |

206| `gcpAuthRefresh` | Custom script that refreshes GCP Application Default Credentials when they expire or cannot be loaded. See [advanced credential configuration](/en/google-vertex-ai#advanced-credential-configuration) | `gcloud auth application-default login` |

196| `hooks` | Configure custom commands to run at lifecycle events. See [hooks documentation](/en/hooks) for format | See [hooks](/en/hooks) |207| `hooks` | Configure custom commands to run at lifecycle events. See [hooks documentation](/en/hooks) for format | See [hooks](/en/hooks) |

197| `httpHookAllowedEnvVars` | Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective `allowedEnvVars` is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See [Hook configuration](#hook-configuration) | `["MY_TOKEN", "HOOK_SECRET"]` |208| `httpHookAllowedEnvVars` | Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective `allowedEnvVars` is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See [Hook configuration](#hook-configuration) | `["MY_TOKEN", "HOOK_SECRET"]` |

198| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |209| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |

199| `includeGitInstructions` | Include built-in commit and PR workflow instructions and the git status snapshot in Claude's system prompt (default: `true`). Set to `false` to remove both, for example when using your own git workflow skills. The `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` environment variable takes precedence over this setting when set | `false` |210| `includeGitInstructions` | Include built-in commit and PR workflow instructions and the git status snapshot in Claude's system prompt (default: `true`). Set to `false` to remove both, for example when using your own git workflow skills. The `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` environment variable takes precedence over this setting when set | `false` |

200| `language` | Configure Claude's preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default. Also sets the [voice dictation](/en/voice-dictation#change-the-dictation-language) language | `"japanese"` |211| `language` | Configure Claude's preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default. Also sets the [voice dictation](/en/voice-dictation#change-the-dictation-language) language | `"japanese"` |

201| `minimumVersion` | Prevent the auto-updater from downgrading below a specific version. Automatically set when switching to the stable channel and choosing to stay on the current version until stable catches up. Used with `autoUpdatesChannel` | `"2.1.85"` |212| `minimumVersion` | Floor that prevents background auto-updates and `claude update` from installing a version below this one. Switching from the `"latest"` channel to `"stable"` via `/config` prompts you to stay on the current version or allow the downgrade. Choosing to stay sets this value. Also useful in [managed settings](/en/permissions#managed-settings) to pin an organization-wide minimum | `"2.1.100"` |

202| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-6"` |213| `model` | Override the default model to use for Claude Code. `--model` and [`ANTHROPIC_MODEL`](/en/model-config#environment-variables) override this for one session | `"claude-sonnet-4-6"` |

203| `modelOverrides` | Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs. Each model picker entry uses its mapped value when calling the provider API. See [Override model IDs per version](/en/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |214| `modelOverrides` | Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs. Each model picker entry uses its mapped value when calling the provider API. See [Override model IDs per version](/en/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |

204| `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` |215| `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically. Set the refresh interval with [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](/en/env-vars). See [Dynamic headers](/en/monitoring-usage#dynamic-headers) | `/bin/generate_otel_headers.sh` |

205| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/en/output-styles) | `"Explanatory"` |216| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/en/output-styles) | `"Explanatory"` |

217| `parentSettingsBehavior` | {/* min-version: 2.1.133 */}(Managed settings only) Controls whether managed settings supplied programmatically by an embedding host process, such as the Agent SDK or an IDE extension, apply when an admin-deployed managed tier is also present. `"first-wins"`: the parent-supplied settings are dropped and only the admin tier applies. `"merge"`: the parent-supplied settings apply under the admin tier, filtered so they can tighten policy but not loosen it. Has no effect when no admin tier is deployed. Default: `"first-wins"`. Requires Claude Code v2.1.133 or later | `"merge"` |

206| `permissions` | See table below for structure of permissions. | |218| `permissions` | See table below for structure of permissions. | |

207| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |219| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |

208| `pluginTrustMessage` | (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use this to add organization-specific context, for example to confirm that plugins from your internal marketplace are vetted. | `"All plugins from our marketplace are approved by IT"` |220| `pluginTrustMessage` | (Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use this to add organization-specific context, for example to confirm that plugins from your internal marketplace are vetted. | `"All plugins from our marketplace are approved by IT"` |

221| `policyHelper` | {/* min-version: 2.1.136 */}Admin-deployed executable that computes managed settings dynamically at startup. Only honored from MDM or a system `managed-settings.json` file. See [Compute managed settings with a policy helper](#compute-managed-settings-with-a-policy-helper). Requires Claude Code v2.1.136 or later | `{"path": "/usr/local/bin/claude-policy"}` |

222| `preferredNotifChannel` | Method for task-complete and permission-prompt notifications: `"auto"`, `"terminal_bell"`, `"iterm2"`, `"iterm2_with_bell"`, `"kitty"`, `"ghostty"`, or `"notifications_disabled"`. Default: `"auto"`, which sends a desktop notification in iTerm2, Ghostty, and Kitty and does nothing in other terminals. Set `"terminal_bell"` to ring the bell character in any terminal. Appears in `/config` as **Notifications**. See [Get a terminal bell or notification](/en/terminal-config#get-a-terminal-bell-or-notification) | `"terminal_bell"` |

209| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |223| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |

224| `prUrlTemplate` | URL template for the PR badge shown in the footer and in tool-result summaries. Substitutes `{host}`, `{owner}`, `{repo}`, `{number}`, and `{url}` from the `gh`-reported PR URL. Use to point PR links at an internal code-review tool instead of `github.com`. Does not affect `#123` autolinks in Claude's prose | `"https://reviews.example.com/{owner}/{repo}/pull/{number}"` |

210| `respectGitignore` | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions | `false` |225| `respectGitignore` | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions | `false` |

211| `showClearContextOnPlanAccept` | Show the "clear context" option on the plan accept screen. Defaults to `false`. Set to `true` to restore the option | `true` |226| `showClearContextOnPlanAccept` | Show the "clear context" option on the plan accept screen. Defaults to `false`. Set to `true` to restore the option | `true` |

212| `showThinkingSummaries` | Show [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) summaries in interactive sessions. When unset or `false` (default in interactive mode), thinking blocks are redacted by the API and shown as a collapsed stub. Redaction only changes what you see, not what the model generates: to reduce thinking spend, [lower the budget or disable thinking](/en/common-workflows#use-extended-thinking-thinking-mode) instead. Non-interactive mode (`-p`) and SDK callers always receive summaries regardless of this setting | `true` |227| `showThinkingSummaries` | Show [extended thinking](/en/model-config#extended-thinking) summaries in interactive sessions. When unset or `false` (default in interactive mode), thinking blocks are redacted by the API and shown as a collapsed stub. Redaction only changes what you see, not what the model generates: to reduce thinking spend, [lower the budget or disable thinking](/en/model-config#extended-thinking) instead. Non-interactive mode (`-p`) and SDK callers always receive summaries regardless of this setting | `true` |

228| `showTurnDuration` | Show turn duration messages after responses, e.g. "Cooked for 1m 6s". Default: `true`. Appears in `/config` as **Show turn duration** | `false` |

229| `skillOverrides` | {/* min-version: 2.1.129 */}Per-skill visibility overrides keyed by skill name. Value is `"on"`, `"name-only"`, `"user-invocable-only"`, or `"off"`. Lets you hide or collapse a skill without editing its SKILL.md. Does not apply to plugin skills, which are managed through `/plugin`. The `/skills` menu writes these to `.claude/settings.local.json`. See [Override skill visibility from settings](/en/skills#override-skill-visibility-from-settings). Requires Claude Code v2.1.129 or later | `{"legacy-context": "name-only", "deploy": "off"}` |

230| `skipWebFetchPreflight` | Skip the [WebFetch domain safety check](/en/data-usage#webfetch-domain-safety-check) that sends each requested hostname to `api.anthropic.com` before fetching. Set to `true` in environments that block traffic to Anthropic, such as Bedrock, Vertex AI, or Foundry deployments with restrictive egress. When skipped, WebFetch attempts any URL without consulting the blocklist | `true` |

213| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |231| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |

214| `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"] }` |232| `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"] }` |

215| `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"]}` |233| `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"]}` |

234| `sshConfigs` | SSH connections to show in the [Desktop](/en/desktop#pre-configure-ssh-connections-for-your-team) environment dropdown. Each entry requires `id`, `name`, and `sshHost`; `sshPort`, `sshIdentityFile`, and `startDirectory` are optional. When set in managed settings, connections are read-only for users. Read from managed and user settings only | `[{"id": "dev-vm", "name": "Dev VM", "sshHost": "user@dev.example.com"}]` |

216| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |235| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |

217| `strictKnownMarketplaces` | (Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Applies to marketplace additions only. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |236| `strictKnownMarketplaces` | (Managed settings only) Allowlist of plugin marketplace sources. Undefined = no restrictions, empty array = lockdown. Enforced on marketplace add and on plugin install, update, refresh, and auto-update, so a marketplace added before the policy was set cannot be used to fetch plugins. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |

237| `syntaxHighlightingDisabled` | Disable syntax highlighting in diffs, code blocks, and file previews | `true` |

238| `teammateMode` | How [agent team](/en/agent-teams) teammates display: `auto` (picks split panes in tmux or iTerm2, in-process otherwise), `in-process`, or `tmux`. `--teammate-mode` overrides this for one session. See [choose a display mode](/en/agent-teams#choose-a-display-mode) | `"in-process"` |

239| `terminalProgressBarEnabled` | Show the terminal progress bar in supported terminals: ConEmu, Ghostty 1.2.0+, and iTerm2 3.6.6+. Default: `true`. Appears in `/config` as **Terminal progress bar** | `false` |

240| `tui` | Terminal UI renderer. Use `"fullscreen"` for the flicker-free [alt-screen renderer](/en/fullscreen) with virtualized scrollback. Use `"default"` for the classic main-screen renderer. Set via `/tui`. You can also set the [`CLAUDE_CODE_NO_FLICKER`](/en/env-vars) environment variable | `"fullscreen"` |

218| `useAutoModeDuringPlan` | Whether plan mode uses auto mode semantics when auto mode is available. Default: `true`. Not read from shared project settings. Appears in `/config` as "Use auto mode during plan" | `false` |241| `useAutoModeDuringPlan` | Whether plan mode uses auto mode semantics when auto mode is available. Default: `true`. Not read from shared project settings. Appears in `/config` as "Use auto mode during plan" | `false` |

219| `viewMode` | Default transcript view mode on startup: `"default"`, `"verbose"`, or `"focus"`. Overrides the sticky Ctrl+O selection when set | `"verbose"` |242| `viewMode` | Default transcript view mode on startup: `"default"`, `"verbose"`, or `"focus"`. Overrides the sticky `/focus` selection when set. The `--verbose` flag overrides this for one session | `"verbose"` |

220| `voiceEnabled` | Enable push-to-talk [voice dictation](/en/voice-dictation). Written automatically when you run `/voice`. Requires a Claude.ai account | `true` |243| `voice` | [Voice dictation](/en/voice-dictation) settings: `enabled` turns dictation on, `mode` selects `"hold"` or `"tap"`, and `autoSubmit` sends the prompt on key release in hold mode. Written automatically when you run `/voice`. Requires a Claude.ai account | `{ "enabled": true, "mode": "tap" }` |

244| `voiceEnabled` | Legacy alias for `voice.enabled`. Prefer the `voice` object | `true` |

245| `wslInheritsWindowsSettings` | (Windows managed settings only) When `true`, Claude Code on WSL reads managed settings from the Windows policy chain in addition to `/etc/claude-code`, with Windows sources taking priority. Only honored when set in the HKLM registry key or `C:\Program Files\ClaudeCode\managed-settings.json`, both of which require Windows admin to write. For HKCU policy to also apply on WSL, the flag must additionally be set in HKCU itself. Has no effect on native Windows | `true` |

221 246 

222### Global config settings247### Global config settings

223 248 

224These settings are stored in `~/.claude.json` rather than `settings.json`. Adding them to `settings.json` will trigger a schema validation error.249These settings are stored in `~/.claude.json` rather than `settings.json`. Adding them to `settings.json` will trigger a schema validation error.

225 250 

251<Note>

252 Versions before v2.1.119 also store `autoScrollEnabled`, `editorMode`, `showTurnDuration`, `teammateMode`, and `terminalProgressBarEnabled` here instead of in `settings.json`.

253</Note>

254 

226| Key | Description | Example |255| Key | Description | Example |

227| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------- |256| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------ |

228| `autoConnectIde` | Automatically connect to a running IDE when Claude Code starts from an external terminal. Default: `false`. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal | `true` |257| `autoConnectIde` | Automatically connect to a running IDE when Claude Code starts from an external terminal. Default: `false`. Appears in `/config` as **Auto-connect to IDE (external terminal)** when running outside a VS Code or JetBrains terminal. The [`CLAUDE_CODE_AUTO_CONNECT_IDE`](/en/env-vars) environment variable overrides this when set | `true` |

229| `autoInstallIdeExtension` | Automatically install the Claude Code IDE extension when running from a VS Code terminal. Default: `true`. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/en/env-vars) environment variable | `false` |258| `autoInstallIdeExtension` | Automatically install the Claude Code IDE extension when running from a VS Code terminal. Default: `true`. Appears in `/config` as **Auto-install IDE extension** when running inside a VS Code or JetBrains terminal. You can also set the [`CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL`](/en/env-vars) environment variable | `false` |

230| `editorMode` | Key binding mode for the input prompt: `"normal"` or `"vim"`. Default: `"normal"`. Appears in `/config` as **Editor mode** | `"vim"` |259| `externalEditorContext` | Prepend Claude's previous response as `#`-commented context when you open the external editor with `Ctrl+G`. Default: `false`. Appears in `/config` as **Show last response in external editor** | `true` |

231| `showTurnDuration` | Show turn duration messages after responses, e.g. "Cooked for 1m 6s". Default: `true`. Appears in `/config` as **Show turn duration** | `false` |

232| `terminalProgressBarEnabled` | Show the terminal progress bar in supported terminals: ConEmu, Ghostty 1.2.0+, and iTerm2 3.6.6+. Default: `true`. Appears in `/config` as **Terminal progress bar** | `false` |

233| `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 [choose a display mode](/en/agent-teams#choose-a-display-mode) | `"in-process"` |

234 260 

235### Worktree settings261### Worktree settings

236 262 

237Configure how `--worktree` creates and manages git worktrees. Use these settings to reduce disk usage and startup time in large monorepos.263Configure how `--worktree` creates and manages git worktrees.

238 264 

239| Key | Description | Example |265| Key | Description | Example |

240| :---------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |266| :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |

267| `worktree.baseRef` | Which ref new worktrees branch from. `"fresh"` (default) branches from `origin/<default-branch>` for a clean tree matching the remote. `"head"` branches from your current local `HEAD`, so unpushed commits and feature-branch state are present in the worktree. Applies to `--worktree`, the `EnterWorktree` tool, and subagent isolation | `"head"` |

241| `worktree.symlinkDirectories` | Directories to symlink from the main repository into each worktree to avoid duplicating large directories on disk. No directories are symlinked by default | `["node_modules", ".cache"]` |268| `worktree.symlinkDirectories` | Directories to symlink from the main repository into each worktree to avoid duplicating large directories on disk. No directories are symlinked by default | `["node_modules", ".cache"]` |

242| `worktree.sparsePaths` | Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos | `["packages/my-app", "shared/utils"]` |269| `worktree.sparsePaths` | Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos | `["packages/my-app", "shared/utils"]` |

243 270 

244To copy gitignored files like `.env` into new worktrees, use a [`.worktreeinclude` file](/en/common-workflows#copy-gitignored-files-to-worktrees) in your project root instead of a setting.271To copy gitignored files like `.env` into new worktrees, use a [`.worktreeinclude` file](/en/worktrees#copy-gitignored-files-into-worktrees) in your project root instead of a setting.

245 272 

246### Permission settings273### Permission settings

247 274 


275Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/sandboxing) for details.302Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/sandboxing) for details.

276 303 

277| Keys | Description | Example |304| Keys | Description | Example |

278| :------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ |305| :------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------- |

279| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |306| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |

280| `failIfUnavailable` | Exit with an error at startup if `sandbox.enabled` is true but the sandbox cannot start (missing dependencies, unsupported platform, or platform restrictions). When false (default), a warning is shown and commands run unsandboxed. Intended for managed settings deployments that require sandboxing as a hard gate | `true` |307| `failIfUnavailable` | Exit with an error at startup if `sandbox.enabled` is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed settings deployments that require sandboxing as a hard gate | `true` |

281| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |308| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |

282| `excludedCommands` | Commands that should run outside of the sandbox | `["docker *"]` |309| `excludedCommands` | Commands that should run outside of the sandbox | `["docker *"]` |

283| `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` |310| `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` |


286| `filesystem.denyRead` | Paths where sandboxed commands cannot read. Arrays are merged across all settings scopes. Also merged with paths from `Read(...)` deny permission rules. | `["~/.aws/credentials"]` |313| `filesystem.denyRead` | Paths where sandboxed commands cannot read. Arrays are merged across all settings scopes. Also merged with paths from `Read(...)` deny permission rules. | `["~/.aws/credentials"]` |

287| `filesystem.allowRead` | Paths to re-allow reading within `denyRead` regions. Takes precedence over `denyRead`. Arrays are merged across all settings scopes. Use this to create workspace-only read access patterns. | `["."]` |314| `filesystem.allowRead` | Paths to re-allow reading within `denyRead` regions. Takes precedence over `denyRead`. Arrays are merged across all settings scopes. Use this to create workspace-only read access patterns. | `["."]` |

288| `filesystem.allowManagedReadPathsOnly` | (Managed settings only) Only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources. Default: false | `true` |315| `filesystem.allowManagedReadPathsOnly` | (Managed settings only) Only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources. Default: false | `true` |

289| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |316| `network.allowUnixSockets` | (macOS only) Unix socket paths accessible in sandbox. Ignored on Linux and WSL2, where the seccomp filter cannot inspect socket paths; use `allowAllUnixSockets` instead. | `["~/.ssh/agent-socket"]` |

290| `network.allowAllUnixSockets` | Allow all Unix socket connections in sandbox. Default: false | `true` |317| `network.allowAllUnixSockets` | Allow all Unix socket connections in sandbox. On Linux and WSL2 this is the only way to permit Unix sockets, since it skips the seccomp filter that otherwise blocks `socket(AF_UNIX, ...)` calls. Default: false | `true` |

291| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |318| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |

292| `network.allowMachLookup` | Additional XPC/Mach service names the sandbox may look up (macOS only). Supports a single trailing `*` for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright. | `["com.apple.coresimulator.*"]` |319| `network.allowMachLookup` | Additional XPC/Mach service names the sandbox may look up (macOS only). Supports a single trailing `*` for prefix matching. Needed for tools that communicate via XPC such as the iOS Simulator or Playwright. | `["com.apple.coresimulator.*"]` |

293| `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` |320| `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` |

321| `network.deniedDomains` | Array of domains to block for outbound network traffic. Supports the same wildcard syntax as `allowedDomains`. Takes precedence over `allowedDomains` when both match. Merged from all settings sources regardless of `allowManagedDomainsOnly`. | `["sensitive.cloud.example.com"]` |

294| `network.allowManagedDomainsOnly` | (Managed settings only) Only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Domains from user, project, and local settings are ignored. Non-allowed domains are blocked automatically without prompting the user. Denied domains are still respected from all sources. Default: false | `true` |322| `network.allowManagedDomainsOnly` | (Managed settings only) Only `allowedDomains` and `WebFetch(domain:...)` allow rules from managed settings are respected. Domains from user, project, and local settings are ignored. Non-allowed domains are blocked automatically without prompting the user. Denied domains are still respected from all sources. Default: false | `true` |

295| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |323| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |

296| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |324| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |

297| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |325| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |

298| `enableWeakerNetworkIsolation` | (macOS only) Allow access to the system TLS trust service (`com.apple.trustd.agent`) in the sandbox. Required for Go-based tools like `gh`, `gcloud`, and `terraform` to verify TLS certificates when using `httpProxyPort` with a MITM proxy and custom CA. **Reduces security** by opening a potential data exfiltration path. Default: false | `true` |326| `enableWeakerNetworkIsolation` | (macOS only) Allow access to the system TLS trust service (`com.apple.trustd.agent`) in the sandbox. Required for Go-based tools like `gh`, `gcloud`, and `terraform` to verify TLS certificates when using `httpProxyPort` with a MITM proxy and custom CA. **Reduces security** by opening a potential data exfiltration path. Default: false | `true` |

327| `bwrapPath` | (Managed settings only, Linux/WSL2) Absolute path to the bubblewrap (`bwrap`) binary. Overrides automatic detection via `PATH`. Only honored from [managed settings](/en/settings#settings-precedence), not from user or project settings. Useful when `bwrap` is installed at a non-standard location in managed environments. | `/opt/admin/bwrap` |

328| `socatPath` | (Managed settings only, Linux/WSL2) Absolute path to the `socat` binary used for the sandbox network proxy. Overrides automatic detection via `PATH`. Only honored from managed settings. | `/opt/admin/socat` |

299 329 

300#### Sandbox path prefixes330#### Sandbox path prefixes

301 331 


323 },353 },

324 "network": {354 "network": {

325 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],355 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],

356 "deniedDomains": ["uploads.github.com"],

326 "allowUnixSockets": [357 "allowUnixSockets": [

327 "/var/run/docker.sock"358 "/var/run/docker.sock"

328 ],359 ],


425 456 

426**Restrict HTTP hook URLs:**457**Restrict HTTP hook URLs:**

427 458 

428Limit which URLs HTTP hooks can target. Supports `*` as a wildcard for matching. When the array is defined, HTTP hooks targeting non-matching URLs are silently blocked.459Limit which URLs HTTP hooks can target. Supports `*` as a wildcard for matching. When the array is defined, HTTP hooks targeting non-matching URLs are silently blocked. Hostname matching is case-insensitive and ignores a trailing FQDN dot, matching DNS semantics.

429 460 

430```json theme={null}461```json theme={null}

431{462{


443}474}

444```475```

445 476 

477### Compute managed settings with a policy helper

478 

479The `policyHelper` setting points at an executable that computes managed settings at startup, so admins can derive policy from device posture, identity, or a remote service instead of a static file. Configure it from MDM or a system `managed-settings.json` file. Claude Code ignores `policyHelper` when it appears in any other scope, including user settings, project settings, the HKCU registry hive, and [server-managed settings](/en/server-managed-settings).

480 

481The setting accepts these keys:

482 

483| Key | Type | Description |

484| ------------------- | ------ | ------------------------------------------------------------------------------------------------------- |

485| `path` | string | Absolute path to the helper executable |

486| `timeoutMs` | number | How long to wait for the helper before treating the run as failed |

487| `refreshIntervalMs` | number | How often to re-run the helper in the background. Set to `0` to disable refresh, or to at least `60000` |

488 

489The helper writes a JSON envelope to stdout. Put the settings under a `managedSettings` key rather than at the top level, since a bare settings object parses with `managedSettings` undefined and applies nothing:

490 

491```json theme={null}

492{

493 "managedSettings": {

494 "permissions": { "deny": ["Read(//etc/secrets/**)"] }

495 },

496 "claudeMd": "# Organization context\n...",

497 "appendSystemPrompt": "Always cite the internal style guide."

498}

499```

500 

501When the helper emits `managedSettings`, that object replaces the file-based managed settings for the run. When the helper exits non-zero at startup, Claude Code prints the error and refuses to start, so a helper that needs outage resilience should serve from its own cache and exit `0`.

502 

446### Settings precedence503### Settings precedence

447 504 

448Settings apply in order of precedence. From highest to lowest:505Settings apply in order of precedence. From highest to lowest:


453 * Within the managed tier, precedence is: server-managed > MDM/OS-level policies > file-based (`managed-settings.d/*.json` + `managed-settings.json`) > HKCU registry (Windows only). Only one managed source is used; sources do not merge across tiers. Within the file-based tier, drop-in files and the base file are merged together.510 * Within the managed tier, precedence is: server-managed > MDM/OS-level policies > file-based (`managed-settings.d/*.json` + `managed-settings.json`) > HKCU registry (Windows only). Only one managed source is used; sources do not merge across tiers. Within the file-based tier, drop-in files and the base file are merged together.

454 511 

4552. **Command line arguments**5122. **Command line arguments**

456 * Temporary overrides for a specific session513 * Temporary overrides for a specific session. JSON passed via `--settings <file-or-json>` merges with file-based settings using the same rules as the other layers: a key set here overrides the same key in local, project, or user settings, and omitting a key leaves the lower-layer value in place

457 514 

4583. **Local project settings** (`.claude/settings.local.json`)5153. **Local project settings** (`.claude/settings.local.json`)

459 * Personal project-specific settings516 * Personal project-specific settings


474 531 

475### Verify active settings532### Verify active settings

476 533 

477Run `/status` inside Claude Code to see which settings sources are active and where they come from. The output shows each configuration layer (managed, user, project) along with its origin, such as `Enterprise managed settings (remote)`, `Enterprise managed settings (plist)`, `Enterprise managed settings (HKLM)`, or `Enterprise managed settings (file)`. If a settings file contains errors, `/status` reports the issue so you can fix it.534Run `/status` inside Claude Code to see which settings sources are active and where they come from. The output shows each configuration layer (managed, user, project) along with its origin, such as `Enterprise managed settings (remote)`, `Enterprise managed settings (plist)`, `Enterprise managed settings (HKLM)`, `Enterprise managed settings (HKCU)`, or `Enterprise managed settings (file)`. If a settings file contains errors, `/status` reports the issue so you can fix it.

478 535 

479### Key points about the configuration system536### Key points about the configuration system

480 537 


535 },592 },

536 "extraKnownMarketplaces": {593 "extraKnownMarketplaces": {

537 "acme-tools": {594 "acme-tools": {

595 "source": {

538 "source": "github",596 "source": "github",

539 "repo": "acme-corp/claude-plugins"597 "repo": "acme-corp/claude-plugins"

540 }598 }

541 }599 }

600 }

542}601}

543```602```

544 603 


553* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)612* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)

554* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace613* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace

555 614 

615<Note>

616 Project settings take precedence over user settings, so setting a plugin to `false` in `~/.claude/settings.json` does not disable a plugin that the project's `.claude/settings.json` enables. To opt out of a project-enabled plugin on your machine, set it to `false` in `.claude/settings.local.json` instead.

617 

618 Plugins force-enabled by managed settings cannot be disabled this way, since managed settings override local settings.

619</Note>

620 

556**Example**:621**Example**:

557 622 

558```json theme={null}623```json theme={null}


631 696 

632#### `strictKnownMarketplaces`697#### `strictKnownMarketplaces`

633 698 

634**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [managed settings](/en/settings#settings-files) and provides administrators with strict control over marketplace sources.699**Managed settings only**: Controls which plugin marketplaces users are allowed to add and install plugins from. This setting can only be configured in [managed settings](/en/settings#settings-files) and provides administrators with strict control over marketplace sources.

635 700 

636**Managed settings file locations**:701**Managed settings file locations**:

637 702 


644* Only available in managed settings (`managed-settings.json`)709* Only available in managed settings (`managed-settings.json`)

645* Cannot be overridden by user or project settings (highest precedence)710* Cannot be overridden by user or project settings (highest precedence)

646* Enforced BEFORE network/filesystem operations (blocked sources never execute)711* Enforced BEFORE network/filesystem operations (blocked sources never execute)

647* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching712* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern` and `pathPattern`, which use regex matching

648 713 

649**Allowlist behavior**:714**Allowlist behavior**:

650 715 


654 719 

655**All supported source types**:720**All supported source types**:

656 721 

657The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host.722The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` and `pathPattern` use regex matching against the marketplace host and filesystem path respectively.

658 723 

6591. **GitHub repositories**:7241. **GitHub repositories**:

660 725 


734* `url`: extracts hostname from the URL799* `url`: extracts hostname from the URL

735* `npm`, `file`, `directory`: not supported for host pattern matching800* `npm`, `file`, `directory`: not supported for host pattern matching

736 801 

8028. **Path pattern matching**:

803 

804```json theme={null}

805{ "source": "pathPattern", "pathPattern": "^/opt/approved/" }

806{ "source": "pathPattern", "pathPattern": ".*" }

807```

808 

809Fields: `pathPattern` (required: regex pattern matched against the `path` field of `file` and `directory` sources)

810 

811Use path pattern matching to allow filesystem-based marketplaces alongside `hostPattern` restrictions for network sources. Set `".*"` to allow all local paths, or a narrower pattern to restrict to specific directories.

812 

737**Configuration examples**:813**Configuration examples**:

738 814 

739Example: allow specific marketplaces only:815Example: allow specific marketplaces only:


862 938 

863* Restrictions are checked BEFORE any network requests or filesystem operations939* Restrictions are checked BEFORE any network requests or filesystem operations

864* When blocked, users see clear error messages indicating the source is blocked by managed policy940* When blocked, users see clear error messages indicating the source is blocked by managed policy

865* The restriction applies only to adding NEW marketplaces; previously installed marketplaces remain accessible941* The restriction is enforced on marketplace add and on plugin install, update, refresh, and auto-update. A marketplace added before the policy was set cannot be used to install or update plugins once its source no longer matches the allowlist

866* Managed settings have the highest precedence and cannot be overridden942* Managed settings have the highest precedence and cannot be overridden

867 943 

868See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation.944See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation.


895 971 

896* [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies972* [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies

897* [Authentication](/en/authentication): set up user access to Claude Code973* [Authentication](/en/authentication): set up user access to Claude Code

898* [Troubleshooting](/en/troubleshooting): solutions for common configuration issues974* [Debug your configuration](/en/debug-your-config): diagnose why a setting, hook, or MCP server isn't taking effect

975* [Troubleshoot installation and login](/en/troubleshoot-install): installation, authentication, and platform issues

setup.md +133 −27

Details

20 * Alpine Linux 3.19+20 * Alpine Linux 3.19+

21* **Hardware**: 4 GB+ RAM, x64 or ARM64 processor21* **Hardware**: 4 GB+ RAM, x64 or ARM64 processor

22* **Network**: internet connection required. See [network configuration](/en/network-config#network-access-requirements).22* **Network**: internet connection required. See [network configuration](/en/network-config#network-access-requirements).

23* **Shell**: Bash, Zsh, PowerShell, or CMD. Native Windows setups require [Git for Windows](https://git-scm.com/downloads/win). WSL setups do not.23* **Shell**: Bash, Zsh, PowerShell, or CMD. On native Windows, [Git for Windows](https://git-scm.com/downloads/win) is recommended; Claude Code falls back to PowerShell when Git Bash is absent. WSL setups do not require Git for Windows.

24* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)24* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)

25 25 

26### Additional dependencies26### Additional dependencies


59 59 

60 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.60 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. If you see `'irm' is not recognized as an internal or external command`, you're in CMD, not PowerShell. Your prompt shows `PS C:\` when you're in PowerShell and `C:\` without the `PS` when you're in CMD.

61 61 

62 **Native Windows setups require [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it. WSL setups do not need it.62 [Git for Windows](https://git-scm.com/downloads/win) is recommended on native Windows so Claude Code can use the Bash tool. If Git for Windows is not installed, Claude Code uses PowerShell as the shell tool instead. WSL setups do not need Git for Windows.

63 63 

64 <Info>64 <Info>

65 Native installations automatically update in the background to keep you on the latest version.65 Native installations automatically update in the background to keep you on the latest version.


89 </Tab>89 </Tab>

90</Tabs>90</Tabs>

91 91 

92You can also install with [apt, dnf, or apk](/en/setup#install-with-linux-package-managers) on Debian, Fedora, RHEL, and Alpine.

93 

92After installation completes, open a terminal in the project you want to work in and start Claude Code:94After installation completes, open a terminal in the project you want to work in and start Claude Code:

93 95 

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

95claude97claude

96```98```

97 99 

98If you encounter any issues during installation, see the [troubleshooting guide](/en/troubleshooting).100If you encounter any issues during installation, see [Troubleshoot installation and login](/en/troubleshoot-install).

99 101 

100### Set up on Windows102### Set up on Windows

101 103 

102You can run Claude Code natively on Windows or inside WSL. Pick based on where your projects are located and which features you need:104You can run Claude Code natively on Windows or inside WSL. Pick based on where your projects are located and which features you need:

103 105 

104| Option | Requires | [Sandboxing](/en/sandboxing) | When to use |106| Option | Requires | [Sandboxing](/en/sandboxing) | When to use |

105| -------------- | ---------------------------------------------------- | ---------------------------- | ----------------------------------------------- |107| -------------- | ------------------------------------------------------------------------------------------- | ---------------------------- | ----------------------------------------------- |

106| Native Windows | [Git for Windows](https://git-scm.com/downloads/win) | Not supported | Windows-native projects and tools |108| Native Windows | [Git for Windows](https://git-scm.com/downloads/win) recommended; PowerShell used if absent | Not supported | Windows-native projects and tools |

107| WSL 2 | WSL 2 enabled | Supported | Linux toolchains or sandboxed command execution |109| WSL 2 | WSL 2 enabled | Supported | Linux toolchains or sandboxed command execution |

108| WSL 1 | WSL 1 enabled | Not supported | If WSL 2 is unavailable |110| WSL 1 | WSL 1 enabled | Not supported | If WSL 2 is unavailable |

109 111 


113 115 

114Whether you install from PowerShell or CMD only affects which install command you run. Your prompt shows `PS C:\Users\YourName>` in PowerShell and `C:\Users\YourName>` without the `PS` in CMD. If you're new to the terminal, the [terminal guide](/en/terminal-guide#windows) walks through each step.116Whether you install from PowerShell or CMD only affects which install command you run. Your prompt shows `PS C:\Users\YourName>` in PowerShell and `C:\Users\YourName>` without the `PS` in CMD. If you're new to the terminal, the [terminal guide](/en/terminal-guide#windows) walks through each step.

115 117 

116After installation, launch `claude` from PowerShell, CMD, or Git Bash. Claude Code uses Git Bash internally to execute commands regardless of where you launched it. If Claude Code can't find your Git Bash installation, set the path in your [settings.json file](/en/settings):118After installation, launch `claude` from PowerShell, CMD, or Git Bash. When Git Bash is installed, Claude Code uses it internally to execute commands regardless of where you launched it. If Claude Code can't find your Git Bash installation, set the path in your [settings.json file](/en/settings):

117 119 

118```json theme={null}120```json theme={null}

119{121{


123}125}

124```126```

125 127 

126Claude Code can also run PowerShell natively on Windows as an opt-in preview. See [PowerShell tool](/en/tools-reference#powershell-tool) for setup and limitations.128Claude Code can also run PowerShell natively on Windows. When Git Bash is installed, the PowerShell tool is rolling out progressively as an additional option: set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` to opt in or `0` to opt out. See [PowerShell tool](/en/tools-reference#powershell-tool) for setup and limitations.

127 129 

128**Option 2: WSL**130**Option 2: WSL**

129 131 


157claude --version159claude --version

158```160```

159 161 

162If this fails with `command not found` or another error, see [Troubleshoot installation and login](/en/troubleshoot-install).

163 

160For a more detailed check of your installation and configuration, run [`claude doctor`](/en/troubleshooting#get-more-help):164For a more detailed check of your installation and configuration, run [`claude doctor`](/en/troubleshooting#get-more-help):

161 165 

162```bash theme={null}166```bash theme={null}


171 175 

172## Update Claude Code176## Update Claude Code

173 177 

174Native installations automatically update in the background. You can [configure the release channel](#configure-release-channel) to control whether you receive updates immediately or on a delayed stable schedule, or [disable auto-updates](#disable-auto-updates) entirely. Homebrew and WinGet installations require manual updates.178Native installations automatically update in the background. You can [configure the release channel](#configure-release-channel) to control whether you receive updates immediately or on a delayed stable schedule, or [disable auto-updates](#disable-auto-updates) entirely. Homebrew, WinGet, and [Linux package manager](#install-with-linux-package-managers) installations require manual updates by default.

175 179 

176### Auto-updates180### Auto-updates

177 181 

178Claude Code checks for updates on startup and periodically while running. Updates download and install in the background, then take effect the next time you start Claude Code.182Claude Code checks for updates on startup and periodically while running. Updates download and install in the background, then take effect the next time you start Claude Code.

179 183 

180<Note>184<Note>

181 Homebrew and WinGet installations do not auto-update. For Homebrew, run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed. For WinGet, run `winget upgrade Anthropic.ClaudeCode`.185 Homebrew, WinGet, apt, dnf, and apk installations do not auto-update by default; see below to opt in for Homebrew and WinGet. To upgrade Homebrew manually, run `brew upgrade claude-code` or `brew upgrade claude-code@latest`, depending on which cask you installed. For WinGet, run `winget upgrade Anthropic.ClaudeCode`. For Linux package managers, see the upgrade commands in [Install with Linux package managers](#install-with-linux-package-managers).

186 

187 To have Claude Code run the upgrade command for you on Homebrew or WinGet, set [`CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE`](/en/env-vars) to `1`. Claude Code then runs the upgrade in the background when a new version is available and shows a restart prompt on success. The upgrade targets only the Claude Code package and does not affect other software you have installed.

188 

189 On WinGet the upgrade may fail while Claude Code is running because Windows locks the executable. In that case Claude Code shows the manual command instead. apt, dnf, and apk continue to require a manual upgrade because those commands need elevated privileges.

182 190 

183 **Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.191 **Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.

184 192 


204 212 

205Homebrew installations choose a channel by cask name instead of this setting: `claude-code` tracks stable and `claude-code@latest` tracks latest.213Homebrew installations choose a channel by cask name instead of this setting: `claude-code` tracks stable and `claude-code@latest` tracks latest.

206 214 

215### Pin a minimum version

216 

217The `minimumVersion` setting establishes a floor. Background auto-updates and `claude update` refuse to install any version below this value, so moving to the `"stable"` channel does not downgrade you if you are already on a newer `"latest"` build.

218 

219Switching from `"latest"` to `"stable"` via `/config` prompts you to either stay on the current version or allow the downgrade. Choosing to stay sets `minimumVersion` to that version. Switching back to `"latest"` clears it.

220 

221Add it to your [settings.json file](/en/settings) to pin a floor explicitly:

222 

223```json theme={null}

224{

225 "autoUpdatesChannel": "stable",

226 "minimumVersion": "2.1.100"

227}

228```

229 

230In [managed settings](/en/permissions#managed-settings), this enforces an organization-wide minimum that user and project settings cannot override.

231 

207### Disable auto-updates232### Disable auto-updates

208 233 

209Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](/en/settings#available-settings) file:234Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](/en/settings#available-settings) file:


216}241}

217```242```

218 243 

244`DISABLE_AUTOUPDATER` only stops the background check; `claude update` and `claude install` still work. To block all update paths, including manual updates, set [`DISABLE_UPDATES`](/en/env-vars) instead. Use this when you distribute Claude Code through your own channels and need users to stay on the version you provide.

245 

219### Update manually246### Update manually

220 247 

221To apply an update immediately without waiting for the next background check, run:248To apply an update immediately without waiting for the next background check, run:


226 253 

227## Advanced installation options254## Advanced installation options

228 255 

229These options are for version pinning, migrating from npm, and verifying binary integrity.256These options are for version pinning, Linux package managers, npm, and verifying binary integrity.

230 257 

231### Install a specific version258### Install a specific version

232 259 


298 </Tab>325 </Tab>

299</Tabs>326</Tabs>

300 327 

301### Deprecated npm installation328### Install with Linux package managers

302 329 

303npm installation is deprecated. The native installer is faster, requires no dependencies, and auto-updates in the background. Use the [native installation](#install-claude-code) method when possible.330Claude Code publishes signed apt, dnf, and apk repositories. Replace `stable` with `latest` for the rolling channel. Package manager installations do not auto-update through Claude Code; updates arrive through your normal system upgrade workflow.

304 331 

305#### Migrate from npm to native332All repositories are signed with the [Claude Code release signing key](#binary-integrity-and-code-signing). Before trusting the key, verify it as described in each tab.

306 333 

307If you previously installed Claude Code with npm, switch to the native installer:334<Tabs>

335 <Tab title="apt">

336 For Debian and Ubuntu. To use the rolling channel, change both `stable` occurrences in the `deb` line: the URL path and the suite name.

308 337 

309```bash theme={null}338 ```bash theme={null}

310# Install the native binary339 sudo install -d -m 0755 /etc/apt/keyrings

311curl -fsSL https://claude.ai/install.sh | bash340 sudo curl -fsSL https://downloads.claude.ai/keys/claude-code.asc \

341 -o /etc/apt/keyrings/claude-code.asc

342 echo "deb [signed-by=/etc/apt/keyrings/claude-code.asc] https://downloads.claude.ai/claude-code/apt/stable stable main" \

343 | sudo tee /etc/apt/sources.list.d/claude-code.list

344 sudo apt update

345 sudo apt install claude-code

346 ```

312 347 

313# Remove the old npm installation348 Verify the GPG key fingerprint before trusting it: `gpg --show-keys /etc/apt/keyrings/claude-code.asc` should report `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE`.

314npm uninstall -g @anthropic-ai/claude-code

315```

316 349 

317You can also run `claude install` from an existing npm installation to install the native binary alongside it, then remove the npm version.350 To upgrade later, run `sudo apt update && sudo apt upgrade claude-code`.

351 </Tab>

352 

353 <Tab title="dnf">

354 For Fedora and RHEL:

318 355 

319#### Install with npm356 ```bash theme={null}

357 sudo tee /etc/yum.repos.d/claude-code.repo <<'EOF'

358 [claude-code]

359 name=Claude Code

360 baseurl=https://downloads.claude.ai/claude-code/rpm/stable

361 enabled=1

362 gpgcheck=1

363 gpgkey=https://downloads.claude.ai/keys/claude-code.asc

364 EOF

365 sudo dnf install claude-code

366 ```

367 

368 dnf downloads the key on first install and prompts you to confirm the fingerprint. Verify it matches `31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE` before accepting.

369 

370 To upgrade later, run `sudo dnf upgrade claude-code`.

371 </Tab>

320 372 

321If you need npm installation for compatibility reasons, you must have [Node.js 18+](https://nodejs.org/en/download) installed. Install the package globally:373 <Tab title="apk">

374 For Alpine Linux:

375 

376 ```sh theme={null}

377 wget -O /etc/apk/keys/claude-code.rsa.pub \

378 https://downloads.claude.ai/keys/claude-code.rsa.pub

379 echo "https://downloads.claude.ai/claude-code/apk/stable" >> /etc/apk/repositories

380 apk add claude-code

381 ```

382 

383 Verify the downloaded key with `sha256sum /etc/apk/keys/claude-code.rsa.pub`, which should report `395759c1f7449ef4cdef305a42e820f3c766d6090d142634ebdb049f113168b6`.

384 

385 To upgrade later, run `apk update && apk upgrade claude-code`.

386 </Tab>

387</Tabs>

388 

389### Install with npm

390 

391You can also install Claude Code as a global npm package. The package requires [Node.js 18 or later](https://nodejs.org/en/download).

322 392 

323```bash theme={null}393```bash theme={null}

324npm install -g @anthropic-ai/claude-code394npm install -g @anthropic-ai/claude-code

325```395```

326 396 

397The npm package installs the same native binary as the standalone installer. npm pulls the binary in through a per-platform optional dependency such as `@anthropic-ai/claude-code-darwin-arm64`, and a postinstall step links it into place. The installed `claude` binary does not itself invoke Node.

398 

399Supported npm install platforms are `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `linux-x64-musl`, `linux-arm64-musl`, `win32-x64`, and `win32-arm64`. Your package manager must allow optional dependencies. See [troubleshooting](/en/troubleshoot-install#native-binary-not-found-after-npm-install) if the binary is missing after install.

400 

401To upgrade an npm installation, run `npm install -g @anthropic-ai/claude-code@latest`. Avoid `npm update -g`, which respects the semver range from the original install and may not move you to the newest release.

402 

327<Warning>403<Warning>

328 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshooting#permission-errors-during-installation).404 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks. If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshoot-install#permission-errors-during-installation).

329</Warning>405</Warning>

330 406 

331### Binary integrity and code signing407### Binary integrity and code signing


361 Set `VERSION` to the release you want to verify.437 Set `VERSION` to the release you want to verify.

362 438 

363 ```bash theme={null}439 ```bash theme={null}

364 REPO=https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases440 REPO=https://downloads.claude.ai/claude-code-releases

365 VERSION=2.1.89441 VERSION=2.1.89

366 curl -fsSLO "$REPO/$VERSION/manifest.json"442 curl -fsSLO "$REPO/$VERSION/manifest.json"

367 curl -fsSLO "$REPO/$VERSION/manifest.json.sig"443 curl -fsSLO "$REPO/$VERSION/manifest.json.sig"


415 491 

416* **macOS**: signed by "Anthropic PBC" and notarized by Apple. Verify with `codesign --verify --verbose ./claude`.492* **macOS**: signed by "Anthropic PBC" and notarized by Apple. Verify with `codesign --verify --verbose ./claude`.

417* **Windows**: signed by "Anthropic, PBC". Verify with `Get-AuthenticodeSignature .\claude.exe`.493* **Windows**: signed by "Anthropic, PBC". Verify with `Get-AuthenticodeSignature .\claude.exe`.

418* **Linux**: use the manifest signature above to verify integrity. Linux binaries are not individually code-signed.494* **Linux**: binaries are not individually code-signed. If you download directly from the `claude-code-releases` bucket or use the native installer, verify integrity with the manifest signature above. If you install with [apt, dnf, or apk](#install-with-linux-package-managers), your package manager verifies signatures automatically using the repository signing key.

419 495 

420## Uninstall Claude Code496## Uninstall Claude Code

421 497 

422To remove Claude Code, follow the instructions for your installation method.498To remove Claude Code, follow the instructions for your installation method. If `claude` still runs afterward, you likely have a second installation or a leftover shell alias from an older installer. See [Check for conflicting installations](/en/troubleshoot-install#check-for-conflicting-installations) to find and remove it.

423 499 

424### Native installation500### Native installation

425 501 


463winget uninstall Anthropic.ClaudeCode539winget uninstall Anthropic.ClaudeCode

464```540```

465 541 

542### apt / dnf / apk

543 

544Remove the package and the repository configuration:

545 

546<Tabs>

547 <Tab title="apt">

548 ```bash theme={null}

549 sudo apt remove claude-code

550 sudo rm /etc/apt/sources.list.d/claude-code.list /etc/apt/keyrings/claude-code.asc

551 ```

552 </Tab>

553 

554 <Tab title="dnf">

555 ```bash theme={null}

556 sudo dnf remove claude-code

557 sudo rm /etc/yum.repos.d/claude-code.repo

558 ```

559 </Tab>

560 

561 <Tab title="apk">

562 ```sh theme={null}

563 apk del claude-code

564 sed -i '\|downloads.claude.ai/claude-code/apk|d' /etc/apk/repositories

565 rm /etc/apk/keys/claude-code.rsa.pub

566 ```

567 </Tab>

568</Tabs>

569 

466### npm570### npm

467 571 

468Remove the global npm package:572Remove the global npm package:


477 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.581 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.

478</Warning>582</Warning>

479 583 

584The VS Code extension, the JetBrains plugin, and the Desktop app also write to `~/.claude/`. If any of them is still installed, the directory is recreated the next time it runs. To remove Claude Code completely, uninstall the [VS Code extension](/en/vs-code#uninstall-the-extension), the JetBrains plugin, and the Desktop app before deleting these files.

585 

480To remove Claude Code settings and cached data:586To remove Claude Code settings and cached data:

481 587 

482<Tabs>588<Tabs>

skills.md +72 −36

Details

8 8 

9Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `/skill-name`.9Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `/skill-name`.

10 10 

11Create a skill when you keep pasting the same playbook, checklist, or multi-step procedure into chat, or when a section of CLAUDE.md has grown into a procedure rather than a fact. Unlike CLAUDE.md content, a skill's body loads only when it's used, so long reference material costs almost nothing until you need it.11Create a skill when you keep pasting the same instructions, checklist, or multi-step procedure into chat, or when a section of CLAUDE.md has grown into a procedure rather than a fact. Unlike CLAUDE.md content, a skill's body loads only when it's used, so long reference material costs almost nothing until you need it.

12 12 

13<Note>13<Note>

14 For built-in commands like `/help` and `/compact`, and bundled skills like `/debug` and `/simplify`, see the [commands reference](/en/commands).14 For built-in commands like `/help` and `/compact`, and bundled skills like `/debug` and `/simplify`, see the [commands reference](/en/commands).


20 20 

21## Bundled skills21## Bundled skills

22 22 

23Claude Code includes a set of bundled skills that are available in every session, including `/simplify`, `/batch`, `/debug`, `/loop`, and `/claude-api`. Unlike built-in commands, which execute fixed logic directly, bundled skills are prompt-based: they give Claude a detailed playbook and let it orchestrate the work using its tools. You invoke them the same way as any other skill, by typing `/` followed by the skill name.23Claude Code includes a set of bundled skills that are available in every session, including `/simplify`, `/batch`, `/debug`, `/loop`, and `/claude-api`. Unlike most built-in commands, which execute fixed logic directly, bundled skills are prompt-based: they give Claude detailed instructions and let it orchestrate the work using its tools. You invoke them the same way as any other skill, by typing `/` followed by the skill name.

24 24 

25Bundled skills are listed alongside built-in commands in the [commands reference](/en/commands), marked **Skill** in the Purpose column.25Bundled skills are listed alongside built-in commands in the [commands reference](/en/commands), marked **Skill** in the Purpose column.

26 26 


28 28 

29### Create your first skill29### Create your first skill

30 30 

31This example creates a skill that teaches Claude to explain code using visual diagrams and analogies. Since it uses default frontmatter, Claude can load it automatically when you ask how something works, or you can invoke it directly with `/explain-code`.31This example creates a skill that summarizes the uncommitted changes in your git repository and flags anything risky. It pulls the live diff into the prompt before Claude reads it, so the response is grounded in your actual working tree rather than what Claude can guess from open files. Claude loads the skill automatically when you ask about your changes, or you can invoke it directly with `/summarize-changes`.

32 32 

33<Steps>33<Steps>

34 <Step title="Create the skill directory">34 <Step title="Create the skill directory">

35 Create a directory for the skill in your personal skills folder. Personal skills are available across all your projects.35 Create a directory for the skill in your personal skills folder. Personal skills are available across all your projects.

36 36 

37 ```bash theme={null}37 ```bash theme={null}

38 mkdir -p ~/.claude/skills/explain-code38 mkdir -p ~/.claude/skills/summarize-changes

39 ```39 ```

40 </Step>40 </Step>

41 41 

42 <Step title="Write SKILL.md">42 <Step title="Write SKILL.md">

43 Every skill needs a `SKILL.md` file with two parts: YAML frontmatter (between `---` markers) that tells Claude when to use the skill, and markdown content with instructions Claude follows when the skill is invoked. The `name` field becomes the `/slash-command`, and the `description` helps Claude decide when to load it automatically.43 Every skill needs a `SKILL.md` file with two parts: YAML frontmatter between `---` markers that tells Claude when to use the skill, and markdown content with the instructions Claude follows when the skill runs. The directory name becomes the command you type, and the `description` helps Claude decide when to load the skill automatically.

44 44 

45 Create `~/.claude/skills/explain-code/SKILL.md`:45 Save this to `~/.claude/skills/summarize-changes/SKILL.md`:

46 46 

47 ```yaml theme={null}47 ```yaml theme={null}

48 ---48 ---

49 name: explain-code49 description: Summarizes uncommitted changes and flags anything risky. Use when the user asks what changed, wants a commit message, or asks to review their diff.

50 description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"

51 ---50 ---

52 51 

53 When explaining code, always include:52 ## Current changes

54 53 

55 1. **Start with an analogy**: Compare the code to something from everyday life54 !`git diff HEAD`

56 2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships

57 3. **Walk through the code**: Explain step-by-step what happens

58 4. **Highlight a gotcha**: What's a common mistake or misconception?

59 55 

60 Keep explanations conversational. For complex concepts, use multiple analogies.56 ## Instructions

57 

58 Summarize the changes above in two or three bullet points, then list any risks you notice such as missing error handling, hardcoded values, or tests that need updating. If the diff is empty, say there are no uncommitted changes.

61 ```59 ```

60 

61 The `` !`git diff HEAD` `` line uses [dynamic context injection](#inject-dynamic-context): Claude Code runs the command and replaces the line with its output before Claude sees the skill content, so the instructions arrive with the current diff already inlined.

62 </Step>62 </Step>

63 63 

64 <Step title="Test the skill">64 <Step title="Test the skill">

65 You can test it two ways:65 Open a git project, make a small edit to any file, and start Claude Code by running `claude`. You can test the skill two ways.

66 66 

67 **Let Claude invoke it automatically** by asking something that matches the description:67 **Let Claude invoke it automatically** by asking something that matches the description:

68 68 

69 ```text theme={null}69 ```text theme={null}

70 How does this code work?70 What did I change?

71 ```71 ```

72 72 

73 **Or invoke it directly** with the skill name:73 **Or invoke it directly** with the skill name:

74 74 

75 ```text theme={null}75 ```text theme={null}

76 /explain-code src/auth/login.ts76 /summarize-changes

77 ```77 ```

78 78 

79 Either way, Claude should include an analogy and ASCII diagram in its explanation.79 Either way, Claude should respond with a short summary of your edit and a list of risks.

80 </Step>80 </Step>

81</Steps>81</Steps>

82 82 


91| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |91| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |

92| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |92| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |

93 93 

94When 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.94When skills share the same name across levels, enterprise overrides personal, and personal overrides 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.

95 95 

96#### Live change detection96#### Live change detection

97 97 


169 169 

170Your `SKILL.md` can contain anything, but thinking through how you want the skill invoked (by you, by Claude, or both) and where you want it to run (inline or in a subagent) helps guide what to include. For complex skills, you can also [add supporting files](#add-supporting-files) to keep the main skill focused.170Your `SKILL.md` can contain anything, but thinking through how you want the skill invoked (by you, by Claude, or both) and where you want it to run (inline or in a subagent) helps guide what to include. For complex skills, you can also [add supporting files](#add-supporting-files) to keep the main skill focused.

171 171 

172Keep the body itself concise. Once a skill loads, its content [stays in context across turns](#skill-content-lifecycle), so every line is a recurring token cost. State what to do rather than narrating how or why, and apply the same conciseness test you would for [CLAUDE.md content](/en/best-practices#write-an-effective-claude-md).

173 

172### Frontmatter reference174### Frontmatter reference

173 175 

174Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:176Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:


187All fields are optional. Only `description` is recommended so Claude knows when to use the skill.189All fields are optional. Only `description` is recommended so Claude knows when to use the skill.

188 190 

189| Field | Required | Description |191| Field | Required | Description |

190| :------------------------- | :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |192| :------------------------- | :---------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

191| `name` | No | Display name for the skill. If omitted, uses the directory name. Lowercase letters, numbers, and hyphens only (max 64 characters). |193| `name` | No | Display name for the skill. If omitted, uses the directory name. Lowercase letters, numbers, and hyphens only (max 64 characters). |

192| `description` | Recommended | What the skill does and when to use it. Claude uses this to decide when to apply the skill. If omitted, uses the first paragraph of markdown content. Front-load the key use case: the combined `description` and `when_to_use` text is truncated at 1,536 characters in the skill listing to reduce context usage. |194| `description` | Recommended | What the skill does and when to use it. Claude uses this to decide when to apply the skill. If omitted, uses the first paragraph of markdown content. Put the key use case first: the combined `description` and `when_to_use` text is truncated at 1,536 characters in the skill listing to reduce context usage. |

193| `when_to_use` | No | Additional context for when Claude should invoke the skill, such as trigger phrases or example requests. Appended to `description` in the skill listing and counts toward the 1,536-character cap. |195| `when_to_use` | No | Additional context for when Claude should invoke the skill, such as trigger phrases or example requests. Appended to `description` in the skill listing and counts toward the 1,536-character cap. |

194| `argument-hint` | No | Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. |196| `argument-hint` | No | Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. |

195| `disable-model-invocation` | No | Set to `true` to prevent Claude from automatically loading this skill. Use for workflows you want to trigger manually with `/name`. Default: `false`. |197| `arguments` | No | Named positional arguments for [`$name` substitution](#available-string-substitutions) in the skill content. Accepts a space-separated string or a YAML list. Names map to argument positions in order. |

198| `disable-model-invocation` | No | Set to `true` to prevent Claude from automatically loading this skill. Use for workflows you want to trigger manually with `/name`. Also prevents the skill from being [preloaded into subagents](/en/sub-agents#preload-skills-into-subagents). Default: `false`. |

196| `user-invocable` | No | Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn't invoke directly. Default: `true`. |199| `user-invocable` | No | Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn't invoke directly. Default: `true`. |

197| `allowed-tools` | No | Tools Claude can use without asking permission when this skill is active. Accepts a space-separated string or a YAML list. |200| `allowed-tools` | No | Tools Claude can use without asking permission when this skill is active. Accepts a space-separated string or a YAML list. |

198| `model` | No | Model to use when this skill is active. |201| `model` | No | Model to use when this skill is active. The override applies for the rest of the current turn and is not saved to settings; the session model resumes on your next prompt. Accepts the same values as [`/model`](/en/model-config), or `inherit` to keep the active model. |

199| `effort` | No | [Effort level](/en/model-config#adjust-effort-level) when this skill is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `max` (Opus 4.6 only). |202| `effort` | No | [Effort level](/en/model-config#adjust-effort-level) when this skill is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. |

200| `context` | No | Set to `fork` to run in a forked subagent context. |203| `context` | No | Set to `fork` to run in a forked subagent context. |

201| `agent` | No | Which subagent type to use when `context: fork` is set. |204| `agent` | No | Which subagent type to use when `context: fork` is set. |

202| `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. |205| `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. |


212| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |215| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |

213| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |216| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |

214| `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. |217| `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. |

218| `$name` | Named argument declared in the [`arguments`](#frontmatter-reference) frontmatter list. Names map to positions in order, so with `arguments: [issue, branch]` the placeholder `$issue` expands to the first argument and `$branch` to the second. |

215| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |219| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |

220| `${CLAUDE_EFFORT}` | The current effort level: `low`, `medium`, `high`, `xhigh`, or `max`. Use this to adapt skill instructions to the active effort setting. |

216| `${CLAUDE_SKILL_DIR}` | The directory containing the skill's `SKILL.md` file. For plugin skills, this is the skill's subdirectory within the plugin, not the plugin root. Use this in bash injection commands to reference scripts or files bundled with the skill, regardless of the current working directory. |221| `${CLAUDE_SKILL_DIR}` | The directory containing the skill's `SKILL.md` file. For plugin skills, this is the skill's subdirectory within the plugin, not the plugin root. Use this in bash injection commands to reference scripts or files bundled with the skill, regardless of the current working directory. |

217 222 

218Indexed arguments use shell-style quoting, so wrap multi-word values in quotes to pass them as a single argument. For example, `/my-skill "hello world" second` makes `$0` expand to `hello world` and `$1` to `second`. The `$ARGUMENTS` placeholder always expands to the full argument string as typed.223Indexed arguments use shell-style quoting, so wrap multi-word values in quotes to pass them as a single argument. For example, `/my-skill "hello world" second` makes `$0` expand to `hello world` and `$1` to `second`. The `$ARGUMENTS` placeholder always expands to the full argument string as typed.


303 308 

304The `allowed-tools` field grants permission for the listed tools while the skill is active, so Claude can use them without prompting you for approval. It does not restrict which tools are available: every tool remains callable, and your [permission settings](/en/permissions) still govern tools that are not listed.309The `allowed-tools` field grants permission for the listed tools while the skill is active, so Claude can use them without prompting you for approval. It does not restrict which tools are available: every tool remains callable, and your [permission settings](/en/permissions) still govern tools that are not listed.

305 310 

311For skills checked into a project's `.claude/skills/` directory, `allowed-tools` takes effect after you accept the workspace trust dialog for that folder, the same as permission rules in `.claude/settings.json`. Review project skills before trusting a repository, since a skill can grant itself broad tool access.

312 

306This skill lets Claude run git commands without per-use approval whenever you invoke it:313This skill lets Claude run git commands without per-use approval whenever you invoke it:

307 314 

308```yaml theme={null}315```yaml theme={null}


414To disable this behavior for skills and custom commands from user, project, plugin, or [additional-directory](#skills-from-additional-directories) sources, set `"disableSkillShellExecution": true` in [settings](/en/settings). Each command is replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. This setting is most useful in [managed settings](/en/permissions#managed-settings), where users cannot override it.421To disable this behavior for skills and custom commands from user, project, plugin, or [additional-directory](#skills-from-additional-directories) sources, set `"disableSkillShellExecution": true` in [settings](/en/settings). Each command is replaced with `[shell command execution disabled by policy]` instead of being run. Bundled and managed skills are not affected. This setting is most useful in [managed settings](/en/permissions#managed-settings), where users cannot override it.

415 422 

416<Tip>423<Tip>

417 To enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) in a skill, include the word "ultrathink" anywhere in your skill content.424 To request deeper reasoning when a skill runs, include `ultrathink` anywhere in the skill content. See [Use ultrathink for one-off deep reasoning](/en/model-config#use-ultrathink-for-one-off-deep-reasoning).

418</Tip>425</Tip>

419 426 

420### Run skills in a subagent427### Run skills in a subagent


464 471 

465### Restrict Claude's skill access472### Restrict Claude's skill access

466 473 

467By 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.474By 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. A few built-in commands are also available through the Skill tool, including `/init`, `/review`, and `/security-review`. Other built-in commands such as `/compact` are not.

468 475 

469Three ways to control which skills Claude can invoke:476Three ways to control which skills Claude can invoke:

470 477 


494 The `user-invocable` field only controls menu visibility, not Skill tool access. Use `disable-model-invocation: true` to block programmatic invocation.501 The `user-invocable` field only controls menu visibility, not Skill tool access. Use `disable-model-invocation: true` to block programmatic invocation.

495</Note>502</Note>

496 503 

504### Override skill visibility from settings

505 

506The `skillOverrides` setting controls skill visibility from your [settings](/en/settings) instead of the skill's own frontmatter. Use it for skills whose SKILL.md you don't want to edit, such as ones checked into a shared project repo or provided by an MCP server. The `/skills` menu writes it for you: highlight a skill and press `Space` to cycle states, then `Enter` to save to `.claude/settings.local.json`.

507 

508Each key is a skill name and each value is one of four states:

509 

510| Value | Listed to Claude | In `/` menu |

511| :---------------------- | :------------------- | :---------- |

512| `"on"` | Name and description | Yes |

513| `"name-only"` | Name only | Yes |

514| `"user-invocable-only"` | Hidden | Yes |

515| `"off"` | Hidden | Hidden |

516 

517A skill that is absent from `skillOverrides` is treated as `"on"`. The example below collapses one skill to its name and turns another off entirely:

518 

519```json theme={null}

520{

521 "skillOverrides": {

522 "legacy-context": "name-only",

523 "deploy": "off"

524 }

525}

526```

527 

528Plugin skills are not affected by `skillOverrides`. Manage those through `/plugin` instead.

529 

497## Share skills530## Share skills

498 531 

499Skills can be distributed at different scopes depending on your audience:532Skills can be distributed at different scopes depending on your audience:


514mkdir -p ~/.claude/skills/codebase-visualizer/scripts547mkdir -p ~/.claude/skills/codebase-visualizer/scripts

515```548```

516 549 

517Create `~/.claude/skills/codebase-visualizer/SKILL.md`. The description tells Claude when to activate this Skill, and the instructions tell Claude to run the bundled script:550Save this to `~/.claude/skills/codebase-visualizer/SKILL.md`. The description tells Claude when to activate this Skill, and the instructions tell Claude to run the bundled script. The script path uses [`${CLAUDE_SKILL_DIR}`](#available-string-substitutions) so it resolves correctly whether the skill is installed at the personal, project, or plugin level:

518 551 

519````yaml theme={null}552````yaml theme={null}

520---553---

521name: codebase-visualizer554name: codebase-visualizer

522description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.555description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.

523allowed-tools: Bash(python *)556allowed-tools: Bash(python3 *)

524---557---

525 558 

526# Codebase Visualizer559# Codebase Visualizer


532Run the visualization script from your project root:565Run the visualization script from your project root:

533 566 

534```bash567```bash

535python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .568python3 ${CLAUDE_SKILL_DIR}/scripts/visualize.py .

536```569```

537 570 

538This creates `codebase-map.html` in the current directory and opens it in your default browser.571This creates `codebase-map.html` in the current directory and opens it in your default browser.


545- **Directory totals**: Shows aggregate size of each folder578- **Directory totals**: Shows aggregate size of each folder

546````579````

547 580 

548Create `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with:581Save this to `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with:

549 582 

550* A **summary sidebar** showing file count, directory count, total size, and number of file types583* A **summary sidebar** showing file count, directory count, total size, and number of file types

551* A **bar chart** breaking down the codebase by file type (top 8 by size)584* A **bar chart** breaking down the codebase by file type (top 8 by size)

552* A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators585* A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators

553 586 

554The script requires Python but uses only built-in libraries, so there are no packages to install:587The script requires Python 3 but uses only built-in libraries, so there are no packages to install:

555 588 

556```python expandable theme={null}589```python expandable theme={null}

557#!/usr/bin/env python3590#!/usr/bin/env python3


560import json593import json

561import sys594import sys

562import webbrowser595import webbrowser

596from html import escape

563from pathlib import Path597from pathlib import Path

564from collections import Counter598from collections import Counter

565 599 


648 {lang_bars}682 {lang_bars}

649 </div>683 </div>

650 <div class="main">684 <div class="main">

651 <h1>📁 {data["name"]}</h1>685 <h1>📁 {escape(data["name"])}</h1>

652 <ul class="tree" id="root"></ul>686 <ul class="tree" id="root"></ul>

653 </div>687 </div>

654 </div>688 </div>


656 const data = {json.dumps(data)};690 const data = {json.dumps(data)};

657 const colors = {json.dumps(colors)};691 const colors = {json.dumps(colors)};

658 function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }}692 function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }}

693 function esc(s) {{ return s.replace(/[&<>"']/g, c => ({{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}}[c])); }}

659 function render(node, parent) {{694 function render(node, parent) {{

660 if (node.children) {{695 if (node.children) {{

661 const det = document.createElement('details');696 const det = document.createElement('details');

662 det.open = parent === document.getElementById('root');697 det.open = parent === document.getElementById('root');

663 det.innerHTML = `<summary><span class="folder">📁 ${{node.name}}</span><span class="size">${{fmt(node.size)}}</span></summary>`;698 det.innerHTML = `<summary><span class="folder">📁 ${{esc(node.name)}}</span><span class="size">${{fmt(node.size)}}</span></summary>`;

664 const ul = document.createElement('ul'); ul.className = 'tree';699 const ul = document.createElement('ul'); ul.className = 'tree';

665 node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name));700 node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name));

666 node.children.forEach(c => render(c, ul));701 node.children.forEach(c => render(c, ul));


668 const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li);703 const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li);

669 }} else {{704 }} else {{

670 const li = document.createElement('li'); li.className = 'file';705 const li = document.createElement('li'); li.className = 'file';

671 li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{node.name}}<span class="size">${{fmt(node.size)}}</span>`;706 li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{esc(node.name)}}<span class="size">${{fmt(node.size)}}</span>`;

672 parent.appendChild(li);707 parent.appendChild(li);

673 }}708 }}

674 }}709 }}


689 724 

690To test, open Claude Code in any project and ask "Visualize this codebase." Claude runs the script, generates `codebase-map.html`, and opens it in your browser.725To test, open Claude Code in any project and ask "Visualize this codebase." Claude runs the script, generates `codebase-map.html`, and opens it in your browser.

691 726 

692This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the heavy lifting while Claude handles orchestration.727This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the work while Claude handles orchestration.

693 728 

694## Troubleshooting729## Troubleshooting

695 730 


713 748 

714Skill descriptions are loaded into context so Claude knows what's available. All skill names are always included, but if you have many skills, descriptions are shortened to fit the character budget, which can strip the keywords Claude needs to match your request. The budget scales dynamically at 1% of the context window, with a fallback of 8,000 characters.749Skill descriptions are loaded into context so Claude knows what's available. All skill names are always included, but if you have many skills, descriptions are shortened to fit the character budget, which can strip the keywords Claude needs to match your request. The budget scales dynamically at 1% of the context window, with a fallback of 8,000 characters.

715 750 

716To raise the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable. Or trim the `description` and `when_to_use` text at the source: front-load the key use case, since each entry's combined text is capped at 1,536 characters regardless of budget.751To raise the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable. To free budget for other skills, set low-priority entries to `"name-only"` in [`skillOverrides`](#override-skill-visibility-from-settings) so they list without a description. You can also trim the `description` and `when_to_use` text at the source: put the key use case first, since each entry's combined text is capped at 1,536 characters regardless of budget.

717 752 

718## Related resources753## Related resources

719 754 

755* **[Debug your configuration](/en/debug-your-config)**: diagnose why a skill isn't appearing or triggering

720* **[Subagents](/en/sub-agents)**: delegate tasks to specialized agents756* **[Subagents](/en/sub-agents)**: delegate tasks to specialized agents

721* **[Plugins](/en/plugins)**: package and distribute skills with other extensions757* **[Plugins](/en/plugins)**: package and distribute skills with other extensions

722* **[Hooks](/en/hooks)**: automate workflows around tool events758* **[Hooks](/en/hooks)**: automate workflows around tool events

statusline.md +29 −19

Details

25 25 

26## Set up a status line26## Set up a status line

27 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.28Use the [`/statusline` command](#use-the-%2Fstatusline-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 29 

30### Use the /statusline command30### Use the /statusline command

31 31 


64 64 

65The optional `refreshInterval` field re-runs your command every N seconds in addition to the [event-driven updates](#how-status-lines-work). The minimum is `1`. Set this when your status line shows time-based data such as a clock, or when background subagents change git state while the main session is idle. Leave it unset to run only on events.65The optional `refreshInterval` field re-runs your command every N seconds in addition to the [event-driven updates](#how-status-lines-work). The minimum is `1`. Set this when your status line shows time-based data such as a clock, or when background subagents change git state while the main session is idle. Leave it unset to run only on events.

66 66 

67The optional `hideVimModeIndicator` field suppresses the built-in `-- INSERT --` text below the prompt. Set this to `true` when your script renders [`vim.mode`](#available-data) itself, so the mode is not shown twice.

68 

67### Disable the status line69### Disable the status line

68 70 

69Run `/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.71Run `/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.


72 74 

73This 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.75This 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.

74 76 

75<Note>Running [`/statusline`](#use-the-statusline-command) with a description of what you want configures all of this for you automatically.</Note>77<Note>Running [`/statusline`](#use-the-%2Fstatusline-command) with a description of what you want configures all of this for you automatically.</Note>

76 78 

77These examples use Bash scripts, which work on macOS and Linux. On Windows, see [Windows configuration](#windows-configuration) for PowerShell and Git Bash examples.79These examples use Bash scripts, which work on macOS and Linux. On Windows, see [Windows configuration](#windows-configuration) for PowerShell and Git Bash examples.

78 80 


132 134 

133**When it updates**135**When it updates**

134 136 

135Your 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.137Your script runs after each new assistant message, after `/compact` finishes, 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.

136 138 

137These triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set [`refreshInterval`](#manually-configure-a-status-line) to also re-run the command on a fixed timer.139These triggers can go quiet when the main session is idle, for example while a coordinator waits on background subagents. To keep time-based or externally-sourced segments current during idle periods, set [`refreshInterval`](#manually-configure-a-status-line) to also re-run the command on a fixed timer.

138 140 


155| `workspace.project_dir` | Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session |157| `workspace.project_dir` | Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session |

156| `workspace.added_dirs` | Additional directories added via `/add-dir` or `--add-dir`. Empty array if none have been added |158| `workspace.added_dirs` | Additional directories added via `/add-dir` or `--add-dir`. Empty array if none have been added |

157| `workspace.git_worktree` | Git worktree name when the current directory is inside a linked worktree created with `git worktree add`. Absent in the main working tree. Populated for any git worktree, unlike `worktree.*` which applies only to `--worktree` sessions |159| `workspace.git_worktree` | Git worktree name when the current directory is inside a linked worktree created with `git worktree add`. Absent in the main working tree. Populated for any git worktree, unlike `worktree.*` which applies only to `--worktree` sessions |

158| `cost.total_cost_usd` | Total session cost in USD |160| `cost.total_cost_usd` | Estimated session cost in USD, computed client-side. May differ from your actual bill |

159| `cost.total_duration_ms` | Total wall-clock time since the session started, in milliseconds |161| `cost.total_duration_ms` | Total wall-clock time since the session started, in milliseconds |

160| `cost.total_api_duration_ms` | Total time spent waiting for API responses in milliseconds |162| `cost.total_api_duration_ms` | Total time spent waiting for API responses in milliseconds |

161| `cost.total_lines_added`, `cost.total_lines_removed` | Lines of code changed |163| `cost.total_lines_added`, `cost.total_lines_removed` | Lines of code changed |

162| `context_window.total_input_tokens`, `context_window.total_output_tokens` | Cumulative token counts across the session |164| `context_window.total_input_tokens`, `context_window.total_output_tokens` | Token counts currently in the context window, from the most recent API response. Input includes cache reads and writes. {/* min-version: 2.1.132 */}Before v2.1.132 these were cumulative session totals |

163| `context_window.context_window_size` | Maximum context window size in tokens. 200000 by default, or 1000000 for models with extended context. |165| `context_window.context_window_size` | Maximum context window size in tokens. 200000 by default, or 1000000 for models with extended context. |

164| `context_window.used_percentage` | Pre-calculated percentage of context window used |166| `context_window.used_percentage` | Pre-calculated percentage of context window used |

165| `context_window.remaining_percentage` | Pre-calculated percentage of context window remaining |167| `context_window.remaining_percentage` | Pre-calculated percentage of context window remaining |

166| `context_window.current_usage` | Token counts from the last API call, described in [context window fields](#context-window-fields) |168| `context_window.current_usage` | Token counts from the last API call, described in [context window fields](#context-window-fields) |

167| `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. |169| `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. |

170| `effort.level` | Current reasoning effort (`low`, `medium`, `high`, `xhigh`, or `max`). Reflects the live session value, including mid-session `/effort` changes. Absent when the current model does not support the effort parameter |

171| `thinking.enabled` | Whether extended thinking is enabled for the session |

168| `rate_limits.five_hour.used_percentage`, `rate_limits.seven_day.used_percentage` | Percentage of the 5-hour or 7-day rate limit consumed, from 0 to 100 |172| `rate_limits.five_hour.used_percentage`, `rate_limits.seven_day.used_percentage` | Percentage of the 5-hour or 7-day rate limit consumed, from 0 to 100 |

169| `rate_limits.five_hour.resets_at`, `rate_limits.seven_day.resets_at` | Unix epoch seconds when the 5-hour or 7-day rate limit window resets |173| `rate_limits.five_hour.resets_at`, `rate_limits.seven_day.resets_at` | Unix epoch seconds when the 5-hour or 7-day rate limit window resets |

170| `session_id` | Unique session identifier |174| `session_id` | Unique session identifier |


172| `transcript_path` | Path to conversation transcript file |176| `transcript_path` | Path to conversation transcript file |

173| `version` | Claude Code version |177| `version` | Claude Code version |

174| `output_style.name` | Name of the current output style |178| `output_style.name` | Name of the current output style |

175| `vim.mode` | Current vim mode (`NORMAL` or `INSERT`) when [vim mode](/en/interactive-mode#vim-editor-mode) is enabled |179| `vim.mode` | Current vim mode (`NORMAL`, `INSERT`, `VISUAL`, or `VISUAL LINE`) when [vim mode](/en/interactive-mode#vim-editor-mode) is enabled |

176| `agent.name` | Agent name when running with the `--agent` flag or agent settings configured |180| `agent.name` | Agent name when running with the `--agent` flag or agent settings configured |

177| `worktree.name` | Name of the active worktree. Present only during `--worktree` sessions |181| `worktree.name` | Name of the active worktree. Present only during `--worktree` sessions |

178| `worktree.path` | Absolute path to the worktree directory |182| `worktree.path` | Absolute path to the worktree directory |


190 "session_name": "my-session",194 "session_name": "my-session",

191 "transcript_path": "/path/to/transcript.jsonl",195 "transcript_path": "/path/to/transcript.jsonl",

192 "model": {196 "model": {

193 "id": "claude-opus-4-6",197 "id": "claude-opus-4-7",

194 "display_name": "Opus"198 "display_name": "Opus"

195 },199 },

196 "workspace": {200 "workspace": {


211 "total_lines_removed": 23215 "total_lines_removed": 23

212 },216 },

213 "context_window": {217 "context_window": {

214 "total_input_tokens": 15234,218 "total_input_tokens": 15500,

215 "total_output_tokens": 4521,219 "total_output_tokens": 1200,

216 "context_window_size": 200000,220 "context_window_size": 200000,

217 "used_percentage": 8,221 "used_percentage": 8,

218 "remaining_percentage": 92,222 "remaining_percentage": 92,


224 }228 }

225 },229 },

226 "exceeds_200k_tokens": false,230 "exceeds_200k_tokens": false,

231 "effort": {

232 "level": "high"

233 },

234 "thinking": {

235 "enabled": true

236 },

227 "rate_limits": {237 "rate_limits": {

228 "five_hour": {238 "five_hour": {

229 "used_percentage": 23.5,239 "used_percentage": 23.5,


254 264 

255 * `session_name`: appears only when a custom name has been set with `--name` or `/rename`265 * `session_name`: appears only when a custom name has been set with `--name` or `/rename`

256 * `workspace.git_worktree`: appears only when the current directory is inside a linked git worktree266 * `workspace.git_worktree`: appears only when the current directory is inside a linked git worktree

267 * `effort`: appears only when the current model supports the reasoning effort parameter

257 * `vim`: appears only when vim mode is enabled268 * `vim`: appears only when vim mode is enabled

258 * `agent`: appears only when running with the `--agent` flag or agent settings configured269 * `agent`: appears only when running with the `--agent` flag or agent settings configured

259 * `worktree`: appears only during `--worktree` sessions. When present, `branch` and `original_branch` may also be absent for hook-based worktrees270 * `worktree`: appears only during `--worktree` sessions. When present, `branch` and `original_branch` may also be absent for hook-based worktrees


261 272 

262 **Fields that may be `null`**:273 **Fields that may be `null`**:

263 274 

264 * `context_window.current_usage`: `null` before the first API call in a session275 * `context_window.current_usage`: `null` before the first API call in a session, and again after `/compact` until the next API call repopulates it

265 * `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session276 * `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session

266 277 

267 Handle missing fields with conditional access and null values with fallback defaults in your scripts.278 Handle missing fields with conditional access and null values with fallback defaults in your scripts.


269 280 

270### Context window fields281### Context window fields

271 282 

272The `context_window` object provides two ways to track context usage:283The `context_window` object describes the live context window from the most recent API response. As of v2.1.132, `total_input_tokens` and `total_output_tokens` reflect current context usage, not cumulative session totals.

273 284 

274* **Cumulative totals** (`total_input_tokens`, `total_output_tokens`): sum of all tokens across the entire session, useful for tracking total consumption285* **Combined totals** (`total_input_tokens`, `total_output_tokens`): tokens currently in the context window. `total_input_tokens` is the sum of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`; `total_output_tokens` is the output tokens from the most recent response. Both are `0` before the first API response.

275* **Current usage** (`current_usage`): token counts from the most recent API call, use this for accurate context percentage since it reflects the actual context state286* **Per-component usage** (`current_usage`): the same token counts broken out by category. Use this when you need cache hits separate from fresh input.

276 287 

277The `current_usage` object contains:288The `current_usage` object contains:

278 289 


285 296 

286If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.297If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.

287 298 

288The `current_usage` object is `null` before the first API call in a session.299The `current_usage` object is `null` before the first API call in a session, and again immediately after `/compact` until the next API call repopulates it.

289 300 

290## Examples301## Examples

291 302 


460 471 

461### Cost and duration tracking472### Cost and duration tracking

462 473 

463Track 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.474Track your session's API costs and elapsed time. The `cost.total_cost_usd` field accumulates the estimated 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.

464 475 

465Each script formats cost as currency and converts milliseconds to minutes and seconds:476Each script formats cost as currency and converts milliseconds to minutes and seconds:

466 477 


905 916 

906### Windows configuration917### Windows configuration

907 918 

908On Windows, Claude Code runs status line commands through Git Bash. You can invoke PowerShell from that shell:919On Windows, Claude Code runs status line commands through Git Bash when Git Bash is installed, or through PowerShell when Git Bash is absent. To run a PowerShell script as your status line, invoke it via `powershell`; this works from either shell:

909 920 

910<CodeGroup>921<CodeGroup>

911 ```json settings.json theme={null}922 ```json settings.json theme={null}


932 ```943 ```

933</CodeGroup>944</CodeGroup>

934 945 

935Or run a Bash script directly:946Or, when Git Bash is installed, run a Bash script directly:

936 947 

937<CodeGroup>948<CodeGroup>

938 ```json settings.json theme={null}949 ```json settings.json theme={null}


1000 1011 

1001**Context percentage shows unexpected values**1012**Context percentage shows unexpected values**

1002 1013 

1003* Use `used_percentage` for accurate context state rather than cumulative totals1014* Use `used_percentage` for the simplest accurate context state

1004* The `total_input_tokens` and `total_output_tokens` are cumulative across the session and may exceed the context window size

1005* Context percentage may differ from `/context` output due to when each is calculated1015* Context percentage may differ from `/context` output due to when each is calculated

1006 1016 

1007**OSC 8 links not clickable**1017**OSC 8 links not clickable**

sub-agents.md +124 −26

Details

24 24 

25Claude uses each subagent's description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it.25Claude uses each subagent's description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it.

26 26 

27Claude Code includes several built-in subagents like **Explore**, **Plan**, and **general-purpose**. You can also create custom subagents to handle specific tasks. This page covers the [built-in subagents](#built-in-subagents), [how to create your own](#quickstart-create-your-first-subagent), [full configuration options](#configure-subagents), [patterns for working with subagents](#work-with-subagents), and [example subagents](#example-subagents).27Claude Code includes several built-in subagents like **Explore**, **Plan**, and **general-purpose**. You can also create custom subagents to handle specific tasks. This page covers:

28 

29* [Built-in subagents](#built-in-subagents)

30* [How to create your own](#quickstart-create-your-first-subagent)

31* [Full configuration options](#configure-subagents)

32* [Patterns for working with subagents](#work-with-subagents)

33* [Forked subagents](#fork-the-current-conversation)

34* [Example subagents](#example-subagents)

28 35 

29## Built-in subagents36## Built-in subagents

30 37 


44 </Tab>51 </Tab>

45 52 

46 <Tab title="Plan">53 <Tab title="Plan">

47 A research agent used during [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan.54 A research agent used during [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode) to gather context before presenting a plan.

48 55 

49 * **Model**: Inherits from main conversation56 * **Model**: Inherits from main conversation

50 * **Tools**: Read-only tools (denied access to Write and Edit tools)57 * **Tools**: Read-only tools (denied access to Write and Edit tools)


69 | Agent | Model | When Claude uses it |76 | Agent | Model | When Claude uses it |

70 | :---------------- | :----- | :------------------------------------------------------- |77 | :---------------- | :----- | :------------------------------------------------------- |

71 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |78 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |

72 | Claude Code Guide | Haiku | When you ask questions about Claude Code features |79 | claude-code-guide | Haiku | When you ask questions about Claude Code features |

73 </Tab>80 </Tab>

74</Tabs>81</Tabs>

75 82 


173 180 

174**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call:181**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts. You can define multiple subagents in a single `--agents` call:

175 182 

176```bash theme={null}183<Tabs>

177claude --agents '{184 <Tab title="macOS, Linux, WSL">

185 ```bash theme={null}

186 claude --agents '{

178 "code-reviewer": {187 "code-reviewer": {

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

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


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

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

187 }196 }

188}'197 }'

189```198 ```

199 </Tab>

200 

201 <Tab title="Windows PowerShell">

202 ```powershell theme={null}

203 claude --agents @'

204 {

205 "code-reviewer": {

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

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

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

209 "model": "sonnet"

210 },

211 "debugger": {

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

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

214 }

215 }

216 '@

217 ```

218 </Tab>

219</Tabs>

190 220 

191The `--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`, `initialPrompt`, `memory`, `effort`, `background`, `isolation`, and `color`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents.221The `--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`, `initialPrompt`, `memory`, `effort`, `background`, `isolation`, and `color`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents.

192 222 


205Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:235Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:

206 236 

207<Note>237<Note>

208 Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use `/agents` to load it immediately.238 Subagents are loaded at session start. If you add or edit a subagent file directly on disk, restart your session to load it. Subagents created through the `/agents` interface take effect immediately without a restart.

209</Note>239</Note>

210 240 

211```markdown theme={null}241```markdown theme={null}


229The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.259The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.

230 260 

231| Field | Required | Description |261| Field | Required | Description |

232| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |262| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

233| `name` | Yes | Unique identifier using lowercase letters and hyphens |263| `name` | Yes | Unique identifier using lowercase letters and hyphens |

234| `description` | Yes | When Claude should delegate to this subagent |264| `description` | Yes | When Claude should delegate to this subagent |

235| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |265| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted. To preload Skills into context, use the `skills` field rather than listing `Skill` here |

236| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |266| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |

237| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, a full model ID (for example, `claude-opus-4-6`), or `inherit`. Defaults to `inherit` |267| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, a full model ID (for example, `claude-opus-4-7`), or `inherit`. Defaults to `inherit` |

238| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, or `plan` |268| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, or `plan`. Ignored for [plugin subagents](#choose-the-subagent-scope) |

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

240| `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 |270| `skills` | No | [Skills](/en/skills) to preload into the subagent's context at startup. The full skill content is injected, not just the description. Subagents can still invoke unlisted project, user, and plugin skills through the Skill tool |

241| `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#installing-mcp-servers) as value |271| `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#installing-mcp-servers) as value. Ignored for [plugin subagents](#choose-the-subagent-scope) |

242| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |272| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent. Ignored for [plugin subagents](#choose-the-subagent-scope) |

243| `memory` | No | [Persistent memory scope](#enable-persistent-memory): `user`, `project`, or `local`. Enables cross-session learning |273| `memory` | No | [Persistent memory scope](#enable-persistent-memory): `user`, `project`, or `local`. Enables cross-session learning |

244| `background` | No | Set to `true` to always run this subagent as a [background task](#run-subagents-in-foreground-or-background). Default: `false` |274| `background` | No | Set to `true` to always run this subagent as a [background task](#run-subagents-in-foreground-or-background). Default: `false` |

245| `effort` | No | Effort level when this subagent is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `max` (Opus 4.6 only) |275| `effort` | No | Effort level when this subagent is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model |

246| `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 |276| `isolation` | No | Set to `worktree` to run the subagent in a temporary [git worktree](/en/worktrees), giving it an isolated copy of the repository. The worktree is automatically cleaned up if the subagent makes no changes |

247| `color` | No | Display color for the subagent in the task list and transcript. Accepts `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan` |277| `color` | No | Display color for the subagent in the task list and transcript. Accepts `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan` |

248| `initialPrompt` | No | Auto-submitted as the first user turn when this agent runs as the main session agent (via `--agent` or the `agent` setting). [Commands](/en/commands) and [skills](/en/skills) are processed. Prepended to any user-provided prompt |278| `initialPrompt` | No | Auto-submitted as the first user turn when this agent runs as the main session agent (via `--agent` or the `agent` setting). [Commands](/en/commands) and [skills](/en/skills) are processed. Prepended to any user-provided prompt |

249 279 


252The `model` field controls which [AI model](/en/model-config) the subagent uses:282The `model` field controls which [AI model](/en/model-config) the subagent uses:

253 283 

254* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`284* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`

255* **Full model ID**: Use a full model ID such as `claude-opus-4-6` or `claude-sonnet-4-6`. Accepts the same values as the `--model` flag285* **Full model ID**: Use a full model ID such as `claude-opus-4-7` or `claude-sonnet-4-6`. Accepts the same values as the `--model` flag

256* **inherit**: Use the same model as the main conversation286* **inherit**: Use the same model as the main conversation

257* **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation)287* **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation)

258 288 


321 351 

322Use the `mcpServers` field to give a subagent access to [MCP](/en/mcp) servers that aren't available in the main conversation. Inline servers defined here are connected when the subagent starts and disconnected when it finishes. String references share the parent session's connection.352Use the `mcpServers` field to give a subagent access to [MCP](/en/mcp) servers that aren't available in the main conversation. Inline servers defined here are connected when the subagent starts and disconnected when it finishes. String references share the parent session's connection.

323 353 

354<Note>

355 The `mcpServers` field applies in both contexts where an agent file can run:

356 

357 * As a subagent, spawned through the Agent tool or an @-mention

358 * As the main session, launched with [`--agent`](#invoke-subagents-explicitly) or the `agent` setting

359 

360 When the agent is the main session, inline server definitions connect at startup alongside servers from [`.mcp.json`](/en/mcp) and settings files.

361</Note>

362 

324Each entry in the list is either an inline server definition or a string referencing an MCP server already configured in your session:363Each entry in the list is either an inline server definition or a string referencing an MCP server already configured in your session:

325 364 

326```yaml theme={null}365```yaml theme={null}


358| `plan` | Plan mode (read-only exploration) |397| `plan` | Plan mode (read-only exploration) |

359 398 

360<Warning>399<Warning>

361 Use `bypassPermissions` with caution. It skips permission prompts, allowing the subagent to execute operations without approval. Writes to `.git`, `.claude`, `.vscode`, `.idea`, and `.husky` directories still prompt for confirmation, except for `.claude/commands`, `.claude/agents`, and `.claude/skills`. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) for details.400 Use `bypassPermissions` with caution. It skips all permission prompts, allowing the subagent to execute operations without approval, including writes to `.git`, `.claude`, `.vscode`, `.idea`, and `.husky`. Root and home directory removals such as `rm -rf /` still prompt as a circuit breaker. See [permission modes](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) for details.

362</Warning>401</Warning>

363 402 

364If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden. If the parent uses [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode), the subagent inherits auto mode and any `permissionMode` in its frontmatter is ignored: the classifier evaluates the subagent's tool calls with the same block and allow rules as the parent session.403If the parent uses `bypassPermissions` or `acceptEdits`, this takes precedence and cannot be overridden. If the parent uses [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode), the subagent inherits auto mode and any `permissionMode` in its frontmatter is ignored: the classifier evaluates the subagent's tool calls with the same block and allow rules as the parent session.

365 404 

366#### Preload skills into subagents405#### Preload skills into subagents

367 406 


379Implement API endpoints. Follow the conventions and patterns from the preloaded skills.418Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

380```419```

381 420 

382The full content of each skill is injected into the subagent's context, not just made available for invocation. Subagents don't inherit skills from the parent conversation; you must list them explicitly.421The full content of each listed skill is injected into the subagent's context at startup. This field controls which skills are preloaded, not which skills the subagent can access: without it, the subagent can still discover and invoke project, user, and plugin skills through the Skill tool during execution. To prevent a subagent from invoking skills entirely, omit `Skill` from the [`tools`](#available-tools) list or add it to `disallowedTools`.

422 

423You cannot preload skills that set [`disable-model-invocation: true`](/en/skills#control-who-invokes-a-skill), since preloading draws from the same set of skills Claude can invoke. If a listed skill is missing or disabled, Claude Code skips it and logs a warning to the debug log.

383 424 

384<Note>425<Note>

385 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.426 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.


466exit 0507exit 0

467```508```

468 509 

469See [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.510See [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. On Windows, write hook scripts in PowerShell and add `shell: powershell` to the hook entry as shown in [running hooks in PowerShell](/en/hooks#windows-powershell-tool).

470 511 

471#### Disable specific subagents512#### Disable specific subagents

472 513 


500Define 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.541Define 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.

501 542 

502<Note>543<Note>

503 Frontmatter hooks fire when the agent is spawned as a subagent through the Agent tool or an @-mention. They do not fire when the agent runs as the main session via [`--agent`](#invoke-subagents-explicitly) or the `agent` setting. For session-wide hooks, configure them in [`settings.json`](/en/hooks).544 Frontmatter hooks fire when the agent is spawned as a subagent through the Agent tool or an @-mention, and when the agent runs as the main session via [`--agent`](#invoke-subagents-explicitly) or the `agent` setting. In the main-session case they run alongside any hooks defined in [`settings.json`](/en/hooks).

504</Note>545</Note>

505 546 

506All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are:547All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are:


531---572---

532```573```

533 574 

534`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.575When the agent is invoked as a subagent, `Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.

535 576 

536#### Project-level hooks for subagent events577#### Project-level hooks for subagent events

537 578 


637 678 

638To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars).679To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars).

639 680 

681When [fork mode](#fork-the-current-conversation) is enabled, every subagent spawn runs in the background regardless of the `background` field. Forks still surface permission prompts in your terminal as they occur instead of pre-approving; named subagents follow the pre-approval flow above.

682 

640### Common patterns683### Common patterns

641 684 

642#### Isolate high-volume operations685#### Isolate high-volume operations


688 731 

689Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.732Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.

690 733 

691For a quick question about something already in your conversation, use [`/btw`](/en/interactive-mode#side-questions-with-btw) instead of a subagent. It sees your full context but has no tool access, and the answer is discarded rather than added to history.734For a quick question about something already in your conversation, use [`/btw`](/en/interactive-mode#side-questions-with-%2Fbtw) instead of a subagent. It sees your full context but has no tool access, and the answer is discarded rather than added to history.

692 735 

693<Note>736<Note>

694 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.737 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.


743 786 

744The `preTokens` value shows how many tokens were used before compaction occurred.787The `preTokens` value shows how many tokens were used before compaction occurred.

745 788 

789## Fork the current conversation

790 

791<Note>

792 Forked subagents are experimental and require Claude Code v2.1.117 or later. Behavior and configuration may change in future releases. Enable them by setting the [`CLAUDE_CODE_FORK_SUBAGENT`](/en/env-vars) environment variable to `1`. The variable is honored in interactive mode and via the SDK or `claude -p`.

793</Note>

794 

795A fork is a subagent that inherits the entire conversation so far instead of starting fresh. This drops the input isolation that subagents otherwise provide: a fork sees the same system prompt, tools, model, and message history as the main session, so you can hand it a side task without re-explaining the situation. The fork's own tool calls still stay out of your conversation and only its final result comes back, so your main context window stays clean. Use a fork when a named subagent would need too much background to be useful, or when you want to try several approaches in parallel from the same starting point.

796 

797Enabling fork mode changes Claude Code in three ways:

798 

799* Claude spawns a fork whenever it would otherwise use the [general-purpose](#built-in-subagents) subagent. Named subagents such as Explore still spawn as before.

800* Every subagent spawn runs in the [background](#run-subagents-in-foreground-or-background), whether it is a fork or a named subagent. Set `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` to `1` to keep spawns synchronous.

801* The `/fork` command spawns a fork instead of acting as an alias for [`/branch`](/en/commands).

802 

803You can start a fork yourself with `/fork` followed by a directive. Claude Code names the fork from the first words of the directive. The following example forks the conversation to draft test cases while you continue with the implementation in the main session:

804 

805```text theme={null}

806/fork draft unit tests for the parser changes so far

807```

808 

809The fork appears in a panel below your prompt and runs in the background while you keep working. When it finishes, its result arrives as a message in your main conversation. The next section covers the panel controls for watching and steering forks while they run.

810 

811### Observe and steer running forks

812 

813Running forks appear in a panel below the prompt input, with one row for the main session and one for each fork. Use these keys to interact with the panel:

814 

815| Key | Action |

816| :-------- | :----------------------------------------------------------------- |

817| `↑` / `↓` | Move between rows |

818| `Enter` | Open the selected fork's transcript and send it follow-up messages |

819| `x` | Dismiss a finished fork or stop a running one |

820| `Esc` | Return focus to the prompt input |

821 

822### How forks differ from named subagents

823 

824A fork inherits everything the main session has at the moment it spawns. A named subagent starts from its own definition.

825 

826| | Fork | Named subagent |

827| :---------------------- | :------------------------------- | :----------------------------------------------------------------------------------------- |

828| Context | Full conversation history | Fresh context with the prompt you pass |

829| System prompt and tools | Same as main session | From the subagent's [definition file](#write-subagent-files) |

830| Model | Same as main session | From the subagent's `model` field |

831| Permissions | Prompts surface in your terminal | [Pre-approved](#run-subagents-in-foreground-or-background) before launch, then auto-denied |

832| Prompt cache | Shared with main session | Separate cache |

833 

834Because a fork's system prompt and tool definitions are identical to the parent, its first request reuses the parent's prompt cache. This makes forking cheaper than spawning a fresh subagent for tasks that need the same context.

835 

836When Claude spawns a fork through the Agent tool, it can pass `isolation: "worktree"` so the fork's file edits are written to a separate git worktree instead of your checkout.

837 

838### Limitations

839 

840Setting `CLAUDE_CODE_FORK_SUBAGENT=1` enables fork mode in interactive sessions, [non-interactive mode](/en/headless), and the Agent SDK. A fork cannot spawn further forks.

841 

746## Example subagents842## Example subagents

747 843 

748These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.844These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.


921exit 01017exit 0

922```1018```

923 1019 

924Make the script executable:1020On macOS and Linux, make the script executable:

925 1021 

926```bash theme={null}1022```bash theme={null}

927chmod +x ./scripts/validate-readonly-query.sh1023chmod +x ./scripts/validate-readonly-query.sh

928```1024```

929 1025 

1026On Windows, write the validation script in PowerShell and add `shell: powershell` to the hook entry. See [running hooks in PowerShell](/en/hooks#windows-powershell-tool).

1027 

930The 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.1028The 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.

931 1029 

932## Next steps1030## Next steps

terminal-config.md +255 −65

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> 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.3> Use this file to discover all available pages before exploring further.

4 4 

5# Optimize your terminal setup5# Configure your terminal for Claude Code

6 6 

7> Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience.7> Fix Shift+Enter for newlines, get a terminal bell when Claude finishes, configure tmux, match the color theme, and enable Vim mode in the Claude Code CLI.

8 8 

9### Themes and appearance9Claude Code works in any terminal without configuration. This page is for when something specific is not behaving the way you expect. Find your symptom below. If everything already feels right, you do not need this page.

10 10 

11Claude cannot control the theme of your terminal. That's handled by your terminal application. You can match Claude Code's theme to your terminal any time via the `/config` command.11* [Shift+Enter submits instead of inserting a newline](#enter-multiline-prompts)

12* [Option-key shortcuts do nothing on macOS](#enable-option-key-shortcuts-on-macos)

13* [No sound or alert when Claude finishes](#get-a-terminal-bell-or-notification)

14* [You run Claude Code inside tmux](#configure-tmux)

15* [Display flickers or scrollback jumps](#switch-to-fullscreen-rendering)

16* [You want Vim keys in the prompt](#edit-prompts-with-vim-keybindings)

12 17 

13For additional customization of the Claude Code interface itself, you can configure a [custom status line](/en/statusline) to display contextual information like the current model, working directory, or git branch at the bottom of your terminal.18This page is about getting your terminal to send the right signals to Claude Code. To change which keys Claude Code itself responds to, see [keybindings](/en/keybindings) instead.

14 19 

15### Line breaks20## Enter multiline prompts

16 21 

17You have several options for entering line breaks into Claude Code:22Pressing Enter submits your message. To add a line break without submitting, press Ctrl+J, or type `\` and then press Enter. Both work in every terminal with no setup.

18 23 

19* **Quick escape**: Type `\` followed by Enter to create a newline24In most terminals you can also press Shift+Enter, but support varies by terminal emulator:

20* **Ctrl+J**: Sends a line feed character, which works as a newline in any terminal without configuration

21* **Shift+Enter**: Works out of the box in iTerm2, WezTerm, Ghostty, and Kitty

22* **Keyboard shortcut**: Set up a keybinding to insert a newline in other terminals

23 25 

24#### Set up Shift+Enter with /terminal-setup26| Terminal | Shift+Enter for newline |

27| :---------------------------------------------------------------------- | :------------------------------------------ |

28| Ghostty, Kitty, iTerm2, WezTerm, Warp, Apple Terminal, Windows Terminal | Works without setup |

29| VS Code, Cursor, Windsurf, Alacritty, Zed | Run `/terminal-setup` once |

30| gnome-terminal, JetBrains IDEs such as PyCharm and Android Studio | Not available; use Ctrl+J or `\` then Enter |

25 31 

26Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter for VS Code, Alacritty, Zed, and Warp.32For VS Code, Cursor, Windsurf, Alacritty, and Zed, `/terminal-setup` writes Shift+Enter and other keybindings into the terminal's configuration file. In VS Code, Cursor, and Windsurf it also sets `terminal.integrated.mouseWheelScrollSensitivity` in the editor settings for smoother scrolling in [fullscreen mode](/en/fullscreen). Existing bindings and settings are left in place; if you see a message such as `VSCode terminal Shift+Enter key binding already configured`, no change was made. Run `/terminal-setup` directly in the host terminal rather than inside tmux or screen, since it needs to write to the host terminal's configuration.

27 33 

28<Note>34If you are running inside tmux, Shift+Enter also requires the [tmux configuration below](#configure-tmux) even when the outer terminal supports it.

29 The `/terminal-setup` command is only visible in terminals that require manual configuration. If you're using iTerm2, WezTerm, Ghostty, or Kitty, you won't see this command because Shift+Enter already works natively.

30</Note>

31 

32#### Set up Shift+Enter in tmux

33 

34Inside tmux, `Shift+Enter` submits instead of inserting a newline unless extended key reporting is enabled. Add these lines to `~/.tmux.conf`, then run `tmux source-file ~/.tmux.conf` to reload your configuration:

35 

36```text theme={null}

37set -s extended-keys on

38set -as terminal-features 'xterm*:extkeys'

39```

40 35 

41Claude Code requests extended keys at startup, but tmux ignores the request unless `extended-keys` is set to `on`. The `terminal-features` line tells tmux that your outer terminal can send these sequences.36To bind newline to a different key, or to swap behavior so Enter inserts a newline and Shift+Enter submits, map the `chat:newline` and `chat:submit` actions in your [keybindings file](/en/keybindings).

42 37 

43#### Set up Option+Enter on macOS38## Enable Option key shortcuts on macOS

44 39 

45On macOS, you can use Option+Enter as the newline keybinding in Terminal.app, iTerm2, and the VS Code terminal after enabling the Option-as-Meta setting.40Some Claude Code shortcuts use the Option key, such as Option+Enter for a newline or Option+P to switch models. On macOS, most terminals do not send Option as a modifier by default, so these shortcuts do nothing until you enable it. The terminal setting for this is usually labeled "Use Option as Meta Key"; Meta is the historical Unix name for the key now labeled Option or Alt.

46 41 

47<Tabs>42<Tabs>

48 <Tab title="Terminal.app">43 <Tab title="Apple Terminal">

49 1. Open Settings → Profiles → Keyboard44 Open Settings → Profiles → Keyboard and check "Use Option as Meta Key".

50 2. Check "Use Option as Meta Key"45 

46 If you accepted Claude Code's first-run prompt that offered "Option+Enter for newlines and visual bell", this is already done. That prompt runs `/terminal-setup` for you, which enables Option as Meta and switches the audio bell to a visual screen flash in your Apple Terminal profile.

51 </Tab>47 </Tab>

52 48 

53 <Tab title="iTerm2">49 <Tab title="iTerm2">

54 1. Open Settings → Profiles → Keys50 Open Settings → Profiles → Keys → General and set Left Option key and Right Option key to "Esc+".

55 2. Under General, set Left/Right Option key to "Esc+"51 

52 Running `/terminal-setup` in iTerm2 enables "Applications in terminal may access clipboard" under Settings → General → Selection so the `/copy` command can write to your system clipboard. The command detects iTerm2 even when run from inside tmux. Restart iTerm2 for the change to take effect.

56 </Tab>53 </Tab>

57 54 

58 <Tab title="VS Code">55 <Tab title="VS Code">

59 Set `"terminal.integrated.macOptionIsMeta": true` in VS Code settings.56 Add `"terminal.integrated.macOptionIsMeta": true` to your VS Code settings.

60 </Tab>57 </Tab>

61</Tabs>58</Tabs>

62 59 

63### Notification setup60For Ghostty, Kitty, and other terminals, look for an Option-as-Alt or Option-as-Meta setting in the terminal's configuration file.

61 

62## Get a terminal bell or notification

63 

64When Claude finishes a task or pauses for a permission prompt, it fires a notification event. Surfacing this as a terminal bell or desktop notification lets you switch to other work while a long task runs.

64 65 

65When Claude finishes working and is waiting for your input, it fires a notification event. You can surface this event as a desktop notification through your terminal or run custom logic with [notification hooks](/en/hooks#notification).66By default Claude Code sends a desktop notification only in Ghostty, Kitty, and iTerm2. In other terminals, set [`preferredNotifChannel`](/en/settings#available-settings) to `"terminal_bell"` to ring the terminal bell instead, or configure a [Notification hook](#play-a-sound-with-a-notification-hook) for a custom sound or command.

66 67 

67#### Terminal notifications68The desktop notification reaches your local machine over SSH, so a remote session can still alert you. Ghostty and Kitty forward it to your OS notification center without further setup. iTerm2 requires you to enable forwarding:

68 69 

69Kitty and Ghostty support desktop notifications without additional configuration. iTerm 2 requires setup:70<Steps>

71 <Step title="Open iTerm2 notification settings">

72 Go to Settings → Profiles → Terminal.

73 </Step>

70 74 

711. Open iTerm 2 Settings → Profiles Terminal75 <Step title="Enable alerts">

722. Enable "Notification Center Alerts"76 Check "Notification Center Alerts", then click "Filter Alerts" and enable "Send escape sequence-generated alerts".

733. Click "Filter Alerts" and check "Send escape sequence-generated alerts"77 </Step>

78</Steps>

74 79 

75If notifications aren't appearing, verify that your terminal app has notification permissions in your OS settings.80If notifications still do not appear, confirm that your terminal application has notification permission in your OS settings, and if you are running inside tmux, [enable passthrough](#configure-tmux).

76 81 

77When running Claude Code inside tmux, notifications and the [terminal progress bar](/en/settings#global-config-settings) only reach the outer terminal, such as iTerm2, Kitty, or Ghostty, if you enable passthrough in your tmux configuration:82### Play a sound with a Notification hook

78 83 

84In any terminal you can configure a [Notification hook](/en/hooks-guide#get-notified-when-claude-needs-input) to play a sound or run a custom command when Claude needs your attention. Hooks run alongside the built-in notification rather than replacing it, so terminals that do not receive a desktop notification, such as Warp or the VS Code integrated terminal, can use a hook or set `preferredNotifChannel` to `"terminal_bell"` instead.

85 

86The example below plays a system sound on macOS. The linked guide has desktop notification commands for macOS, Linux, and Windows.

87 

88```json ~/.claude/settings.json theme={null}

89{

90 "hooks": {

91 "Notification": [

92 {

93 "hooks": [{ "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }]

94 }

95 ]

96 }

97}

79```98```

99 

100## Configure tmux

101 

102When Claude Code runs inside tmux, two things break by default: Shift+Enter submits instead of inserting a newline, and desktop notifications and the [progress bar](/en/settings#available-settings) never reach the outer terminal. Add these lines to `~/.tmux.conf`, then run `tmux source-file ~/.tmux.conf` to apply them to the running server:

103 

104```bash ~/.tmux.conf theme={null}

80set -g allow-passthrough on105set -g allow-passthrough on

106set -s extended-keys on

107set -as terminal-features 'xterm*:extkeys'

81```108```

82 109 

83Without this setting, tmux intercepts the escape sequences and they do not reach the terminal application.110The `allow-passthrough` line lets notifications and progress updates reach the outer terminal instead of being swallowed by tmux. The `extended-keys` lines let tmux distinguish Shift+Enter from plain Enter so the newline shortcut works.

111 

112## Match the color theme

113 

114Use the `/theme` command, or the theme picker in `/config`, to choose a Claude Code theme that matches your terminal. Selecting the auto option detects your terminal's light or dark background, so the theme follows OS appearance changes whenever your terminal does. Claude Code does not control the terminal's own color scheme, which is set by the terminal application.

115 

116To customize what appears at the bottom of the interface, configure a [custom status line](/en/statusline) that shows the current model, working directory, git branch, or other context.

117 

118### Create a custom theme

119 

120<Note>

121 Custom themes require Claude Code v2.1.118 or later.

122</Note>

123 

124In addition to the built-in presets, `/theme` lists any custom themes you have defined and any themes contributed by installed [plugins](/en/plugins-reference#themes). Select **New custom theme…** at the end of the list to create one interactively: you name the theme, then pick individual color tokens to override. Press `Ctrl+E` while a custom theme is highlighted to edit it.

125 

126Each custom theme is a JSON file in `~/.claude/themes/`. The filename without the `.json` extension is the theme's slug, and selecting the theme stores `custom:<slug>` as your theme preference. The file has three optional fields:

127 

128| Field | Type | Description |

129| :---------- | :----- | :---------------------------------------------------------------------------------------------------------------------------------------------- |

130| `name` | string | Display label shown in `/theme`. Defaults to the filename slug |

131| `base` | string | Built-in preset the theme starts from: `dark`, `light`, `dark-daltonized`, `light-daltonized`, `dark-ansi`, or `light-ansi`. Defaults to `dark` |

132| `overrides` | object | Map of color token names to color values. Tokens not listed here fall through to the base preset |

133 

134Color values accept `#rrggbb`, `#rgb`, `rgb(r,g,b)`, `ansi256(n)`, or `ansi:<name>` where `<name>` is one of the 16 standard ANSI color names such as `red` or `cyanBright`. Unknown tokens and invalid color values are ignored, so a typo cannot break rendering.

135 

136The following example defines a theme that keeps the dark preset but recolors the prompt accent, error text, and success text:

137 

138```json ~/.claude/themes/dracula.json theme={null}

139{

140 "name": "Dracula",

141 "base": "dark",

142 "overrides": {

143 "claude": "#bd93f9",

144 "error": "#ff5555",

145 "success": "#50fa7b"

146 }

147}

148```

149 

150Claude Code watches `~/.claude/themes/` and reloads when a file changes, so edits made in your editor apply to a running session without a restart.

151 

152The reference below covers the tokens you can set in `overrides`. The interactive editor in `/theme` shows the same tokens with a live preview, plus a few single-purpose accents such as onboarding screen colors that are omitted here.

153 

154<Accordion title="Color token reference">

155 The following example combines tokens from several of the groups below: the brand accent, the plan mode border, the diff backgrounds, and the fullscreen message background.

156 

157 ```json ~/.claude/themes/midnight.json theme={null}

158 {

159 "name": "Midnight",

160 "base": "dark",

161 "overrides": {

162 "claude": "#a78bfa",

163 "planMode": "#38bdf8",

164 "diffAdded": "#14532d",

165 "diffRemoved": "#7f1d1d",

166 "userMessageBackground": "#1e1b4b"

167 }

168 }

169 ```

170 

171 #### Text and accent colors

172 

173 Control the primary brand accent and the foreground text shades used throughout the interface.

174 

175 | Token | Controls |

176 | :------------ | :--------------------------------------------------------------- |

177 | `claude` | Primary brand accent, used for the spinner and assistant label |

178 | `text` | Default foreground text |

179 | `inverseText` | Text drawn on top of a colored background, such as status badges |

180 | `inactive` | Secondary text such as hints, timestamps, and disabled items |

181 | `subtle` | Faint borders and de-emphasized secondary text |

182 | `suggestion` | Autocomplete suggestions and selection highlight in pickers |

183 | `permission` | Dialog borders, including permission prompts and pickers |

184 | `remember` | Memory and `CLAUDE.md` indicators |

185 

186 #### Status colors

187 

188 Signal success, failure, and warning states across messages and indicators.

189 

190 | Token | Controls |

191 | :-------- | :--------------------------------------------------- |

192 | `success` | Success messages and passing checks |

193 | `error` | Error messages and failures |

194 | `warning` | Warnings, caution messages, and the auto mode border |

195 | `merged` | Merged pull request status |

196 

197 #### Input box and mode indicators

198 

199 Set the input box border color and the accent shown while a permission mode or indicator is active.

200 

201 | Token | Controls |

202 | :------------- | :------------------------------------------------- |

203 | `promptBorder` | Input box border in the default permission mode |

204 | `planMode` | Plan mode accent and border |

205 | `autoAccept` | Accept-edits mode accent and border |

206 | `bashBorder` | Input box border when entering a `!` shell command |

207 | `ide` | IDE connection indicator |

208 | `fastMode` | Fast mode indicator |

209 

210 #### Diff rendering

211 

212 Color added and removed code in file edits and reviews.

213 

214 | Token | Controls |

215 | :------------------ | :------------------------------------------------- |

216 | `diffAdded` | Background of added lines |

217 | `diffRemoved` | Background of removed lines |

218 | `diffAddedDimmed` | Background of unchanged context near added lines |

219 | `diffRemovedDimmed` | Background of unchanged context near removed lines |

220 | `diffAddedWord` | Word-level highlight within an added line |

221 | `diffRemovedWord` | Word-level highlight within a removed line |

222 

223 #### Fullscreen mode

224 

225 Apply only in [fullscreen rendering mode](/en/fullscreen), where messages have a background fill.

226 

227 | Token | Controls |

228 | :--------------------------- | :----------------------------------------------------------------- |

229 | `userMessageBackground` | Background behind your messages in the transcript |

230 | `userMessageBackgroundHover` | Background behind a message while hovered or expanded |

231 | `messageActionsBackground` | Background behind the selected message when the action bar is open |

232 | `bashMessageBackgroundColor` | Background behind `!` shell command entries in the transcript |

233 | `memoryBackgroundColor` | Background behind `#` memory entries in the transcript |

234 | `selectionBg` | Background of text selected with the mouse |

235 

236 #### Usage meter and speaker labels

237 

238 Adjust the bar shown in the `/usage` view and the labels that distinguish your messages from Claude's.

239 

240 | Token | Controls |

241 | :----------------- | :------------------------------------------------ |

242 | `rate_limit_fill` | Filled portion of the usage meter |

243 | `rate_limit_empty` | Unfilled portion of the usage meter |

244 | `briefLabelYou` | Color of the `You` label on your messages |

245 | `briefLabelClaude` | Color of the `Claude` label on assistant messages |

246 

247 #### Shimmer variants and subagent colors

248 

249 Several tokens have a paired shimmer variant that supplies the lighter color used in the spinner's animated gradient. Override the shimmer alongside its base token if the animation looks mismatched.

250 

251 * `claude` and `claudeShimmer`

252 * `warning` and `warningShimmer`

253 * `permission` and `permissionShimmer`

254 * `promptBorder` and `promptBorderShimmer`

255 * `inactive` and `inactiveShimmer`

256 * `fastMode` and `fastModeShimmer`

257 

258 Each [subagent](/en/sub-agents) and parallel task is shown in one of eight named colors so you can tell them apart in the transcript. The token names follow the pattern `<color>_FOR_SUBAGENTS_ONLY`, where `<color>` is `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan`. Override these to change what each named color looks like. For example, a subagent with `color: blue` in its definition is drawn using the `blue_FOR_SUBAGENTS_ONLY` value.

259 

260 The [`ultrathink`](/en/model-config#use-ultrathink-for-one-off-deep-reasoning) and [`ultraplan`](/en/ultraplan) keywords in the prompt input are rendered with a seven-color rainbow gradient. The token names follow the pattern `rainbow_<color>` and `rainbow_<color>_shimmer`, where `<color>` is `red`, `orange`, `yellow`, `green`, `blue`, `indigo`, or `violet`.

261</Accordion>

262 

263## Switch to fullscreen rendering

264 

265If the display flickers or the scroll position jumps while Claude is working, switch to [fullscreen rendering mode](/en/fullscreen). It draws to a separate screen the terminal reserves for full-screen apps instead of appending to your normal scrollback, which keeps memory usage flat and adds mouse support for scrolling and selection. In this mode you scroll with the mouse or PageUp inside Claude Code rather than with your terminal's native scrollback; see the [fullscreen page](/en/fullscreen#search-and-review-the-conversation) for how to search and copy.

84 266 

85Other terminals, including the default macOS Terminal, do not support native notifications. Use [notification hooks](/en/hooks#notification) instead.267Run `/tui fullscreen` to switch in the current session with your conversation intact. To make it the default, set the `CLAUDE_CODE_NO_FLICKER` environment variable before starting Claude Code:

86 268 

87#### Notification hooks269<CodeGroup>

270 ```bash Bash and Zsh theme={null}

271 CLAUDE_CODE_NO_FLICKER=1 claude

272 ```

88 273 

89To add custom behavior when notifications fire, such as playing a sound or sending a message, configure a [notification hook](/en/hooks#notification). Hooks run alongside terminal notifications, not as a replacement.274 ```powershell PowerShell theme={null}

275 $env:CLAUDE_CODE_NO_FLICKER = "1"; claude

276 ```

90 277 

91### Reduce flicker and memory usage278 ```json ~/.claude/settings.json theme={null}

279 {

280 "env": {

281 "CLAUDE_CODE_NO_FLICKER": "1"

282 }

283 }

284 ```

285</CodeGroup>

92 286 

93If you see flicker during long sessions, or your terminal scroll position jumps to the top while Claude is working, try [fullscreen rendering](/en/fullscreen). It uses an alternate rendering path that keeps memory flat and adds mouse support. Enable it with `CLAUDE_CODE_NO_FLICKER=1`.287## Paste large content

94 288 

95### Handling large inputs289When you paste more than 10,000 characters into the prompt, Claude Code collapses the input to a `[Pasted text]` placeholder so the input box stays usable. The full content is still sent to Claude when you submit.

96 290 

97When working with extensive code or long instructions:291The VS Code integrated terminal can drop characters from very large pastes before they reach Claude Code, so prefer file-based workflows there. For very large inputs such as entire files or long logs, write the content to a file and ask Claude to read it instead of pasting. This keeps the conversation transcript readable and lets Claude reference the file by path in later turns.

98 292 

99* **Avoid direct pasting**: Claude Code may struggle with very long pasted content293## Edit prompts with Vim keybindings

100* **Use file-based workflows**: Write content to a file and ask Claude to read it

101* **Be aware of VS Code limitations**: The VS Code terminal is particularly prone to truncating long pastes

102 294 

103### Vim Mode295Claude Code includes a Vim-style editing mode for the prompt input. Enable it through `/config` → Editor mode, or by setting [`editorMode`](/en/settings#available-settings) to `"vim"` in `~/.claude/settings.json`. Set Editor mode back to `normal` to turn it off.

104 296 

105Claude Code supports a subset of Vim keybindings that can be enabled via `/config` → Editor mode. To set the mode directly in your config file, set the [`editorMode`](/en/settings#global-config-settings) global config key to `"vim"` in `~/.claude.json`.297Vim mode supports a subset of NORMAL- and VISUAL-mode motions and operators, such as `hjkl` navigation, `v`/`V` selection, and `d`/`c`/`y` with text objects. See the [Vim editor mode reference](/en/interactive-mode#vim-editor-mode) for the full key table. Vim motions are not remappable through the keybindings file.

106 298 

107The supported subset includes:299Pressing Enter still submits your prompt in INSERT mode, unlike standard Vim. Use `o` or `O` in NORMAL mode, or Ctrl+J, to insert a newline instead.

108 300 

109* Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT)301## Related resources

110* Navigation: `h`/`j`/`k`/`l`, `w`/`e`/`b`, `0`/`$`/`^`, `gg`/`G`, `f`/`F`/`t`/`T` with `;`/`,` repeat

111* Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat)

112* Yank/paste: `yy`/`Y`, `yw`/`ye`/`yb`, `p`/`P`

113* Text objects: `iw`/`aw`, `iW`/`aW`, `i"`/`a"`, `i'`/`a'`, `i(`/`a(`, `i[`/`a[`, `i{`/`a{`

114* Indentation: `>>`/`<<`

115* Line operations: `J` (join lines)

116 302 

117See [Interactive mode](/en/interactive-mode#vim-editor-mode) for the complete reference.303* [Interactive mode](/en/interactive-mode): full keyboard shortcut reference and the Vim key table

304* [Keybindings](/en/keybindings): remap any Claude Code shortcut, including Enter and Shift+Enter

305* [Fullscreen rendering](/en/fullscreen): details on scrolling, search, and copy in fullscreen mode

306* [Hooks guide](/en/hooks-guide): more Notification hook examples for Linux and Windows

307* [Troubleshooting](/en/troubleshooting): fixes for issues outside terminal configuration

Details

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

8 8 

9 9 

10 

11Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration.10Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration.

12 11 

13<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="third_party_overview" />} />12<ContactSalesCard surface="third_party_overview" />

14 13 

15## Compare deployment options14## Compare deployment options

16 15 

tools-reference.md +13 −11

Details

11To add custom tools, connect an [MCP server](/en/mcp). To extend Claude with reusable prompt-based workflows, write a [skill](/en/skills), which runs through the existing `Skill` tool rather than adding a new tool entry.11To add custom tools, connect an [MCP server](/en/mcp). To extend Claude with reusable prompt-based workflows, write a [skill](/en/skills), which runs through the existing `Skill` tool rather than adding a new tool entry.

12 12 

13| Tool | Description | Permission Required |13| Tool | Description | Permission Required |

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

15| `Agent` | Spawns a [subagent](/en/sub-agents) with its own context window to handle a task | No |15| `Agent` | Spawns a [subagent](/en/sub-agents) with its own context window to handle a task | No |

16| `AskUserQuestion` | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |16| `AskUserQuestion` | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |

17| `Bash` | Executes shell commands in your environment. See [Bash tool behavior](#bash-tool-behavior) | Yes |17| `Bash` | Executes shell commands in your environment. See [Bash tool behavior](#bash-tool-behavior) | Yes |

18| `CronCreate` | Schedules a recurring or one-shot prompt within the current session (gone when Claude exits). See [scheduled tasks](/en/scheduled-tasks) | No |18| `CronCreate` | Schedules a recurring or one-shot prompt within the current session. Tasks are session-scoped and restored on `--resume` or `--continue` if unexpired. See [scheduled tasks](/en/scheduled-tasks) | No |

19| `CronDelete` | Cancels a scheduled task by ID | No |19| `CronDelete` | Cancels a scheduled task by ID | No |

20| `CronList` | Lists all scheduled tasks in the session | No |20| `CronList` | Lists all scheduled tasks in the session | No |

21| `Edit` | Makes targeted edits to specific files | Yes |21| `Edit` | Makes targeted edits to specific files | Yes |

22| `EnterPlanMode` | Switches to plan mode to design an approach before coding | No |22| `EnterPlanMode` | Switches to plan mode to design an approach before coding | No |

23| `EnterWorktree` | Creates an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) and switches into it. Pass a `path` to switch into an existing worktree of the current repository instead of creating a new one | No |23| `EnterWorktree` | Creates an isolated [git worktree](/en/worktrees) and switches into it. Pass a `path` to switch into an existing worktree of the current repository instead of creating a new one. Not available to subagents | No |

24| `ExitPlanMode` | Presents a plan for approval and exits plan mode | Yes |24| `ExitPlanMode` | Presents a plan for approval and exits plan mode | Yes |

25| `ExitWorktree` | Exits a worktree session and returns to the original directory | No |25| `ExitWorktree` | Exits a worktree session and returns to the original directory. Not available to subagents | No |

26| `Glob` | Finds files based on pattern matching | No |26| `Glob` | Finds files based on pattern matching | No |

27| `Grep` | Searches for patterns in file contents | No |27| `Grep` | Searches for patterns in file contents | No |

28| `ListMcpResourcesTool` | Lists resources exposed by connected [MCP servers](/en/mcp) | No |28| `ListMcpResourcesTool` | Lists resources exposed by connected [MCP servers](/en/mcp) | No |

29| `LSP` | Code intelligence via language servers: jump to definitions, find references, report type errors and warnings. See [LSP tool behavior](#lsp-tool-behavior) | No |29| `LSP` | Code intelligence via language servers: jump to definitions, find references, report type errors and warnings. See [LSP tool behavior](#lsp-tool-behavior) | No |

30| `Monitor` | Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. See [Monitor tool](#monitor-tool) | Yes |30| `Monitor` | Runs a command in the background and feeds each output line back to Claude, so it can react to log entries, file changes, or polled status mid-conversation. See [Monitor tool](#monitor-tool) | Yes |

31| `NotebookEdit` | Modifies Jupyter notebook cells | Yes |31| `NotebookEdit` | Modifies Jupyter notebook cells | Yes |

32| `PowerShell` | Executes PowerShell commands on Windows. Opt-in preview. See [PowerShell tool](#powershell-tool) | Yes |32| `PowerShell` | Executes PowerShell commands natively. See [PowerShell tool](#powershell-tool) for availability | Yes |

33| `Read` | Reads the contents of files | No |33| `Read` | Reads the contents of files | No |

34| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |34| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |

35| `SendMessage` | Sends a message to an [agent team](/en/agent-teams) teammate, or [resumes a subagent](/en/sub-agents#resume-subagents) by its agent ID. Stopped subagents auto-resume in the background. Only available when `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set | No |35| `SendMessage` | Sends a message to an [agent team](/en/agent-teams) teammate, or [resumes a subagent](/en/sub-agents#resume-subagents) by its agent ID. Stopped subagents auto-resume in the background. Only available when `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set | No |

36| `ShareOnboardingGuide` | {/* plan-availability: feature=onboarding-guide-share plans=pro,max,team,enterprise providers=anthropic */}Uploads `ONBOARDING.md` and returns a share link teammates can open in Claude Code. Called from `/team-onboarding` after the guide is written. Available to claude.ai subscribers on Pro, Max, Team, and Enterprise plans | Yes |

36| `Skill` | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |37| `Skill` | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

37| `TaskCreate` | Creates a new task in the task list | No |38| `TaskCreate` | Creates a new task in the task list | No |

38| `TaskGet` | Retrieves full details for a specific task | No |39| `TaskGet` | Retrieves full details for a specific task | No |


91 92 

92Monitor uses the same [permission rules as Bash](/en/permissions#tool-specific-permission-rules), so `allow` and `deny` patterns you have set for Bash apply here too. It is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. It is also not available when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set.93Monitor uses the same [permission rules as Bash](/en/permissions#tool-specific-permission-rules), so `allow` and `deny` patterns you have set for Bash apply here too. It is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. It is also not available when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set.

93 94 

95Plugins can declare monitors that start automatically when the plugin is active, instead of asking Claude to start them. See [plugin monitors](/en/plugins-reference#monitors).

96 

94## PowerShell tool97## PowerShell tool

95 98 

96On Windows, Claude Code can run PowerShell commands natively instead of routing through Git Bash. This is an opt-in preview.99The PowerShell tool lets Claude run PowerShell commands natively. On Windows, this means commands run in PowerShell instead of routing through Git Bash. On Windows without Git Bash, the tool is enabled automatically. On Windows with Git Bash installed, the tool is rolling out progressively. On Linux, macOS, and WSL, the tool is opt-in.

97 100 

98### Enable the PowerShell tool101### Enable the PowerShell tool

99 102 


107}110}

108```111```

109 112 

110Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (PowerShell 5.1). The Bash tool remains registered alongside the PowerShell tool, so you may need to ask Claude to use PowerShell.113On Windows, set the variable to `0` to opt out of the rollout. On Linux, macOS, and WSL, the tool requires PowerShell 7 or later: install `pwsh` and ensure it is on your `PATH`.

114 

115On Windows, Claude Code auto-detects `pwsh.exe` for PowerShell 7+ with a fallback to `powershell.exe` for PowerShell 5.1. When the tool is enabled, Claude treats PowerShell as the primary shell. The Bash tool remains available for POSIX scripts when Git Bash is installed.

111 116 

112### Shell selection in settings, hooks, and skills117### Shell selection in settings, hooks, and skills

113 118 


123 128 

124The PowerShell tool has the following known limitations during the preview:129The PowerShell tool has the following known limitations during the preview:

125 130 

126* Auto mode does not work with the PowerShell tool yet

127* PowerShell profiles are not loaded131* PowerShell profiles are not loaded

128* Sandboxing is not supported132* On Windows, sandboxing is not supported

129* Only supported on native Windows, not WSL

130* Git Bash is still required to start Claude Code

131 133 

132## Check which tools are available134## Check which tools are available

133 135 

troubleshoot-install.md +803 −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# Troubleshoot installation and login

6 

7> Fix command not found, PATH, permission, network, and authentication errors when installing or signing in to Claude Code.

8 

9If installation fails or you can't sign in, find your error below. For runtime issues after Claude Code is working, see [Troubleshooting](/en/troubleshooting). For configuration problems such as settings not applying or hooks not firing, see [Debug your configuration](/en/debug-your-config).

10 

11## Find your error

12 

13Match the error message or symptom you're seeing to a fix:

14 

15| What you see | Solution |

16| :------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- |

17| `command not found: claude` or `'claude' is not recognized` | [Fix your PATH](#command-not-found-claude-after-installation) |

18| `syntax error near unexpected token '<'` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

19| `curl: (56) Failure writing output to destination` | [Check connectivity or use an alternative installer](#curl-56-failure-writing-output-to-destination) |

20| `Killed` during install on Linux | [Add swap space for low-memory servers](#install-killed-on-low-memory-linux-servers) |

21| `TLS connect error` or `SSL/TLS secure channel` | [Update CA certificates](#tls-or-ssl-connection-errors) |

22| `Failed to fetch version` or can't reach download server | [Check network and proxy settings](#check-network-connectivity) |

23| `irm is not recognized` or `&& is not valid` | [Use the right command for your shell](#wrong-install-command-on-windows) |

24| `'bash' is not recognized as the name of a cmdlet` | [Use the Windows installer command](#wrong-install-command-on-windows) |

25| `Claude Code on Windows requires either Git for Windows (for bash) or PowerShell` | [Install a shell](#claude-code-on-windows-requires-either-git-for-windows-for-bash-or-powershell) |

26| `Claude Code does not support 32-bit Windows` | [Open Windows PowerShell, not the x86 entry](#claude-code-does-not-support-32-bit-windows) |

27| `The process cannot access the file ... because it is being used by another process` | [Clear the downloads folder and retry](#the-process-cannot-access-the-file-during-windows-install) |

28| `Error loading shared library` | [Wrong binary variant for your system](#linux-musl-or-glibc-binary-mismatch) |

29| `Illegal instruction` | [Architecture or CPU instruction set mismatch](#illegal-instruction) |

30| `cannot execute binary file: Exec format error` in WSL | [WSL1 native-binary regression](#exec-format-error-on-wsl1) |

31| PowerShell installer completes but `claude` is not found or shows an old version | [Restart your terminal and verify PATH](#verify-your-path) |

32| `dyld: cannot load`, `dyld: Symbol not found`, or `Abort trap` on macOS | [Binary incompatibility](#dyld-cannot-load-on-macos) |

33| `Invoke-Expression: Missing argument in parameter list` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

34| `App unavailable in region` | Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries). |

35| `unable to get local issuer certificate` | [Configure corporate CA certificates](#tls-or-ssl-connection-errors) |

36| `OAuth error` or `403 Forbidden` | [Fix authentication](#login-and-authentication) |

37| `Could not load the default credentials` or `Could not load credentials from any providers` | [Bedrock, Vertex, or Foundry credentials](#bedrock-vertex-or-foundry-credentials-not-loading) |

38| `ChainedTokenCredential authentication failed` or `CredentialUnavailableError` | [Bedrock, Vertex, or Foundry credentials](#bedrock-vertex-or-foundry-credentials-not-loading) |

39| `API Error: 500`, `529 Overloaded`, `429`, or other 4xx and 5xx errors not listed above | See the [Error reference](/en/errors) |

40 

41If your issue isn't listed, work through the diagnostic checks below to narrow down the cause.

42 

43<Tip>

44 If you'd rather skip the terminal entirely, the [Claude Code Desktop app](/en/desktop-quickstart) lets you install and use Claude Code through a graphical interface. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs) and start coding without any command-line setup.

45</Tip>

46 

47## Run diagnostic checks

48 

49### Check network connectivity

50 

51The installer downloads from `downloads.claude.ai`. Verify you can reach it:

52 

53```bash theme={null}

54curl -sI https://downloads.claude.ai/claude-code-releases/latest

55```

56 

57An `HTTP/2 200` line means you reached the server. If you see no output, `Could not resolve host`, or a connection timeout, your network is blocking the connection. Common causes:

58 

59* Corporate firewalls or proxies blocking `downloads.claude.ai`

60* Regional network restrictions: try a VPN or alternative network

61* TLS/SSL issues: update your system's CA certificates, or check if `HTTPS_PROXY` is configured

62 

63If you're behind a corporate proxy, set `HTTPS_PROXY` and `HTTP_PROXY` to your proxy's address before installing. Ask your IT team for the proxy URL if you don't know it, or check your browser's proxy settings.

64 

65This example sets both proxy variables, then runs the installer through your proxy:

66 

67<Tabs>

68 <Tab title="macOS/Linux">

69 ```bash theme={null}

70 export HTTP_PROXY=http://proxy.example.com:8080

71 export HTTPS_PROXY=http://proxy.example.com:8080

72 curl -fsSL https://claude.ai/install.sh | bash

73 ```

74 </Tab>

75 

76 <Tab title="Windows PowerShell">

77 ```powershell theme={null}

78 $env:HTTP_PROXY = 'http://proxy.example.com:8080'

79 $env:HTTPS_PROXY = 'http://proxy.example.com:8080'

80 irm https://claude.ai/install.ps1 | iex

81 ```

82 </Tab>

83</Tabs>

84 

85### Verify your PATH

86 

87If installation succeeded but you get a `command not found` or `not recognized` error when running `claude`, the install directory isn't in your PATH. Your shell searches for programs in directories listed in PATH, and the installer places `claude` at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows.

88 

89Check if the install directory is in your PATH by listing your PATH entries and filtering for `local/bin`:

90 

91<Tabs>

92 <Tab title="macOS/Linux">

93 ```bash theme={null}

94 echo $PATH | tr ':' '\n' | grep -Fx "$HOME/.local/bin"

95 ```

96 

97 If this prints `/Users/you/.local/bin` or `/home/you/.local/bin`, the directory is in your PATH and you can skip to [Check for conflicting installations](#check-for-conflicting-installations). If there's no output, add it to your shell configuration.

98 

99 For Zsh, the default on macOS:

100 

101 ```bash theme={null}

102 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

103 source ~/.zshrc

104 ```

105 

106 For Bash, the default on most Linux distributions:

107 

108 ```bash theme={null}

109 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

110 source ~/.bashrc

111 ```

112 

113 Alternatively, close and reopen your terminal.

114 

115 For other shells such as fish or Nushell, add `~/.local/bin` to your PATH using your shell's own configuration syntax, then restart your terminal.

116 

117 Verify the fix worked:

118 

119 ```bash theme={null}

120 claude --version

121 ```

122 </Tab>

123 

124 <Tab title="Windows PowerShell">

125 ```powershell theme={null}

126 $env:PATH -split ';' | Select-String '\.local\\bin'

127 ```

128 

129 If there's no output, add the install directory to your User PATH:

130 

131 ```powershell theme={null}

132 $currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')

133 [Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User')

134 ```

135 

136 Restart your terminal for the change to take effect.

137 

138 Verify the fix worked:

139 

140 ```powershell theme={null}

141 claude --version

142 ```

143 </Tab>

144 

145 <Tab title="Windows CMD">

146 ```batch theme={null}

147 echo %PATH% | findstr /i "local\bin"

148 ```

149 

150 If there's no output, open System Settings, go to Environment Variables, and add `%USERPROFILE%\.local\bin` to your User PATH variable. Restart your terminal.

151 

152 Verify the fix worked:

153 

154 ```batch theme={null}

155 claude --version

156 ```

157 </Tab>

158</Tabs>

159 

160### Check for conflicting installations

161 

162Multiple Claude Code installations can cause version mismatches or unexpected behavior. Check what's installed:

163 

164<Tabs>

165 <Tab title="macOS/Linux">

166 List all `claude` binaries found in your PATH:

167 

168 ```bash theme={null}

169 which -a claude

170 ```

171 

172 If this prints nothing, no `claude` is on your PATH yet. Go back to [Verify your PATH](#verify-your-path).

173 

174 Check the three locations a `claude` binary can come from. `~/.local/bin/claude` is the native installer, `~/.claude/local/` is a legacy local npm install created by older versions of Claude Code, and the npm global list shows a `-g` install:

175 

176 ```bash theme={null}

177 ls -la ~/.local/bin/claude

178 ```

179 

180 ```bash theme={null}

181 ls -la ~/.claude/local/

182 ```

183 

184 ```bash theme={null}

185 npm -g ls @anthropic-ai/claude-code 2>/dev/null

186 ```

187 </Tab>

188 

189 <Tab title="Windows PowerShell">

190 List all `claude` binaries found in your PATH:

191 

192 ```powershell theme={null}

193 where.exe claude

194 ```

195 

196 Check whether the native installer placed a binary:

197 

198 ```powershell theme={null}

199 Test-Path "$env:USERPROFILE\.local\bin\claude.exe"

200 ```

201 </Tab>

202</Tabs>

203 

204If you find multiple installations, keep only one. The native install at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows is recommended. Remove the extras:

205 

206Uninstall an npm global install:

207 

208```bash theme={null}

209npm uninstall -g @anthropic-ai/claude-code

210```

211 

212Remove the legacy local npm install:

213 

214```bash theme={null}

215rm -rf ~/.claude/local

216```

217 

218On Windows, use PowerShell:

219 

220```powershell theme={null}

221Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\local"

222```

223 

224Remove a Homebrew install on macOS. If you installed the `claude-code@latest` cask, substitute that name:

225 

226```bash theme={null}

227brew uninstall --cask claude-code

228```

229 

230Remove a WinGet install on Windows:

231 

232```powershell theme={null}

233winget uninstall Anthropic.ClaudeCode

234```

235 

236### Check directory permissions

237 

238The installer needs write access to `~/.local/bin/` and `~/.claude/` on macOS and Linux. On Windows the install location is under `%USERPROFILE%`, which is writable by your user by default, so this section rarely applies there.

239 

240Check whether the directories are writable:

241 

242```bash theme={null}

243test -w ~/.local/bin && echo "writable" || echo "not writable"

244test -w ~/.claude && echo "writable" || echo "not writable"

245```

246 

247If either directory isn't writable, create the install directory and set your user as the owner:

248 

249```bash theme={null}

250sudo mkdir -p ~/.local/bin

251sudo chown -R $(whoami) ~/.local

252```

253 

254### Verify the binary works

255 

256If `claude --version` prints a version but `claude` crashes or hangs on startup, run these checks to narrow down the cause. If `claude --version` says command not found, go to [Verify your PATH](#verify-your-path) first; the commands below assume `claude` is on your PATH.

257 

258Confirm the binary exists and is executable:

259 

260```bash theme={null}

261ls -la "$(command -v claude)"

262```

263 

264On Windows, use PowerShell:

265 

266```powershell theme={null}

267Get-Command claude | Select-Object Source

268```

269 

270On Linux, check for missing shared libraries. If `ldd` shows missing libraries, you may need to install system packages. On Alpine Linux and other musl-based distributions, see [Alpine Linux setup](/en/setup#alpine-linux-and-musl-based-distributions).

271 

272```bash theme={null}

273ldd "$(command -v claude)" | grep "not found"

274```

275 

276Confirm the binary can execute:

277 

278```bash theme={null}

279claude --version

280```

281 

282## Common installation issues

283 

284These are the most frequently encountered installation problems and their solutions.

285 

286### Install script returns HTML instead of a shell script

287 

288When running the install command, you may see one of these errors:

289 

290```text theme={null}

291bash: line 1: syntax error near unexpected token `<'

292bash: line 1: `<!DOCTYPE html>'

293```

294 

295On PowerShell, the same problem appears as:

296 

297```text theme={null}

298Invoke-Expression: Missing argument in parameter list.

299```

300 

301This means the install URL returned an HTML page instead of the install script. If the HTML page says "App unavailable in region," Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries).

302 

303Otherwise, this can happen due to network issues, regional routing, or a temporary service disruption.

304 

305**Solutions:**

306 

3071. **Use an alternative install method**:

308 

309 On macOS, install via Homebrew:

310 

311 ```bash theme={null}

312 brew install --cask claude-code

313 ```

314 

315 On Windows, install via WinGet:

316 

317 ```powershell theme={null}

318 winget install Anthropic.ClaudeCode

319 ```

320 

3212. **Retry after a few minutes**: the issue is often temporary. Wait and try the original command again.

322 

323### `command not found: claude` after installation

324 

325The install finished but `claude` doesn't work. The exact error varies by platform:

326 

327| Platform | Error message |

328| :---------- | :--------------------------------------------------------------------- |

329| macOS | `zsh: command not found: claude` |

330| Linux | `bash: claude: command not found` |

331| Windows CMD | `'claude' is not recognized as an internal or external command` |

332| PowerShell | `claude : The term 'claude' is not recognized as the name of a cmdlet` |

333 

334This means the install directory isn't in your shell's search path. See [Verify your PATH](#verify-your-path) for the fix on each platform.

335 

336### `curl: (56) Failure writing output to destination`

337 

338The `curl ... | bash` command downloads the script and pipes it to Bash for execution. This error means the connection broke before the script finished downloading. Common causes include network interruptions, the download being blocked mid-stream, or system resource limits.

339 

340**Solutions:**

341 

3421. **Check network stability**: Claude Code binaries are hosted at `downloads.claude.ai`. Test that you can reach it:

343 ```bash theme={null}

344 curl -sI https://downloads.claude.ai/claude-code-releases/latest

345 ```

346 An `HTTP/2 200` line means you reached the server and the original failure was likely intermittent; retry the install command. If you see `Could not resolve host` or a connection timeout, your network is blocking the download.

347 

3482. **Try an alternative install method**:

349 

350 On macOS:

351 

352 ```bash theme={null}

353 brew install --cask claude-code

354 ```

355 

356 On Windows:

357 

358 ```powershell theme={null}

359 winget install Anthropic.ClaudeCode

360 ```

361 

362### TLS or SSL connection errors

363 

364Errors like `curl: (35) TLS connect error`, `schannel: next InitializeSecurityContext failed`, or PowerShell's `Could not establish trust relationship for the SSL/TLS secure channel` indicate TLS handshake failures.

365 

366**Solutions:**

367 

3681. **Update your system CA certificates**:

369 

370 On Ubuntu/Debian:

371 

372 ```bash theme={null}

373 sudo apt-get update && sudo apt-get install ca-certificates

374 ```

375 

376 On macOS, the system curl uses the Keychain trust store; updating macOS itself updates the root certificates.

377 

3782. **On Windows, enable TLS 1.2** in PowerShell before running the installer:

379 ```powershell theme={null}

380 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

381 irm https://claude.ai/install.ps1 | iex

382 ```

383 

3843. **Check for proxy or firewall interference**: corporate proxies that perform TLS inspection can cause these errors, including `unable to get local issuer certificate` and `SELF_SIGNED_CERT_IN_CHAIN`. For the install step, point curl at your corporate CA bundle with `--cacert`:

385 ```bash theme={null}

386 curl --cacert /path/to/corporate-ca.pem -fsSL https://claude.ai/install.sh | bash

387 ```

388 For Claude Code itself once installed, set `NODE_EXTRA_CA_CERTS` so API requests trust the same bundle:

389 ```bash theme={null}

390 export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem

391 ```

392 Ask your IT team for the certificate file if you don't have it. You can also try on a direct connection to confirm the proxy is the cause.

393 

3944. **On Windows, bypass certificate revocation checks** if you see `CRYPT_E_NO_REVOCATION_CHECK (0x80092012)` or `CRYPT_E_REVOCATION_OFFLINE (0x80092013)`. These mean curl reached the server but your network blocks the certificate revocation lookup, which is common behind corporate firewalls. Add `--ssl-revoke-best-effort` to the install command:

395 ```batch theme={null}

396 curl --ssl-revoke-best-effort -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

397 ```

398 Alternatively, install with `winget install Anthropic.ClaudeCode`, which avoids curl entirely.

399 

400### `Failed to fetch version from downloads.claude.ai`

401 

402The installer couldn't reach the download server. This typically means `downloads.claude.ai` is blocked on your network.

403 

404**Solutions:**

405 

4061. **Test connectivity directly**:

407 ```bash theme={null}

408 curl -sI https://downloads.claude.ai/claude-code-releases/latest

409 ```

410 

4112. **If behind a proxy**, set `HTTPS_PROXY` so the installer can route through it. See [proxy configuration](/en/network-config#proxy-configuration) for details.

412 ```bash theme={null}

413 export HTTPS_PROXY=http://proxy.example.com:8080

414 curl -fsSL https://claude.ai/install.sh | bash

415 ```

416 

4173. **If on a restricted network**, try a different network or VPN, or use an alternative install method:

418 

419 On macOS:

420 

421 ```bash theme={null}

422 brew install --cask claude-code

423 ```

424 

425 On Windows:

426 

427 ```powershell theme={null}

428 winget install Anthropic.ClaudeCode

429 ```

430 

431### Wrong install command on Windows

432 

433If you see `'irm' is not recognized`, `The token '&&' is not valid`, or `'bash' is not recognized as the name of a cmdlet`, you copied the install command for a different shell or operating system.

434 

435* **`irm` not recognized**: you're in CMD, not PowerShell. You have two options:

436 

437 Open PowerShell by searching for "PowerShell" in the Start menu, then run the original install command:

438 

439 ```powershell theme={null}

440 irm https://claude.ai/install.ps1 | iex

441 ```

442 

443 Or stay in CMD and use the CMD installer instead:

444 

445 ```batch theme={null}

446 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

447 ```

448 

449* **`&&` not valid**: you're in PowerShell but ran the CMD installer command. Use the PowerShell installer:

450 ```powershell theme={null}

451 irm https://claude.ai/install.ps1 | iex

452 ```

453 

454* **`bash` not recognized**: you ran the macOS/Linux installer on Windows. Use the PowerShell installer instead:

455 ```powershell theme={null}

456 irm https://claude.ai/install.ps1 | iex

457 ```

458 

459### `The process cannot access the file` during Windows install

460 

461If the PowerShell installer fails with `Failed to download binary: The process cannot access the file ... because it is being used by another process`, the installer couldn't write to `%USERPROFILE%\.claude\downloads`. This usually means a previous install attempt is still running, or antivirus software is scanning a partially downloaded binary in that folder.

462 

463Close any other PowerShell windows running the installer and wait for antivirus scans to release the file. Then delete the downloads folder and run the installer again:

464 

465```powershell theme={null}

466Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\downloads"

467irm https://claude.ai/install.ps1 | iex

468```

469 

470### Install killed on low-memory Linux servers

471 

472If you see `Killed` during installation on a VPS or cloud instance:

473 

474```text theme={null}

475Setting up Claude Code...

476Installing Claude Code native build latest...

477bash: line 142: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}

478```

479 

480The Linux OOM killer terminated the process because the system ran out of memory. Claude Code requires at least 4 GB of available RAM.

481 

482**Solutions:**

483 

4841. **Add swap space** if your server has limited RAM. Swap uses disk space as overflow memory, letting the install complete even with low physical RAM.

485 

486 Create a 2 GB swap file and enable it:

487 

488 ```bash theme={null}

489 sudo fallocate -l 2G /swapfile

490 sudo chmod 600 /swapfile

491 sudo mkswap /swapfile

492 sudo swapon /swapfile

493 ```

494 

495 Then retry the installation:

496 

497 ```bash theme={null}

498 curl -fsSL https://claude.ai/install.sh | bash

499 ```

500 

5012. **Close other processes** to free memory before installing.

502 

5033. **Use a larger instance** if possible. Claude Code requires at least 4 GB of RAM.

504 

505### Install hangs in Docker

506 

507When installing Claude Code in a Docker container, installing as root into `/` can cause hangs.

508 

509**Solutions:**

510 

5111. **Set a working directory** before running the installer. When run from `/`, the installer scans the entire filesystem, which causes excessive memory usage. Setting `WORKDIR` limits the scan to a small directory:

512 ```dockerfile theme={null}

513 WORKDIR /tmp

514 RUN curl -fsSL https://claude.ai/install.sh | bash

515 ```

516 

5172. **Increase Docker memory limits** if using Docker Desktop:

518 ```bash theme={null}

519 docker build --memory=4g .

520 ```

521 

522### Claude Desktop overrides the `claude` command on Windows

523 

524If you installed an older version of Claude Desktop, it may register a `Claude.exe` in the `WindowsApps` directory that takes PATH priority over Claude Code CLI. Running `claude` opens the Desktop app instead of the CLI.

525 

526Update Claude Desktop to the latest version to fix this issue.

527 

528### Claude Code on Windows requires either Git for Windows (for bash) or PowerShell

529 

530Claude Code on native Windows needs at least one shell: either [Git for Windows](https://git-scm.com/downloads/win) for Bash, or PowerShell. When neither is found, this error appears at startup. If only PowerShell is found, Claude Code uses the PowerShell tool instead of Bash.

531 

532**If neither is installed**, install one:

533 

534* Git for Windows: download from [git-scm.com/downloads/win](https://git-scm.com/downloads/win). During setup, select "Add to PATH." Restart your terminal after installing.

535* PowerShell 7: download from [aka.ms/powershell](https://aka.ms/powershell).

536 

537**If Git is already installed** but Claude Code can't find it, set the path in your [settings.json file](/en/settings):

538 

539```json theme={null}

540{

541 "env": {

542 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

543 }

544}

545```

546 

547If your Git is installed somewhere else, find the path by running `where.exe git` in PowerShell and use the `bin\bash.exe` path from that directory.

548 

549### Claude Code does not support 32-bit Windows

550 

551Windows includes two PowerShell entries in the Start menu: `Windows PowerShell` and `Windows PowerShell (x86)`. The x86 entry runs as a 32-bit process and triggers this error even on a 64-bit machine. To check which case you're in, run this in the same window that produced the error:

552 

553```powershell theme={null}

554[Environment]::Is64BitOperatingSystem

555```

556 

557If this prints `True`, your operating system is fine. Close the window, open `Windows PowerShell` without the x86 suffix, and run the install command again.

558 

559If this prints `False`, you are on a 32-bit edition of Windows. Claude Code requires a 64-bit operating system. See the [system requirements](/en/setup#system-requirements).

560 

561### Linux musl or glibc binary mismatch

562 

563If you see errors about missing shared libraries like `libstdc++.so.6` or `libgcc_s.so.1` after installation, the installer may have downloaded the wrong binary variant for your system.

564 

565```text theme={null}

566Error loading shared library libstdc++.so.6: No such file or directory

567```

568 

569This can happen on glibc-based systems that have musl cross-compilation packages installed, causing the installer to misdetect the system as musl.

570 

571**Solutions:**

572 

5731. **Check which libc your system uses**:

574 ```bash theme={null}

575 ldd --version 2>&1 | head -1

576 ```

577 Output mentioning `GNU libc` or `GLIBC` means glibc. Output mentioning `musl` means musl.

578 

5792. **If you're on glibc but got the musl binary**, remove the installation and reinstall. You can also manually download the correct binary using the manifest at `https://downloads.claude.ai/claude-code-releases/{VERSION}/manifest.json`. File a [GitHub issue](https://github.com/anthropics/claude-code/issues) with the output of `ldd --version` and `ls /lib/libc.musl*`.

580 

5813. **If you're actually on musl**, such as Alpine Linux, install the required packages:

582 ```bash theme={null}

583 apk add libgcc libstdc++ ripgrep

584 ```

585 

586### `Illegal instruction`

587 

588If running `claude` or the installer prints `Illegal instruction`, the native binary uses CPU instructions your processor doesn't support. There are two distinct causes.

589 

590**Architecture mismatch.** The installer downloaded the wrong binary, for example x86 on an ARM server. Check with `uname -m` on macOS or Linux, or `$env:PROCESSOR_ARCHITECTURE` in PowerShell. If the result doesn't match the binary you received, [file a GitHub issue](https://github.com/anthropics/claude-code/issues) with the output.

591 

592**Missing AVX instruction set.** If your architecture is correct but you still see `Illegal instruction`, your CPU likely lacks AVX or another instruction the binary requires. This affects roughly pre-2013 Intel and AMD processors, and virtual machines where the hypervisor does not pass AVX through to the guest.

593 

594On a VPS or VM, run `grep -m1 -ow avx /proc/cpuinfo`; an empty result means AVX is not available to the guest.

595 

596There is no native-binary workaround; track [issue #50384](https://github.com/anthropics/claude-code/issues/50384) for status, and include your CPU model from `grep -m1 "model name" /proc/cpuinfo` on Linux or `sysctl -n machdep.cpu.brand_string` on macOS when reporting.

597 

598Alternative install methods download the same native binary and won't resolve either cause.

599 

600### `dyld: cannot load` on macOS

601 

602If you see `dyld: cannot load`, `dyld: Symbol not found`, or `Abort trap: 6` during installation, the binary is incompatible with your macOS version or hardware.

603 

604```text theme={null}

605dyld: cannot load 'claude-2.1.42-darwin-x64' (load command 0x80000034 is unknown)

606Abort trap: 6

607```

608 

609A `Symbol not found` error that references `libicucore` also indicates your macOS version is older than the binary supports:

610 

611```text theme={null}

612dyld: Symbol not found: _ubrk_clone

613 Referenced from: claude-darwin-x64 (which was built for Mac OS X 13.0)

614 Expected in: /usr/lib/libicucore.A.dylib

615```

616 

617**Solutions:**

618 

6191. **Check your macOS version**: Claude Code requires macOS 13.0 or later. Open the Apple menu and select About This Mac to check your version.

620 

6212. **Update macOS** if you're on an older version. The binary uses load commands and system libraries that older macOS versions don't support. Alternative install methods like Homebrew download the same binary and won't resolve this error.

622 

623### `Exec format error` on WSL1

624 

625If running `claude` in WSL prints `cannot execute binary file: Exec format error`, you're on WSL1 and hitting a known native-binary regression tracked in [issue #38788](https://github.com/anthropics/claude-code/issues/38788). The binary's program headers changed in a way WSL1's loader can't handle.

626 

627The cleanest fix is to convert your distribution to WSL2 from PowerShell:

628 

629```powershell theme={null}

630wsl --set-version <DistroName> 2

631```

632 

633If you need to stay on WSL1, invoke the binary through the dynamic linker. Add this function to `~/.bashrc` inside WSL, replacing the path if your home directory differs:

634 

635```bash theme={null}

636claude() {

637 /lib64/ld-linux-x86-64.so.2 "$(readlink -f "$HOME/.local/bin/claude")" "$@"

638}

639```

640 

641Then run `source ~/.bashrc` and retry `claude`.

642 

643### npm install errors in WSL

644 

645These issues apply if you installed Claude Code with `npm install -g` inside WSL. If you used the [native installer](/en/setup), skip this section.

646 

647**OS or platform detection issues.** If npm reports a platform mismatch during install, WSL is likely picking up the Windows `npm`. Run `npm config set os linux` first, then install with `npm install -g @anthropic-ai/claude-code --force`. Do not use `sudo`.

648 

649**`exec: node: not found` when running `claude`.** Your WSL environment is likely using the Windows installation of Node.js. Confirm with `which npm` and `which node`: paths starting with `/mnt/c/` are Windows binaries, while Linux paths start with `/usr/`. To fix this, install Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).

650 

651**nvm version conflicts.** If you have nvm installed in both WSL and Windows, switching Node versions in WSL may break because WSL imports the Windows PATH by default and the Windows nvm takes priority. The most common cause is that nvm isn't loaded in your shell. Add the nvm loader to `~/.bashrc` or `~/.zshrc`:

652 

653```bash theme={null}

654export NVM_DIR="$HOME/.nvm"

655[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

656[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

657```

658 

659Or load it in your current session:

660 

661```bash theme={null}

662source ~/.nvm/nvm.sh

663```

664 

665If nvm is loaded but Windows paths still take priority, prepend your Linux Node path explicitly:

666 

667```bash theme={null}

668export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH"

669```

670 

671<Warning>

672 Avoid disabling Windows PATH importing via `appendWindowsPath = false` as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.

673</Warning>

674 

675### Permission errors during installation

676 

677If the native installer fails with permission errors, the target directory may not be writable. See [Check directory permissions](#check-directory-permissions).

678 

679If you previously installed with npm and are hitting npm-specific permission errors, switch to the native installer:

680 

681```bash theme={null}

682curl -fsSL https://claude.ai/install.sh | bash

683```

684 

685### Native binary not found after npm install

686 

687The `@anthropic-ai/claude-code` npm package pulls in the native binary through a per-platform optional dependency such as `@anthropic-ai/claude-code-darwin-arm64`. If running `claude` after install prints `Could not find native binary package "@anthropic-ai/claude-code-<platform>"`, check the following causes:

688 

689* **Optional dependencies are disabled.** Remove `--omit=optional` from your npm install command, `--no-optional` from pnpm, or `--ignore-optional` from yarn, and check that `.npmrc` does not set `optional=false`. Then reinstall. The native binary is delivered only as an optional dependency, so there is no JavaScript fallback if it is skipped.

690* **Unsupported platform.** Prebuilt binaries are published for `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `linux-x64-musl`, `linux-arm64-musl`, `win32-x64`, and `win32-arm64`. Claude Code does not ship a binary for other platforms; see the [system requirements](/en/setup#system-requirements).

691* **Corporate npm mirror is missing the platform packages.** Ensure your registry mirrors all eight `@anthropic-ai/claude-code-*` platform packages in addition to the meta package.

692 

693Installing with `--ignore-scripts` does not trigger this error. The postinstall step that links the binary into place is skipped, so Claude Code falls back to a wrapper that locates and spawns the platform binary on each launch. This works but starts more slowly; reinstall with scripts enabled for direct execution.

694 

695## Login and authentication

696 

697These sections address login failures, OAuth errors, and token issues.

698 

699### Reset your login

700 

701When login fails and the cause isn't obvious, a clean re-authentication resolves most cases:

702 

7031. Run `/logout` to sign out completely

7042. Close Claude Code

7053. Restart with `claude` and complete the authentication process again

706 

707If the browser doesn't open automatically during login, press `c` to copy the OAuth URL to your clipboard, then paste it into a browser manually. This also works when the URL wraps across lines in a narrow or SSH terminal and can't be clicked directly.

708 

709### OAuth error: Invalid code

710 

711If you see `OAuth error: Invalid code. Please make sure the full code was copied`, the login code expired or was truncated during copy-paste.

712 

713**Solutions:**

714 

715* Press Enter to retry and complete the login quickly after the browser opens

716* Type `c` to copy the full URL if the browser doesn't open automatically

717* If using a remote/SSH session, the browser may open on the wrong machine. Copy the URL displayed in the terminal and open it in your local browser instead.

718 

719### 403 Forbidden after login

720 

721If you see `API Error: 403 {"error":{"type":"forbidden","message":"Request not allowed"}}` after logging in:

722 

723* **Claude Pro/Max users**: verify your subscription is active at [claude.ai/settings](https://claude.ai/settings)

724* **Anthropic Console users**: confirm your account has the "Claude Code" or "Developer" role. Admins assign this in the Anthropic Console under Settings → Members.

725* **Behind a proxy**: corporate proxies can interfere with API requests. See [network configuration](/en/network-config) for proxy setup.

726 

727### This organization has been disabled with an active subscription

728 

729If you see `API Error: 400 ... "This organization has been disabled"` despite having an active Claude subscription, an `ANTHROPIC_API_KEY` environment variable is overriding your subscription. This commonly happens when an old API key from a previous employer or project is still set in your shell profile.

730 

731When `ANTHROPIC_API_KEY` is present and you have approved it, Claude Code uses that key instead of your subscription's OAuth credentials. In non-interactive mode with the `-p` flag, the key is always used when present. See [authentication precedence](/en/authentication#authentication-precedence) for the full resolution order.

732 

733To use your subscription instead, unset the environment variable and remove it from your shell profile:

734 

735```bash theme={null}

736unset ANTHROPIC_API_KEY

737claude

738```

739 

740Check `~/.zshrc`, `~/.bashrc`, or `~/.profile` for `export ANTHROPIC_API_KEY=...` lines and remove them to make the change permanent. On Windows, check your PowerShell profile at `$PROFILE` and your User environment variables for `ANTHROPIC_API_KEY`. Run `/status` inside Claude Code to confirm which authentication method is active.

741 

742### OAuth login fails in WSL2, SSH, or containers

743 

744When Claude Code runs in WSL2, on a remote machine over SSH, or inside a container, the browser usually opens on a different host and its redirect can't reach Claude Code's local callback server. After you sign in, the browser shows a login code instead of redirecting back automatically. Paste that code into the terminal at the `Paste code here if prompted` prompt to complete login.

745 

746If the browser doesn't open at all from WSL2, set the `BROWSER` environment variable to your Windows browser path:

747 

748```bash theme={null}

749export BROWSER="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe"

750claude

751```

752 

753Alternatively, press `c` at the interactive login prompt to copy the OAuth URL, or copy the URL that `claude auth login` prints, and open it in a browser on your local machine.

754 

755If pasting the code into the interactive prompt does nothing, your terminal's paste binding likely isn't reaching the input field. Try your terminal's alternate paste shortcut, often right-click or Shift+Insert in Windows Terminal, or use `claude auth login` instead, which reads the pasted code from standard input:

756 

757```bash theme={null}

758claude auth login

759```

760 

761This fallback also applies on native Windows or any terminal where pasting into the interactive prompt fails.

762 

763### Not logged in or token expired

764 

765If Claude Code prompts you to log in again after a session, your OAuth token may have expired.

766 

767Run `/login` to re-authenticate. If this happens frequently, check that your system clock is accurate, as token validation depends on correct timestamps.

768 

769On macOS, login can also fail when the Keychain is locked or its password is out of sync with your account password, which prevents Claude Code from saving credentials. Run `claude doctor` to check Keychain access. To unlock the Keychain manually, run `security unlock-keychain ~/Library/Keychains/login.keychain-db`. If unlocking doesn't help, open Keychain Access, select the `login` keychain, and choose Edit > Change Password for Keychain "login" to resync it with your account password.

770 

771### Bedrock, Vertex, or Foundry credentials not loading

772 

773If you configured Claude Code to use a cloud provider and see `Could not load credentials from any providers` on Bedrock, `Could not load the default credentials` on Vertex, or `ChainedTokenCredential authentication failed` on Foundry, your cloud provider CLI is likely not authenticated in the current shell.

774 

775For Bedrock, confirm your AWS credentials are valid:

776 

777```bash theme={null}

778aws sts get-caller-identity

779```

780 

781For Vertex AI, confirm `ANTHROPIC_VERTEX_PROJECT_ID` and `CLOUD_ML_REGION` are set in your shell, then set application default credentials:

782 

783```bash theme={null}

784gcloud auth application-default login

785```

786 

787For Microsoft Foundry, confirm `ANTHROPIC_FOUNDRY_API_KEY` is set, or sign in with the Azure CLI so the default credential chain can find your account:

788 

789```bash theme={null}

790az login

791```

792 

793If credentials work in your terminal but not in the VS Code or JetBrains extension, the IDE process likely didn't inherit your shell environment. Set the provider environment variables in the IDE's own settings, or launch the IDE from a terminal where they're already exported.

794 

795See [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry) for full provider setup.

796 

797## Still stuck

798 

799If none of the above resolves your issue:

800 

8011. Check the [GitHub repository](https://github.com/anthropics/claude-code/issues) for known issues, or open a new one with your operating system, the install command you ran, and the full error output

8022. If `claude --version` works but something else is wrong, run `claude doctor` for an automated diagnostic report

8033. If you can start a session, use `/feedback` inside Claude Code to report the problem

troubleshooting.md +51 −906

Details

4 4 

5# Troubleshooting5# Troubleshooting

6 6 

7> Discover solutions to common issues with Claude Code installation and usage.7> Fix high CPU or memory usage, hangs, auto-compact thrashing, and search problems in Claude Code, and find the right page for other issues.

8 8 

9## Troubleshoot installation issues9This page covers performance, stability, and search problems once Claude Code is running. For other issues, start with the page that matches where you're stuck:

10 10 

11<Tip>11| Symptom | Go to |

12 If you'd rather skip the terminal entirely, the [Claude Code Desktop app](/en/desktop-quickstart) lets you install and use Claude Code through a graphical interface. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs) and start coding without any command-line setup.12| :------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------- |

13</Tip>13| `command not found`, install fails, PATH issues, `EACCES`, TLS errors | [Troubleshoot installation and login](/en/troubleshoot-install) |

14| Login loops, OAuth errors, `403 Forbidden`, "organization disabled", Bedrock/Vertex/Foundry credentials | [Troubleshoot installation and login](/en/troubleshoot-install#login-and-authentication) |

15| Settings not applying, hooks not firing, MCP servers not loading | [Debug your configuration](/en/debug-your-config) |

16| `API Error: 5xx`, `529 Overloaded`, `429`, request validation errors | [Error reference](/en/errors) |

17| `model not found` or `you may not have access to it` | [Error reference](/en/errors#theres-an-issue-with-the-selected-model) |

18| VS Code extension not connecting or detecting Claude | [VS Code integration](/en/vs-code#fix-common-issues) |

19| JetBrains plugin or IDE not detected | [JetBrains integration](/en/jetbrains#troubleshooting) |

20| High CPU or memory, slow responses, hangs, search not finding files | [Performance and stability](#performance-and-stability) below |

14 21 

15Find the error message or symptom you're seeing:22If you're not sure which applies, run `/doctor` inside Claude Code for an automated check of your installation, settings, MCP servers, and context usage. If `claude` won't start at all, run `claude doctor` from your shell instead.

16 

17| What you see | Solution |

18| :---------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------- |

19| `command not found: claude` or `'claude' is not recognized` | [Fix your PATH](#command-not-found-claude-after-installation) |

20| `syntax error near unexpected token '<'` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

21| `curl: (56) Failure writing output to destination` | [Download script first, then run it](#curl-56-failure-writing-output-to-destination) |

22| `Killed` during install on Linux | [Add swap space for low-memory servers](#install-killed-on-low-memory-linux-servers) |

23| `TLS connect error` or `SSL/TLS secure channel` | [Update CA certificates](#tls-or-ssl-connection-errors) |

24| `Failed to fetch version` or can't reach download server | [Check network and proxy settings](#check-network-connectivity) |

25| `irm is not recognized` or `&& is not valid` | [Use the right command for your shell](#windows-wrong-install-command) |

26| `'bash' is not recognized as the name of a cmdlet` | [Use the Windows installer command](#windows-wrong-install-command) |

27| `Claude Code on Windows requires git-bash` | [Install or configure Git Bash](#windows-claude-code-on-windows-requires-git-bash) |

28| `Claude Code does not support 32-bit Windows` | [Open Windows PowerShell, not the x86 entry](#windows-claude-code-does-not-support-32-bit-windows) |

29| `Error loading shared library` | [Wrong binary variant for your system](#linux-wrong-binary-variant-installed-musl/glibc-mismatch) |

30| `Illegal instruction` on Linux | [Architecture mismatch](#illegal-instruction-on-linux) |

31| `dyld: cannot load`, `dyld: Symbol not found`, or `Abort trap` on macOS | [Binary incompatibility](#dyld-cannot-load-on-macos) |

32| `Invoke-Expression: Missing argument in parameter list` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

33| `App unavailable in region` | Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries). |

34| `unable to get local issuer certificate` | [Configure corporate CA certificates](#tls-or-ssl-connection-errors) |

35| `OAuth error` or `403 Forbidden` | [Fix authentication](#authentication-issues) |

36 

37If your issue isn't listed, work through these diagnostic steps.

38 

39## Debug installation problems

40 

41### Check network connectivity

42 

43The installer downloads from `storage.googleapis.com`. Verify you can reach it:

44 

45```bash theme={null}

46curl -sI https://storage.googleapis.com

47```

48 

49If this fails, your network may be blocking the connection. Common causes:

50 

51* Corporate firewalls or proxies blocking Google Cloud Storage

52* Regional network restrictions: try a VPN or alternative network

53* TLS/SSL issues: update your system's CA certificates, or check if `HTTPS_PROXY` is configured

54 

55If you're behind a corporate proxy, set `HTTPS_PROXY` and `HTTP_PROXY` to your proxy's address before installing. Ask your IT team for the proxy URL if you don't know it, or check your browser's proxy settings.

56 

57This example sets both proxy variables, then runs the installer through your proxy:

58 

59```bash theme={null}

60export HTTP_PROXY=http://proxy.example.com:8080

61export HTTPS_PROXY=http://proxy.example.com:8080

62curl -fsSL https://claude.ai/install.sh | bash

63```

64 

65### Verify your PATH

66 

67If installation succeeded but you get a `command not found` or `not recognized` error when running `claude`, the install directory isn't in your PATH. Your shell searches for programs in directories listed in PATH, and the installer places `claude` at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows.

68 

69Check if the install directory is in your PATH by listing your PATH entries and filtering for `local/bin`:

70 

71<Tabs>

72 <Tab title="macOS/Linux">

73 ```bash theme={null}

74 echo $PATH | tr ':' '\n' | grep local/bin

75 ```

76 

77 If there's no output, the directory is missing. Add it to your shell configuration:

78 

79 ```bash theme={null}

80 # Zsh (macOS default)

81 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

82 source ~/.zshrc

83 

84 # Bash (Linux default)

85 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

86 source ~/.bashrc

87 ```

88 

89 Alternatively, close and reopen your terminal.

90 

91 Verify the fix worked:

92 

93 ```bash theme={null}

94 claude --version

95 ```

96 </Tab>

97 

98 <Tab title="Windows PowerShell">

99 ```powershell theme={null}

100 $env:PATH -split ';' | Select-String 'local\\bin'

101 ```

102 

103 If there's no output, add the install directory to your User PATH:

104 

105 ```powershell theme={null}

106 $currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')

107 [Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User')

108 ```

109 

110 Restart your terminal for the change to take effect.

111 

112 Verify the fix worked:

113 

114 ```powershell theme={null}

115 claude --version

116 ```

117 </Tab>

118 

119 <Tab title="Windows CMD">

120 ```batch theme={null}

121 echo %PATH% | findstr /i "local\bin"

122 ```

123 

124 If there's no output, open System Settings, go to Environment Variables, and add `%USERPROFILE%\.local\bin` to your User PATH variable. Restart your terminal.

125 

126 Verify the fix worked:

127 

128 ```batch theme={null}

129 claude --version

130 ```

131 </Tab>

132</Tabs>

133 

134### Check for conflicting installations

135 

136Multiple Claude Code installations can cause version mismatches or unexpected behavior. Check what's installed:

137 

138<Tabs>

139 <Tab title="macOS/Linux">

140 List all `claude` binaries found in your PATH:

141 

142 ```bash theme={null}

143 which -a claude

144 ```

145 

146 Check whether the native installer and npm versions are present:

147 

148 ```bash theme={null}

149 ls -la ~/.local/bin/claude

150 ```

151 

152 ```bash theme={null}

153 ls -la ~/.claude/local/

154 ```

155 

156 ```bash theme={null}

157 npm -g ls @anthropic-ai/claude-code 2>/dev/null

158 ```

159 </Tab>

160 

161 <Tab title="Windows PowerShell">

162 ```powershell theme={null}

163 where.exe claude

164 Test-Path "$env:LOCALAPPDATA\Claude Code\claude.exe"

165 ```

166 </Tab>

167</Tabs>

168 

169If you find multiple installations, keep only one. The native install at `~/.local/bin/claude` is recommended. Remove any extra installations:

170 

171Uninstall an npm global install:

172 

173```bash theme={null}

174npm uninstall -g @anthropic-ai/claude-code

175```

176 

177Remove a Homebrew install on macOS (use `claude-code@latest` if you installed that cask):

178 

179```bash theme={null}

180brew uninstall --cask claude-code

181```

182 

183### Check directory permissions

184 

185The installer needs write access to `~/.local/bin/` and `~/.claude/`. If installation fails with permission errors, check whether these directories are writable:

186 

187```bash theme={null}

188test -w ~/.local/bin && echo "writable" || echo "not writable"

189test -w ~/.claude && echo "writable" || echo "not writable"

190```

191 

192If either directory isn't writable, create the install directory and set your user as the owner:

193 

194```bash theme={null}

195sudo mkdir -p ~/.local/bin

196sudo chown -R $(whoami) ~/.local

197```

198 

199### Verify the binary works

200 

201If `claude` is installed but crashes or hangs on startup, run these checks to narrow down the cause.

202 

203Confirm the binary exists and is executable:

204 

205```bash theme={null}

206ls -la $(which claude)

207```

208 

209On Linux, check for missing shared libraries. If `ldd` shows missing libraries, you may need to install system packages. On Alpine Linux and other musl-based distributions, see [Alpine Linux setup](/en/setup#alpine-linux-and-musl-based-distributions).

210 

211```bash theme={null}

212ldd $(which claude) | grep "not found"

213```

214 

215Run a quick sanity check that the binary can execute:

216 

217```bash theme={null}

218claude --version

219```

220 

221## Common installation issues

222 

223These are the most frequently encountered installation problems and their solutions.

224 

225### Install script returns HTML instead of a shell script

226 

227When running the install command, you may see one of these errors:

228 

229```text theme={null}

230bash: line 1: syntax error near unexpected token `<'

231bash: line 1: `<!DOCTYPE html>'

232```

233 

234On PowerShell, the same problem appears as:

235 

236```text theme={null}

237Invoke-Expression: Missing argument in parameter list.

238```

239 

240This means the install URL returned an HTML page instead of the install script. If the HTML page says "App unavailable in region," Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries).

241 

242Otherwise, this can happen due to network issues, regional routing, or a temporary service disruption.

243 

244**Solutions:**

245 

2461. **Use an alternative install method**:

247 

248 On macOS or Linux, install via Homebrew:

249 

250 ```bash theme={null}

251 brew install --cask claude-code

252 ```

253 

254 On Windows, install via WinGet:

255 

256 ```powershell theme={null}

257 winget install Anthropic.ClaudeCode

258 ```

259 

2602. **Retry after a few minutes**: the issue is often temporary. Wait and try the original command again.

261 

262### `command not found: claude` after installation

263 

264The install finished but `claude` doesn't work. The exact error varies by platform:

265 

266| Platform | Error message |

267| :---------- | :--------------------------------------------------------------------- |

268| macOS | `zsh: command not found: claude` |

269| Linux | `bash: claude: command not found` |

270| Windows CMD | `'claude' is not recognized as an internal or external command` |

271| PowerShell | `claude : The term 'claude' is not recognized as the name of a cmdlet` |

272 

273This means the install directory isn't in your shell's search path. See [Verify your PATH](#verify-your-path) for the fix on each platform.

274 

275### `curl: (56) Failure writing output to destination`

276 

277The `curl ... | bash` command downloads the script and passes it directly to Bash for execution using a pipe (`|`). This error means the connection broke before the script finished downloading. Common causes include network interruptions, the download being blocked mid-stream, or system resource limits.

278 

279**Solutions:**

280 

2811. **Check network stability**: Claude Code binaries are hosted on Google Cloud Storage. Test that you can reach it:

282 ```bash theme={null}

283 curl -fsSL https://storage.googleapis.com -o /dev/null

284 ```

285 If the command completes silently, your connection is fine and the issue is likely intermittent. Retry the install command. If you see an error, your network may be blocking the download.

286 

2872. **Try an alternative install method**:

288 

289 On macOS or Linux:

290 

291 ```bash theme={null}

292 brew install --cask claude-code

293 ```

294 

295 On Windows:

296 

297 ```powershell theme={null}

298 winget install Anthropic.ClaudeCode

299 ```

300 

301### TLS or SSL connection errors

302 

303Errors like `curl: (35) TLS connect error`, `schannel: next InitializeSecurityContext failed`, or PowerShell's `Could not establish trust relationship for the SSL/TLS secure channel` indicate TLS handshake failures.

304 

305**Solutions:**

306 

3071. **Update your system CA certificates**:

308 

309 On Ubuntu/Debian:

310 

311 ```bash theme={null}

312 sudo apt-get update && sudo apt-get install ca-certificates

313 ```

314 

315 On macOS via Homebrew:

316 

317 ```bash theme={null}

318 brew install ca-certificates

319 ```

320 

3212. **On Windows, enable TLS 1.2** in PowerShell before running the installer:

322 ```powershell theme={null}

323 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

324 irm https://claude.ai/install.ps1 | iex

325 ```

326 

3273. **Check for proxy or firewall interference**: corporate proxies that perform TLS inspection can cause these errors, including `unable to get local issuer certificate`. Set `NODE_EXTRA_CA_CERTS` to your corporate CA certificate bundle:

328 ```bash theme={null}

329 export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem

330 ```

331 Ask your IT team for the certificate file if you don't have it. You can also try on a direct connection to confirm the proxy is the cause.

332 

3334. **On Windows, bypass certificate revocation checks** if you see `CRYPT_E_NO_REVOCATION_CHECK (0x80092012)` or `CRYPT_E_REVOCATION_OFFLINE (0x80092013)`. These mean curl reached the server but your network blocks the certificate revocation lookup, which is common behind corporate firewalls. Add `--ssl-revoke-best-effort` to the install command:

334 ```bat theme={null}

335 curl --ssl-revoke-best-effort -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

336 ```

337 Alternatively, install with `winget install Anthropic.ClaudeCode`, which avoids curl entirely.

338 

339### `Failed to fetch version from storage.googleapis.com`

340 

341The installer couldn't reach the download server. This typically means `storage.googleapis.com` is blocked on your network.

342 

343**Solutions:**

344 

3451. **Test connectivity directly**:

346 ```bash theme={null}

347 curl -sI https://storage.googleapis.com

348 ```

349 

3502. **If behind a proxy**, set `HTTPS_PROXY` so the installer can route through it. See [proxy configuration](/en/network-config#proxy-configuration) for details.

351 ```bash theme={null}

352 export HTTPS_PROXY=http://proxy.example.com:8080

353 curl -fsSL https://claude.ai/install.sh | bash

354 ```

355 

3563. **If on a restricted network**, try a different network or VPN, or use an alternative install method:

357 

358 On macOS or Linux:

359 

360 ```bash theme={null}

361 brew install --cask claude-code

362 ```

363 

364 On Windows:

365 

366 ```powershell theme={null}

367 winget install Anthropic.ClaudeCode

368 ```

369 

370### Windows: wrong install command

371 

372If you see `'irm' is not recognized`, `The token '&&' is not valid`, or `'bash' is not recognized as the name of a cmdlet`, you copied the install command for a different shell or operating system.

373 

374* **`irm` not recognized**: you're in CMD, not PowerShell. You have two options:

375 

376 Open PowerShell by searching for "PowerShell" in the Start menu, then run the original install command:

377 

378 ```powershell theme={null}

379 irm https://claude.ai/install.ps1 | iex

380 ```

381 

382 Or stay in CMD and use the CMD installer instead:

383 

384 ```batch theme={null}

385 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

386 ```

387 

388* **`&&` not valid**: you're in PowerShell but ran the CMD installer command. Use the PowerShell installer:

389 ```powershell theme={null}

390 irm https://claude.ai/install.ps1 | iex

391 ```

392 

393* **`bash` not recognized**: you ran the macOS/Linux installer on Windows. Use the PowerShell installer instead:

394 ```powershell theme={null}

395 irm https://claude.ai/install.ps1 | iex

396 ```

397 

398### Install killed on low-memory Linux servers

399 

400If you see `Killed` during installation on a VPS or cloud instance:

401 

402```text theme={null}

403Setting up Claude Code...

404Installing Claude Code native build latest...

405bash: line 142: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}

406```

407 

408The Linux OOM killer terminated the process because the system ran out of memory. Claude Code requires at least 4 GB of available RAM.

409 

410**Solutions:**

411 

4121. **Add swap space** if your server has limited RAM. Swap uses disk space as overflow memory, letting the install complete even with low physical RAM.

413 

414 Create a 2 GB swap file and enable it:

415 

416 ```bash theme={null}

417 sudo fallocate -l 2G /swapfile

418 sudo chmod 600 /swapfile

419 sudo mkswap /swapfile

420 sudo swapon /swapfile

421 ```

422 

423 Then retry the installation:

424 

425 ```bash theme={null}

426 curl -fsSL https://claude.ai/install.sh | bash

427 ```

428 

4292. **Close other processes** to free memory before installing.

430 

4313. **Use a larger instance** if possible. Claude Code requires at least 4 GB of RAM.

432 

433### Install hangs in Docker

434 

435When installing Claude Code in a Docker container, installing as root into `/` can cause hangs.

436 

437**Solutions:**

438 

4391. **Set a working directory** before running the installer. When run from `/`, the installer scans the entire filesystem, which causes excessive memory usage. Setting `WORKDIR` limits the scan to a small directory:

440 ```dockerfile theme={null}

441 WORKDIR /tmp

442 RUN curl -fsSL https://claude.ai/install.sh | bash

443 ```

444 

4452. **Increase Docker memory limits** if using Docker Desktop:

446 ```bash theme={null}

447 docker build --memory=4g .

448 ```

449 

450### Windows: Claude Desktop overrides `claude` CLI command

451 

452If you installed an older version of Claude Desktop, it may register a `Claude.exe` in the `WindowsApps` directory that takes PATH priority over Claude Code CLI. Running `claude` opens the Desktop app instead of the CLI.

453 

454Update Claude Desktop to the latest version to fix this issue.

455 

456### Windows: Claude Code on Windows requires git-bash

457 

458Claude Code on native Windows needs [Git for Windows](https://git-scm.com/downloads/win), which includes Git Bash.

459 

460**If Git is not installed**, download and install it from [git-scm.com/downloads/win](https://git-scm.com/downloads/win). During setup, select "Add to PATH." Restart your terminal after installing.

461 

462**If Git is already installed** but Claude Code still can't find it, set the path in your [settings.json file](/en/settings):

463 

464```json theme={null}

465{

466 "env": {

467 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

468 }

469}

470```

471 

472If your Git is installed somewhere else, find the path by running `where.exe git` in PowerShell and use the `bin\bash.exe` path from that directory.

473 

474### Windows: Claude Code does not support 32-bit Windows

475 

476Windows includes two PowerShell entries in the Start menu: `Windows PowerShell` and `Windows PowerShell (x86)`. The x86 entry runs as a 32-bit process and triggers this error even on a 64-bit machine. To check which case you're in, run this in the same window that produced the error:

477 

478```powershell theme={null}

479[Environment]::Is64BitOperatingSystem

480```

481 

482If this prints `True`, your operating system is fine. Close the window, open `Windows PowerShell` without the x86 suffix, and run the install command again.

483 

484If this prints `False`, you are on a 32-bit edition of Windows. Claude Code requires a 64-bit operating system. See the [system requirements](/en/setup#system-requirements).

485 

486### Linux: wrong binary variant installed (musl/glibc mismatch)

487 

488If you see errors about missing shared libraries like `libstdc++.so.6` or `libgcc_s.so.1` after installation, the installer may have downloaded the wrong binary variant for your system.

489 

490```text theme={null}

491Error loading shared library libstdc++.so.6: No such file or directory

492```

493 

494This can happen on glibc-based systems that have musl cross-compilation packages installed, causing the installer to misdetect the system as musl.

495 

496**Solutions:**

497 

4981. **Check which libc your system uses**:

499 ```bash theme={null}

500 ldd /bin/ls | head -1

501 ```

502 If it shows `linux-vdso.so` or references to `/lib/x86_64-linux-gnu/`, you're on glibc. If it shows `musl`, you're on musl.

503 

5042. **If you're on glibc but got the musl binary**, remove the installation and reinstall. You can also manually download the correct binary from the GCS bucket at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json`. File a [GitHub issue](https://github.com/anthropics/claude-code/issues) with the output of `ldd /bin/ls` and `ls /lib/libc.musl*`.

505 

5063. **If you're actually on musl** (Alpine Linux), install the required packages:

507 ```bash theme={null}

508 apk add libgcc libstdc++ ripgrep

509 ```

510 

511### `Illegal instruction` on Linux

512 

513If the installer prints `Illegal instruction` instead of the OOM `Killed` message, the downloaded binary doesn't match your CPU architecture. This commonly happens on ARM servers that receive an x86 binary, or on older CPUs that lack required instruction sets.

514 

515```text theme={null}

516bash: line 142: 2238232 Illegal instruction "$binary_path" install ${TARGET:+"$TARGET"}

517```

518 

519**Solutions:**

520 

5211. **Verify your architecture**:

522 ```bash theme={null}

523 uname -m

524 ```

525 `x86_64` means 64-bit Intel/AMD, `aarch64` means ARM64. If the binary doesn't match, [file a GitHub issue](https://github.com/anthropics/claude-code/issues) with the output.

526 

5272. **Try an alternative install method** while the architecture issue is resolved:

528 ```bash theme={null}

529 brew install --cask claude-code

530 ```

531 

532### `dyld: cannot load` on macOS

533 

534If you see `dyld: cannot load`, `dyld: Symbol not found`, or `Abort trap: 6` during installation, the binary is incompatible with your macOS version or hardware.

535 

536```text theme={null}

537dyld: cannot load 'claude-2.1.42-darwin-x64' (load command 0x80000034 is unknown)

538Abort trap: 6

539```

540 

541A `Symbol not found` error that references `libicucore` also indicates your macOS version is older than the binary supports:

542 

543```text theme={null}

544dyld: Symbol not found: _ubrk_clone

545 Referenced from: claude-darwin-x64 (which was built for Mac OS X 13.0)

546 Expected in: /usr/lib/libicucore.A.dylib

547```

548 

549**Solutions:**

550 

5511. **Check your macOS version**: Claude Code requires macOS 13.0 or later. Open the Apple menu and select About This Mac to check your version.

552 

5532. **Update macOS** if you're on an older version. The binary uses load commands that older macOS versions don't support.

554 

5553. **Try Homebrew** as an alternative install method:

556 ```bash theme={null}

557 brew install --cask claude-code

558 ```

559 

560### Windows installation issues: errors in WSL

561 

562You might encounter the following issues in WSL:

563 

564**OS/platform detection issues**: if you receive an error during installation, WSL may be using Windows `npm`. Try:

565 

566* Run `npm config set os linux` before installation

567* Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check`. Do not use `sudo`.

568 

569**Node not found errors**: if you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).

570 

571**nvm version conflicts**: if you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation.

572 

573You can identify this issue by:

574 

575* Running `which npm` and `which node` - if they point to Windows paths (starting with `/mnt/c/`), Windows versions are being used

576* Experiencing broken functionality after switching Node versions with nvm in WSL

577 

578To resolve this issue, fix your Linux PATH to ensure the Linux node/npm versions take priority:

579 

580**Primary solution: Ensure nvm is properly loaded in your shell**

581 

582The most common cause is that nvm isn't loaded in non-interactive shells. Add the following to your shell configuration file (`~/.bashrc`, `~/.zshrc`, etc.):

583 

584```bash theme={null}

585# Load nvm if it exists

586export NVM_DIR="$HOME/.nvm"

587[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

588[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

589```

590 

591Or run directly in your current session:

592 

593```bash theme={null}

594source ~/.nvm/nvm.sh

595```

596 

597**Alternative: Adjust PATH order**

598 

599If nvm is properly loaded but Windows paths still take priority, you can explicitly prepend your Linux paths to PATH in your shell configuration:

600 

601```bash theme={null}

602export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH"

603```

604 

605<Warning>

606 Avoid disabling Windows PATH importing via `appendWindowsPath = false` as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.

607</Warning>

608 

609### WSL2 sandbox setup

610 

611[Sandboxing](/en/sandboxing) is supported on WSL2 but requires installing additional packages. If you see an error about missing `bubblewrap` or `socat` when running `/sandbox`, install the dependencies:

612 

613<Tabs>

614 <Tab title="Ubuntu/Debian">

615 ```bash theme={null}

616 sudo apt-get install bubblewrap socat

617 ```

618 </Tab>

619 

620 <Tab title="Fedora">

621 ```bash theme={null}

622 sudo dnf install bubblewrap socat

623 ```

624 </Tab>

625</Tabs>

626 

627WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing.

628 

629Sandboxed commands cannot launch Windows binaries such as `cmd.exe`, `powershell.exe`, or executables under `/mnt/c/`. WSL hands these off to the Windows host over a Unix socket, which the sandbox blocks. If a command needs to invoke a Windows binary, add it to [`excludedCommands`](/en/settings#sandbox-settings) so it runs outside the sandbox.

630 

631### Permission errors during installation

632 

633If the native installer fails with permission errors, the target directory may not be writable. See [Check directory permissions](#check-directory-permissions).

634 

635If you previously installed with npm and are hitting npm-specific permission errors, switch to the native installer:

636 

637```bash theme={null}

638curl -fsSL https://claude.ai/install.sh | bash

639```

640 

641## Permissions and authentication

642 

643These sections address login failures, token issues, and permission prompt behavior.

644 

645### Repeated permission prompts

646 

647If you find yourself repeatedly approving the same commands, you can allow specific tools

648to run without approval using the `/permissions` command. See [Permissions docs](/en/permissions#manage-permissions).

649 

650### Authentication issues

651 

652If you're experiencing authentication problems:

653 

6541. Run `/logout` to sign out completely

6552. Close Claude Code

6563. Restart with `claude` and complete the authentication process again

657 

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

659 

660### OAuth error: Invalid code

661 

662If you see `OAuth error: Invalid code. Please make sure the full code was copied`, the login code expired or was truncated during copy-paste.

663 

664**Solutions:**

665 

666* Press Enter to retry and complete the login quickly after the browser opens

667* Type `c` to copy the full URL if the browser doesn't open automatically

668* If using a remote/SSH session, the browser may open on the wrong machine. Copy the URL displayed in the terminal and open it in your local browser instead.

669 

670### 403 Forbidden after login

671 

672If you see `API Error: 403 {"error":{"type":"forbidden","message":"Request not allowed"}}` after logging in:

673 

674* **Claude Pro/Max users**: verify your subscription is active at [claude.ai/settings](https://claude.ai/settings)

675* **Console users**: confirm your account has the "Claude Code" or "Developer" role assigned by your admin

676* **Behind a proxy**: corporate proxies can interfere with API requests. See [network configuration](/en/network-config) for proxy setup.

677 

678### Model not found or not accessible

679 

680If you see `There's an issue with the selected model (...). It may not exist or you may not have access to it`, the API rejected the configured model name.

681 

682Common causes:

683 

684* A typo in the model name passed to `--model`

685* A stale or deprecated model ID saved in your settings

686* An API key without access to that model on your current usage tier

687 

688Check where the model is set, in [priority order](/en/model-config#setting-your-model):

689 

690* The `--model` flag

691* The `ANTHROPIC_MODEL` environment variable

692* The `model` field in `.claude/settings.local.json`

693* The `model` field in your project's `.claude/settings.json`

694* The `model` field in `~/.claude/settings.json`

695 

696To clear a stale value, remove the `model` field from your settings or unset `ANTHROPIC_MODEL`, and Claude Code will fall back to the default model for your account.

697 

698To browse models available to your account, start `claude` interactively and run `/model` to open the picker. For Vertex AI deployments, see [the Vertex AI troubleshooting section](/en/google-vertex-ai#troubleshooting).

699 

700### This organization has been disabled with an active subscription

701 

702If you see `API Error: 400 ... "This organization has been disabled"` despite having an active Claude subscription, an `ANTHROPIC_API_KEY` environment variable is overriding your subscription. This commonly happens when an old API key from a previous employer or project is still set in your shell profile.

703 

704When `ANTHROPIC_API_KEY` is present and you have approved it, Claude Code uses that key instead of your subscription's OAuth credentials. In non-interactive mode (`-p`), the key is always used when present. See [authentication precedence](/en/authentication#authentication-precedence) for the full resolution order.

705 

706To use your subscription instead, unset the environment variable and remove it from your shell profile:

707 

708```bash theme={null}

709unset ANTHROPIC_API_KEY

710claude

711```

712 

713Check `~/.zshrc`, `~/.bashrc`, or `~/.profile` for `export ANTHROPIC_API_KEY=...` lines and remove them to make the change permanent. Run `/status` inside Claude Code to confirm which authentication method is active.

714 

715### OAuth login fails in WSL2

716 

717Browser-based login in WSL2 may fail if WSL can't open your Windows browser. Set the `BROWSER` environment variable:

718 

719```bash theme={null}

720export BROWSER="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe"

721claude

722```

723 

724Or copy the URL manually: when the login prompt appears, press `c` to copy the OAuth URL, then paste it into your Windows browser.

725 

726### Not logged in or token expired

727 

728If Claude Code prompts you to log in again after a session, your OAuth token may have expired.

729 

730Run `/login` to re-authenticate. If this happens frequently, check that your system clock is accurate, as token validation depends on correct timestamps.

731 

732On macOS, login can also fail when the Keychain is locked or its password is out of sync with your account password, which prevents Claude Code from saving credentials. Run `claude doctor` to check Keychain access. To unlock the Keychain manually, run `security unlock-keychain ~/Library/Keychains/login.keychain-db`. If unlocking doesn't help, open Keychain Access, select the `login` keychain, and choose Edit > Change Password for Keychain "login" to resync it with your account password.

733 

734## Configuration file locations

735 

736Claude Code stores configuration in several locations:

737 

738| File | Purpose |

739| :---------------------------- | :----------------------------------------------------------------------------------------------------- |

740| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |

741| `.claude/settings.json` | Project settings (checked into source control) |

742| `.claude/settings.local.json` | Local project settings (not committed) |

743| `~/.claude.json` | Global state (theme, OAuth, MCP servers) |

744| `.mcp.json` | Project MCP servers (checked into source control) |

745| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |

746| Managed settings | [Managed settings](/en/settings#settings-files) (server-managed, MDM/OS-level policies, or file-based) |

747 

748On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`.

749 

750For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp).

751 

752### Resetting configuration

753 

754To reset Claude Code to default settings, you can remove the configuration files:

755 

756```bash theme={null}

757# Reset all user settings and state

758rm ~/.claude.json

759rm -rf ~/.claude/

760 

761# Reset project-specific settings

762rm -rf .claude/

763rm .mcp.json

764```

765 

766<Warning>

767 This will remove all your settings, MCP server configurations, and session history.

768</Warning>

769 23 

770## Performance and stability24## Performance and stability

771 25 


7792. Close and restart Claude Code between major tasks332. Close and restart Claude Code between major tasks

7803. Consider adding large build directories to your `.gitignore` file343. Consider adding large build directories to your `.gitignore` file

781 35 

36If memory usage stays high after these steps, run `/heapdump` to write a JavaScript heap snapshot and a memory breakdown to `~/Desktop`. On Linux without a Desktop folder, the files are written to your home directory.

37 

38The breakdown shows resident set size, JS heap, array buffers, and unaccounted native memory, which helps identify whether the growth is in JavaScript objects or in native code. To inspect retainers, open the `.heapsnapshot` file in Chrome DevTools under Memory → Load. Attach both files when reporting a memory issue on [GitHub](https://github.com/anthropics/claude-code/issues).

39 

782### Auto-compaction stops with a thrashing error40### Auto-compaction stops with a thrashing error

783 41 

784If you see `Autocompact is thrashing: the context refilled to the limit...`, automatic compaction succeeded but a file or tool output immediately refilled the context window several times in a row. Claude Code stops retrying to avoid wasting API calls on a loop that isn't making progress.42If you see `Autocompact is thrashing: the context refilled to the limit...`, automatic compaction succeeded but a file or tool output immediately refilled the context window several times in a row. Claude Code stops retrying to avoid wasting API calls on a loop that isn't making progress.


7971. Press Ctrl+C to attempt to cancel the current operation551. Press Ctrl+C to attempt to cancel the current operation

7982. If unresponsive, you may need to close the terminal and restart562. If unresponsive, you may need to close the terminal and restart

799 57 

58Restarting doesn't lose your conversation. Run `claude --resume` in the same directory to pick the session back up.

59 

800### Search and discovery issues60### Search and discovery issues

801 61 

802If Search tool, `@file` mentions, custom agents, and custom skills aren't working, install system `ripgrep`:62If the Search tool, `@file` mentions, custom agents, or custom skills aren't finding files, the bundled `ripgrep` binary may not run on your system. Install your platform's `ripgrep` package and tell Claude Code to use it instead:

803 63 

804```bash theme={null}64<Tabs>

805# macOS (Homebrew) 65 <Tab title="macOS">

806brew install ripgrep66 ```bash theme={null}

67 brew install ripgrep

68 ```

69 </Tab>

807 70 

808# Windows (winget)71 <Tab title="Ubuntu/Debian">

809winget install BurntSushi.ripgrep.MSVC72 ```bash theme={null}

73 sudo apt install ripgrep

74 ```

75 </Tab>

810 76 

811# Ubuntu/Debian77 <Tab title="Alpine">

812sudo apt install ripgrep78 ```bash theme={null}

79 apk add ripgrep

80 ```

81 </Tab>

813 82 

814# Alpine Linux83 <Tab title="Arch">

815apk add ripgrep84 ```bash theme={null}

85 pacman -S ripgrep

86 ```

87 </Tab>

816 88 

817# Arch Linux89 <Tab title="Windows">

818pacman -S ripgrep90 ```powershell theme={null}

819```91 winget install BurntSushi.ripgrep.MSVC

92 ```

93 </Tab>

94</Tabs>

820 95 

821Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/env-vars).96Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/env-vars).

822 97 


836 111 

8373. **Use native Windows instead**: consider running Claude Code natively on Windows instead of through WSL, for better file system performance.1123. **Use native Windows instead**: consider running Claude Code natively on Windows instead of through WSL, for better file system performance.

838 113 

839## IDE integration issues

840 

841If Claude Code does not connect to your IDE or behaves unexpectedly within an IDE terminal, try the solutions below.

842 

843### JetBrains IDE not detected on WSL2

844 

845If you're using Claude Code on WSL2 with JetBrains IDEs and getting "No available IDEs detected" errors, this is likely due to WSL2's networking configuration or Windows Firewall blocking the connection.

846 

847#### WSL2 networking modes

848 

849WSL2 uses NAT networking by default, which can prevent IDE detection. You have two options:

850 

851**Option 1: Configure Windows Firewall** (recommended)

852 

8531. Find your WSL2 IP address:

854 ```bash theme={null}

855 wsl hostname -I

856 # Example output: 172.21.123.45

857 ```

858 

8592. Open PowerShell as Administrator and create a firewall rule:

860 ```powershell theme={null}

861 New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16

862 ```

863 Adjust the IP range based on your WSL2 subnet from step 1.

864 

8653. Restart both your IDE and Claude Code

866 

867**Option 2: Switch to mirrored networking**

868 

869Add to `.wslconfig` in your Windows user directory:

870 

871```ini theme={null}

872[wsl2]

873networkingMode=mirrored

874```

875 

876Then restart WSL with `wsl --shutdown` from PowerShell.

877 

878<Note>

879 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.

880</Note>

881 

882For additional JetBrains configuration tips, see the [JetBrains IDE guide](/en/jetbrains#plugin-settings).

883 

884### Report Windows IDE integration issues

885 

886If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information:

887 

888* Environment type: native Windows (Git Bash) or WSL1/WSL2

889* WSL networking mode, if applicable: NAT or mirrored

890* IDE name and version

891* Claude Code extension/plugin version

892* Shell type: Bash, Zsh, PowerShell, etc.

893 

894### Escape key not working in JetBrains IDE terminals

895 

896If you're using Claude Code in JetBrains terminals and the `Esc` key doesn't interrupt the agent as expected, this is likely due to a keybinding clash with JetBrains' default shortcuts.

897 

898To fix this issue:

899 

9001. Go to Settings → Tools → Terminal

9012. Either:

902 * Uncheck "Move focus to the editor with Escape", or

903 * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut

9043. Apply the changes

905 

906This allows the `Esc` key to properly interrupt Claude Code operations.

907 

908## Markdown formatting issues

909 

910Claude Code sometimes generates markdown files with missing language tags on code fences, which can affect syntax highlighting and readability in GitHub, editors, and documentation tools.

911 

912### Missing language tags in code blocks

913 

914If you notice code blocks like this in generated markdown:

915 

916````markdown theme={null}

917```

918function example() {

919 return "hello";

920}

921```

922````

923 

924Instead of properly tagged blocks like:

925 

926````markdown theme={null}

927```javascript

928function example() {

929 return "hello";

930}

931```

932````

933 

934**Solutions:**

935 

9361. **Ask Claude to add language tags**: request "Add appropriate language tags to all code blocks in this markdown file."

937 

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

939 

9403. **Manual verification**: after generating markdown files, review them for proper code block formatting and request corrections if needed.

941 

942### Inconsistent spacing and formatting

943 

944If generated markdown has excessive blank lines or inconsistent spacing:

945 

946**Solutions:**

947 

9481. **Request formatting corrections**: ask Claude to "Fix spacing and formatting issues in this markdown file."

949 

9502. **Use formatting tools**: set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files.

951 

9523. **Specify formatting preferences**: include formatting requirements in your prompts or project [memory](/en/memory) files.

953 

954### Reduce markdown formatting issues

955 

956To minimize formatting issues:

957 

958* **Be explicit in requests**: ask for "properly formatted markdown with language-tagged code blocks"

959* **Use project conventions**: document your preferred markdown style in [`CLAUDE.md`](/en/memory)

960* **Set up validation hooks**: use post-processing hooks to automatically verify and fix common formatting issues

961 

962## Get more help114## Get more help

963 115 

964If you're experiencing issues not covered here:116If you're experiencing issues not covered here:

965 117 

9661. Use the `/feedback` command within Claude Code to report problems directly to Anthropic1181. Run `/doctor` to check installation health, settings validity, MCP configuration, and context usage in one pass

9672. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues1192. Use the `/feedback` command within Claude Code to report problems directly to Anthropic

9683. Run `/doctor` to diagnose issues. It checks:1203. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues

969 * Installation type, version, and search functionality1214. Ask Claude directly about its capabilities and features. Claude has built-in access to its documentation.

970 * Auto-update status and available versions

971 * Invalid settings files (malformed JSON, incorrect types)

972 * MCP server configuration errors

973 * Keybinding configuration problems

974 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)

975 * Plugin and agent loading errors

9764. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation

ultraplan.md +1 −0

Details

80 80 

81* [Claude Code on the web](/en/claude-code-on-the-web): the cloud infrastructure ultraplan runs on81* [Claude Code on the web](/en/claude-code-on-the-web): the cloud infrastructure ultraplan runs on

82* [Plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode): how planning works in a local session82* [Plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode): how planning works in a local session

83* [Find bugs with ultrareview](/en/ultrareview): the code review counterpart to ultraplan for catching issues before merge

83* [Remote Control](/en/remote-control): use the claude.ai/code interface with a session running on your own machine84* [Remote Control](/en/remote-control): use the claude.ai/code interface with a session running on your own machine

ultrareview.md +108 −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# Find bugs with ultrareview

6 

7> Run a deep, multi-agent code review in the cloud with /ultrareview to find and verify bugs before you merge.

8 

9<Note>

10 Ultrareview is a research preview feature available in Claude Code v2.1.86 and later. The feature, pricing, and availability may change based on feedback.

11</Note>

12 

13Ultrareview is a deep code review that runs on Claude Code on the web infrastructure. When you run `/ultrareview`, Claude Code launches a fleet of reviewer agents in a remote sandbox to find bugs in your branch or pull request.

14 

15Compared to a local `/review`, ultrareview offers:

16 

17* **Higher signal**: every reported finding is independently reproduced and verified, so the results focus on real bugs rather than style suggestions

18* **Broader coverage**: many reviewer agents explore the change in parallel, which surfaces issues that a single-pass review can miss

19* **No local resource use**: the review runs entirely in a remote sandbox, so your terminal stays free for other work while it runs

20 

21Ultrareview requires authentication with a Claude.ai account because it runs on Claude Code on the web infrastructure. If you are signed in with an API key only, run `/login` and authenticate with Claude.ai first. Ultrareview is not available when using Claude Code with Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry, and it is not available to organizations that have enabled Zero Data Retention.

22 

23## Run ultrareview from the CLI

24 

25Start a review from any git repository in the Claude Code CLI.

26 

27```text theme={null}

28/ultrareview

29```

30 

31Without arguments, ultrareview reviews the diff between your current branch and the default branch, including any uncommitted and staged changes in your working tree. Claude Code bundles the repository state and uploads it to a remote sandbox for the review.

32 

33To review a GitHub pull request instead, pass the PR number.

34 

35```text theme={null}

36/ultrareview 1234

37```

38 

39In PR mode, the remote sandbox clones the pull request directly from GitHub rather than bundling your local working tree. PR mode requires a `github.com` remote on the repository.

40 

41<Tip>

42 If your repository is too large to bundle, Claude Code prompts you to use PR mode instead. Push your branch and open a draft PR, then run `/ultrareview <PR-number>`.

43</Tip>

44 

45Before launching, Claude Code shows a confirmation dialog with the review scope (including the file and line count when reviewing a branch), your remaining free runs, and the estimated cost. After you confirm, the review continues in the background and you can keep using your session. The command runs only when you invoke it with `/ultrareview`; Claude does not start an ultrareview on its own.

46 

47## Pricing and free runs

48 

49Ultrareview is a premium feature that bills against extra usage rather than your plan's included usage.

50 

51| Plan | Included free runs | After free runs |

52| ------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------- |

53| Pro | 3 free runs through May 5, 2026 | billed as [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

54| Max | 3 free runs through May 5, 2026 | billed as [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

55| Team and Enterprise | none | billed as [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

56 

57Pro and Max subscribers receive three free ultrareview runs to try the feature. These three runs are a one-time allotment per account, do not refresh, and expire on May 5, 2026. After you use all three, or after the free run period ends, each review is billed to extra usage and typically costs \$5 to \$20 depending on the size of the change. A run counts once the remote session starts, so a review that you stop early or that fails to complete still uses a free run. For a paid review, extra usage is billed only for the portion that ran.

58 

59Because ultrareview always bills as extra usage outside the free runs, your account or organization must have extra usage enabled before you can launch a paid review. If extra usage is not enabled, Claude Code blocks the launch and links you to the billing settings where you can turn it on. You can also run `/extra-usage` to check or change your current setting.

60 

61## Track a running review

62 

63A review typically takes 5 to 10 minutes. The review runs as a background task, so you can keep working in your session, start other commands, or close the terminal entirely.

64 

65Use `/tasks` to see running and completed reviews, open the detail view for a review, or stop a review that is in progress. Stopping a review archives the cloud session, and partial findings are not returned. When the review finishes, the verified findings appear as a notification in your session. Each finding includes the file location and an explanation of the issue so you can ask Claude to fix it directly.

66 

67## Run ultrareview non-interactively

68 

69Use the `claude ultrareview` subcommand to start an ultrareview from CI or a script without an interactive session. The subcommand launches the same review as `/ultrareview`, blocks until the remote review finishes, prints the findings to stdout, and exits with code 0 on success or 1 on failure.

70 

71```bash theme={null}

72claude ultrareview

73claude ultrareview 1234

74claude ultrareview origin/main

75```

76 

77Without arguments, the subcommand reviews the diff between your current branch and the default branch. Pass a PR number to review a pull request, or pass a base branch to review the diff against that branch instead. Invoking the subcommand counts as consent for the billing and terms prompt that the interactive command shows.

78 

79Progress messages and the live session URL go to stderr so stdout stays parseable. Use these flags to control the output and timeout:

80 

81| Flag | Description |

82| --------------------- | ------------------------------------------------------------------- |

83| `--json` | Print the raw `bugs.json` payload instead of the formatted findings |

84| `--timeout <minutes>` | Maximum minutes to wait for the review to finish. Defaults to 30 |

85 

86Running `claude ultrareview` requires the same authentication and extra usage configuration as `/ultrareview`. The subcommand exits with code 0 when the review completes with or without findings, code 1 when the review fails to launch, the remote session errors, or the timeout elapses, and code 130 when interrupted with Ctrl-C. The remote review keeps running if you interrupt the subcommand; follow the session URL printed to stderr to watch it in the browser.

87 

88For automatic reviews on GitHub pull requests, [Code Review](/en/code-review) integrates with your repository directly and posts findings as inline PR comments without a CLI step.

89 

90## How ultrareview compares to /review

91 

92Both commands review code, but they target different stages of your workflow.

93 

94| | `/review` | `/ultrareview` |

95| -------- | ------------------------------ | ------------------------------------------------------------- |

96| Runs | locally in your session | remotely in a cloud sandbox |

97| Depth | single-pass review | multi-agent fleet with independent verification |

98| Duration | seconds to a few minutes | roughly 5 to 10 minutes |

99| Cost | counts toward normal usage | free runs, then roughly \$5 to \$20 per review as extra usage |

100| Best for | quick feedback while iterating | pre-merge confidence on substantial changes |

101 

102Use `/review` for fast feedback as you work. Use `/ultrareview` before merging a substantial change when you want a deeper pass that catches issues a single review might miss.

103 

104## Related resources

105 

106* [Claude Code on the web](/en/claude-code-on-the-web): learn how remote sessions and cloud sandboxes work

107* [Plan complex changes with ultraplan](/en/ultraplan): the planning counterpart to ultrareview for upfront design work

108* [Manage costs effectively](/en/costs): track usage and set spending limits

voice-dictation.md +50 −18

Details

4 4 

5# Voice dictation5# Voice dictation

6 6 

7> Use push-to-talk voice dictation to speak your prompts instead of typing them in the Claude Code CLI.7> Speak your prompts in the Claude Code CLI with hold-to-record or tap-to-record voice dictation.

8 8 

9Hold a key and speak to dictate your prompts. Your speech is transcribed live into the prompt input, so you can mix voice and typing in the same message. Enable dictation with `/voice`. The default push-to-talk key is `Space`; [rebind to a modifier combination](#rebind-the-push-to-talk-key) to activate on the first keypress rather than after a brief hold.9Speak your prompts instead of typing them in the Claude Code CLI. Your speech is transcribed live into the prompt input, so you can mix voice and typing in the same message. Enable dictation with `/voice`, then either hold a key while you speak or tap once to start and again to send.

10 10 

11<Note>11<Note>

12 Voice dictation requires Claude Code v2.1.69 or later. Check your version with `claude --version`.12 Voice dictation requires Claude Code v2.1.69 or later. Tap mode requires v2.1.116 or later. Check your version with `claude --version`.

13</Note>13</Note>

14 14 

15## Requirements15## Requirements

16 16 

17Voice dictation streams your recorded audio to Anthropic's servers for transcription. Audio is not processed locally. The speech-to-text service is only available when you authenticate with a Claude.ai account, and is not available when Claude Code is configured to use an Anthropic API key directly, Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. See [data usage](/en/data-usage) for how Anthropic handles your data.17Voice dictation streams your recorded audio to Anthropic's servers for transcription. Audio is not processed locally. The speech-to-text service is only available when you authenticate with a Claude.ai account, and is not available when Claude Code is configured to use an Anthropic API key directly, Amazon Bedrock, Google Vertex AI, or Microsoft Foundry. Transcription does not consume Claude messages or tokens and does not count toward the limits shown in `/usage`. See [data usage](/en/data-usage) for how Anthropic handles your data.

18 18 

19Voice dictation also needs local microphone access, so it does not work in remote environments such as [Claude Code on the web](/en/claude-code-on-the-web) or SSH sessions. In WSL, voice dictation requires WSLg for audio access, which is included with WSL2 on Windows 11. On Windows 10 or WSL1, run Claude Code in native Windows instead.19Voice dictation also needs local microphone access, so it does not work in remote environments such as [Claude Code on the web](/en/claude-code-on-the-web) or SSH sessions. In WSL, voice dictation requires WSLg for audio access, which is included with WSL2 on Windows 11. On Windows 10 or WSL1, run Claude Code in native Windows instead.

20 20 

21Audio recording uses a built-in native module on macOS, Linux, and Windows. On Linux, if the native module cannot load, Claude Code falls back to `arecord` from ALSA utils or `rec` from SoX. If neither is available, `/voice` prints an install command for your package manager.21Audio recording uses a built-in native module on macOS, Linux, and Windows. On Linux, if the native module cannot load, Claude Code falls back to `arecord` from ALSA utils or `rec` from SoX. If neither is available, `/voice` prints an install command for your package manager.

22 22 

23The Claude Code [VS Code extension](/en/vs-code) also supports voice dictation with the same Claude.ai account requirement. It is not available in VS Code Remote sessions, including SSH, Dev Containers, and Codespaces, because the microphone is on your local machine and the extension runs on the remote host.

24 

23## Enable voice dictation25## Enable voice dictation

24 26 

25Run `/voice` to toggle voice dictation on. The first time you enable it, Claude Code runs a microphone check. On macOS, this triggers the system microphone permission prompt for your terminal if it has never been granted.27Run `/voice` to enable dictation. The first time you enable it, Claude Code runs a microphone check. On macOS, this triggers the system microphone permission prompt for your terminal if it has never been granted.

26 28 

27```29```

28/voice30/voice

29Voice mode enabled. Hold Space to record. Dictation language: en (/config to change).31Voice mode enabled (hold). Hold Space to record. Dictation language: en (/config to change).

30```32```

31 33 

32Voice dictation persists across sessions. Run `/voice` again to turn it off, or set it directly in your [user settings file](/en/settings):34`/voice` accepts an optional mode argument:

35 

36| Command | Effect |

37| :------------ | :-------------------------------------------- |

38| `/voice` | Toggle on or off, keep the current mode |

39| `/voice hold` | Enable in [hold mode](#hold-to-record) |

40| `/voice tap` | Enable in [tap mode](#tap-to-record-and-send) |

41| `/voice off` | Disable |

42 

43Voice dictation persists across sessions. Set it directly in your [user settings file](/en/settings) instead of running `/voice`:

33 44 

34```json theme={null}45```json theme={null}

35{46{

36 "voiceEnabled": true47 "voice": {

48 "enabled": true,

49 "mode": "tap"

50 }

37}51}

38```52```

39 53 

40While voice dictation is enabled, the input footer shows a `hold Space to speak` hint when the prompt is empty. The hint does not appear if you have a [custom status line](/en/statusline) configured.54While voice dictation is enabled, the input footer shows a `hold Space to speak` hint when the prompt is empty. The hint text is the same in both modes, and it does not appear if you have a [custom status line](/en/statusline) configured.

55 

56Transcription is tuned for coding vocabulary in both modes. Common development terms like `regex`, `OAuth`, `JSON`, and `localhost` are recognized correctly, and your current project name and git branch name are added as recognition hints automatically.

57 

58## Hold to record

41 59 

42## Record a prompt60Hold mode is push-to-talk: recording runs while you hold the key and stops when you release it. This is the default mode.

43 61 

44Hold `Space` to start recording. Claude Code detects a held key by watching for rapid key-repeat events from your terminal, so there is a brief warmup before recording begins. The footer shows `keep holding…` during warmup, then switches to a live waveform once recording is active.62Hold `Space` to start recording. Claude Code detects a held key by watching for rapid key-repeat events from your terminal, so there is a brief warmup before recording begins. The footer shows `keep holding…` during warmup, then switches to a live waveform once recording is active.

45 63 

46The first couple of key-repeat characters type into the input during warmup and are removed automatically when recording activates. A single `Space` tap still types a space, since hold detection only triggers on rapid repeat.64The first couple of key-repeat characters type into the input during warmup and are removed automatically when recording activates. A single `Space` tap still types a space, since hold detection only triggers on rapid repeat.

47 65 

48<Tip>66<Tip>

49 To skip the warmup, [rebind to a modifier combination](#rebind-the-push-to-talk-key) like `meta+k`. Modifier combos start recording on the first keypress.67 To skip the warmup, switch to [tap mode](#tap-to-record-and-send) with `/voice tap`, or [rebind to a modifier combination](#rebind-the-dictation-key) like `meta+k`. Modifier combos start recording on the first keypress.

50</Tip>68</Tip>

51 69 

52Your speech appears in the prompt as you speak, dimmed until the transcript is finalized. Release `Space` to stop recording and finalize the text. The transcript is inserted at your cursor position and the cursor stays at the end of the inserted text, so you can mix typing and dictation in any order. Hold `Space` again to append another recording, or move the cursor first to insert speech elsewhere in the prompt:70Your speech appears in the prompt as you speak, dimmed until the transcript is finalized. Release `Space` to stop recording and finalize the text. The transcript is inserted at your cursor position and the cursor stays at the end of the inserted text, so you can mix typing and dictation in any order. Hold `Space` again to append another recording, or move the cursor first to insert speech elsewhere in the prompt:


57> refactor the auth middleware to use the new token validation helper▮75> refactor the auth middleware to use the new token validation helper▮

58```76```

59 77 

60Transcription is tuned for coding vocabulary. Common development terms like `regex`, `OAuth`, `JSON`, and `localhost` are recognized correctly, and your current project name and git branch name are added as recognition hints automatically.78By default, releasing the key inserts the transcript and waits for you to press `Enter`. Set `"autoSubmit": true` in the `voice` settings object to send the prompt automatically when you release the key, as long as the transcript is at least three words long.

79 

80## Tap to record and send

81 

82Tap mode toggles recording with a single keypress: tap once to start, speak, then tap again to send the prompt. There is no warmup, and you do not need to keep the key held.

83 

84Enable tap mode with `/voice tap`. With the prompt input empty, tap `Space` to start recording. The footer shows a live waveform while recording. Tap `Space` again to stop. Claude Code inserts the transcript and submits the prompt automatically when the transcript is at least three words long. Shorter transcripts are inserted but not submitted, so an accidental tap does not send a stray word.

85 

86The first tap only starts recording when the prompt input is empty, so you can still type spaces normally while composing a message. The second tap stops recording regardless of input contents. Recording also stops automatically after 15 seconds of silence or two minutes total.

61 87 

62## Change the dictation language88## Change the dictation language

63 89 

64Voice dictation uses the same [`language` setting](/en/settings) that controls Claude's response language. If that setting is empty, dictation defaults to English.90Voice dictation uses the same [`language` setting](/en/settings) that controls Claude's response language. If that setting is empty, dictation defaults to English. In the VS Code extension, if `language` is empty, dictation uses VS Code's `accessibility.voice.speechLanguage` setting before defaulting to English.

65 91 

66<Accordion title="Supported dictation languages">92<Accordion title="Supported dictation languages">

67 | Language | Code |93 | Language | Code |


98 124 

99If your `language` setting is not in the supported list, `/voice` warns you on enable and falls back to English for dictation. Claude's text responses are not affected by this fallback.125If your `language` setting is not in the supported list, `/voice` warns you on enable and falls back to English for dictation. Claude's text responses are not affected by this fallback.

100 126 

101## Rebind the push-to-talk key127## Rebind the dictation key

102 128 

103The push-to-talk key is bound to `voice:pushToTalk` in the `Chat` context and defaults to `Space`. Rebind it in [`~/.claude/keybindings.json`](/en/keybindings):129The dictation key is bound to `voice:pushToTalk` in the `Chat` context and defaults to `Space`. The same binding controls both hold and tap modes. Rebind it in [`~/.claude/keybindings.json`](/en/keybindings):

104 130 

105```json theme={null}131```json theme={null}

106{132{


118 144 

119Setting `"space": null` removes the default binding. Omit it if you want both keys active.145Setting `"space": null` removes the default binding. Omit it if you want both keys active.

120 146 

121Because hold detection relies on key-repeat, avoid binding a bare letter key like `v` since it types into the prompt during warmup. Use `Space`, or use a modifier combination like `meta+k` to start recording on the first keypress with no warmup. See [customize keyboard shortcuts](/en/keybindings) for the full keybinding syntax.147In hold mode, avoid binding a bare letter key like `v` since hold detection relies on key-repeat and the letter types into the prompt during warmup. Use `Space`, or use a modifier combination like `meta+k` to start recording on the first keypress with no warmup. Tap mode has no warmup, so most keys work.

148 

149Some keys are not delivered to terminal applications and cannot be bound at all. For example, `Caps Lock` shows an error if you try to bind it. See [customize keyboard shortcuts](/en/keybindings) for the full keybinding syntax and the list of reserved shortcuts.

122 150 

123## Troubleshooting151## Troubleshooting

124 152 


127* **`Voice mode requires a Claude.ai account`**: you are authenticated with an API key or a third-party provider. Run `/login` to sign in with a Claude.ai account.155* **`Voice mode requires a Claude.ai account`**: you are authenticated with an API key or a third-party provider. Run `/login` to sign in with a Claude.ai account.

128* **`Microphone access is denied`**: grant microphone permission to your terminal in system settings. On macOS, go to System Settings → Privacy & Security → Microphone and enable your terminal app, then run `/voice` again. On Windows, go to Settings → Privacy & security → Microphone and turn on microphone access for desktop apps, then run `/voice` again. If your terminal isn't listed in the macOS settings, see [Terminal not listed in macOS Microphone settings](#terminal-not-listed-in-macos-microphone-settings).156* **`Microphone access is denied`**: grant microphone permission to your terminal in system settings. On macOS, go to System Settings → Privacy & Security → Microphone and enable your terminal app, then run `/voice` again. On Windows, go to Settings → Privacy & security → Microphone and turn on microphone access for desktop apps, then run `/voice` again. If your terminal isn't listed in the macOS settings, see [Terminal not listed in macOS Microphone settings](#terminal-not-listed-in-macos-microphone-settings).

129* **`No audio recording tool found` on Linux**: the native audio module could not load and no fallback is installed. Install SoX with the command shown in the error message, for example `sudo apt-get install sox`.157* **`No audio recording tool found` on Linux**: the native audio module could not load and no fallback is installed. Install SoX with the command shown in the error message, for example `sudo apt-get install sox`.

130* **Nothing happens when holding `Space`**: watch the prompt input while you hold. If spaces keep accumulating, voice dictation is off; run `/voice` to enable it. If only one or two spaces appear and then nothing, voice dictation is on but hold detection is not triggering. Hold detection requires your terminal to send key-repeat events, so it cannot detect a held key if key-repeat is disabled at the OS level.158* **`Voice input is failing repeatedly and has been paused`**: voice dictation hit several start-up failures in a row and stopped attempting new sessions until one succeeds. This usually means the microphone or audio stack on this host can't capture audio, for example a headless server, a remote shell with no audio passthrough, or a denied microphone permission. Confirm a working input device, fix the underlying cause from the entries above, then trigger voice again.

159* **Nothing happens when holding `Space` in hold mode**: watch the prompt input while you hold. If spaces keep accumulating, voice dictation is likely off; run `/voice hold` to enable it. If only one or two spaces appear and then nothing, voice dictation is on but hold detection is not triggering. Hold detection requires your terminal to send key-repeat events, so it cannot detect a held key if key-repeat is disabled at the OS level. Switch to tap mode with `/voice tap` to avoid the key-repeat requirement.

160* **Tapping `Space` types a space instead of recording in tap mode**: the first tap only starts recording when the prompt input is empty. Clear the input first, or check that you are in tap mode by running `/voice tap`.

161* **`No audio detected from microphone`**: recording started but captured silence. Confirm the correct input device is set as the system default and that its input level is not muted or near zero. On Windows, open Settings → System → Sound → Input and select your microphone. On macOS, open System Settings → Sound → Input.

162* **`No speech detected`**: audio reached the transcription service but no words were recognized. Speak closer to the microphone, reduce background noise, and confirm your [dictation language](#change-the-dictation-language) matches the language you are speaking.

131* **Transcription is garbled or in the wrong language**: dictation defaults to English. If you are dictating in another language, set it in `/config` first. See [Change the dictation language](#change-the-dictation-language).163* **Transcription is garbled or in the wrong language**: dictation defaults to English. If you are dictating in another language, set it in `/config` first. See [Change the dictation language](#change-the-dictation-language).

132 164 

133### Terminal not listed in macOS Microphone settings165### Terminal not listed in macOS Microphone settings


155## See also187## See also

156 188 

157* [Customize keyboard shortcuts](/en/keybindings): rebind `voice:pushToTalk` and other CLI keyboard actions189* [Customize keyboard shortcuts](/en/keybindings): rebind `voice:pushToTalk` and other CLI keyboard actions

158* [Configure settings](/en/settings): full reference for `voiceEnabled`, `language`, and other settings keys190* [Configure settings](/en/settings): full reference for `voice`, `language`, and other settings keys

159* [Interactive mode](/en/interactive-mode): keyboard shortcuts, input modes, and session controls191* [Interactive mode](/en/interactive-mode): keyboard shortcuts, input modes, and session controls

160* [Commands](/en/commands): reference for `/voice`, `/config`, and all other commands192* [Commands](/en/commands): reference for `/voice`, `/config`, and all other commands

vs-code.md +51 −14

Details

32 32 

33Or in VS Code, press `Cmd+Shift+X` (Mac) or `Ctrl+Shift+X` (Windows/Linux) to open the Extensions view, search for "Claude Code", and click **Install**.33Or in VS Code, press `Cmd+Shift+X` (Mac) or `Ctrl+Shift+X` (Windows/Linux) to open the Extensions view, search for "Claude Code", and click **Install**.

34 34 

35The extension also installs in other VS Code forks like Windsurf or Kiro. Search for "Claude Code" in the editor's Extensions view, or install from the [Open VSX registry](https://open-vsx.org/extension/Anthropic/claude-code). If your editor can't install the extension, run `claude` in its integrated terminal instead. The [CLI](/en/quickstart) works in any terminal.

36 

35<Note>If the extension doesn't appear after installation, restart VS Code or run "Developer: Reload Window" from the Command Palette.</Note>37<Note>If the extension doesn't appear after installation, restart VS Code or run "Developer: Reload Window" from the Command Palette.</Note>

36 38 

37## Get started39## Get started


76 </Step>78 </Step>

77 79 

78 <Step title="Review changes">80 <Step title="Review changes">

79 When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead.81 When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead. If you edit the proposed content directly in the diff view before accepting, Claude is told that you modified it so it does not assume the file matches its original proposal.

80 82 

81 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" width="3292" height="1876" data-path="images/vs-code-edits.png" />83 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" width="3292" height="1876" data-path="images/vs-code-edits.png" />

82 </Step>84 </Step>


95* **Permission modes**: click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. VS Code automatically opens the plan as a full markdown document where you can add inline comments to give feedback before Claude begins. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`.97* **Permission modes**: click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. VS Code automatically opens the plan as a full markdown document where you can add inline comments to give feedback before Claude begins. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`.

96* **Command menu**: click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, viewing plan usage (`/usage`), and starting a [Remote Control](/en/remote-control) session (`/remote-control`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal.98* **Command menu**: click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, viewing plan usage (`/usage`), and starting a [Remote Control](/en/remote-control) session (`/remote-control`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal.

97* **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.99* **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.

98* **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.100* **Extended thinking**: lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). Claude's reasoning appears in the conversation as collapsed blocks: click a block to read it, or press `Ctrl+O` to expand or collapse every thinking block in the session. See [Extended thinking](/en/model-config#extended-thinking) for details.

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

100 102 

101### Reference files and folders103### Reference files and folders


115 117 

116### Resume past conversations118### Resume past conversations

117 119 

118Click 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. New sessions receive AI-generated titles based on your first message. Hover over a session to reveal rename and remove actions: rename to give it a descriptive title, or remove to delete it from the list. For more on resuming sessions, see [Common workflows](/en/common-workflows#resume-previous-conversations).120Click the **Session history** button 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. New sessions receive AI-generated titles based on your first message. Hover over a session to reveal rename and remove actions: rename to give it a descriptive title, or remove to delete it from the list. For more on resuming sessions, see [Manage sessions](/en/sessions).

119 121 

120### Resume remote sessions from Claude.ai122### Resume remote sessions from Claude.ai

121 123 

122If 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.124If 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.

123 125 

124<Steps>126<Steps>

125 <Step title="Open Past Conversations">127 <Step title="Open session history">

126 Click the **Past Conversations** dropdown at the top of the Claude Code panel.128 Click the **Session history** button at the top of the Claude Code panel.

127 </Step>129 </Step>

128 130 

129 <Step title="Select the Remote tab">131 <Step title="Select the Remote tab">


246 248 

247The extension registers a URI handler at `vscode://anthropic.claude-code/open`. Use it to open a new Claude Code tab from your own tooling: a shell alias, a browser bookmarklet, or any script that can open a URL. If VS Code isn't already running, opening the URL launches it first. If VS Code is already running, the URL opens in whichever window is currently focused.249The extension registers a URI handler at `vscode://anthropic.claude-code/open`. Use it to open a new Claude Code tab from your own tooling: a shell alias, a browser bookmarklet, or any script that can open a URL. If VS Code isn't already running, opening the URL launches it first. If VS Code is already running, the URL opens in whichever window is currently focused.

248 250 

249Invoke the handler with your operating system's URL opener. On macOS:251Invoke the handler with your operating system's URL opener.

250 252 

251```bash theme={null}253<Tabs>

252open "vscode://anthropic.claude-code/open"254 <Tab title="macOS">

253```255 ```bash theme={null}

256 open "vscode://anthropic.claude-code/open"

257 ```

258 </Tab>

259 

260 <Tab title="Linux">

261 ```bash theme={null}

262 xdg-open "vscode://anthropic.claude-code/open"

263 ```

264 </Tab>

265 

266 <Tab title="Windows">

267 In PowerShell:

268 

269 ```powershell theme={null}

270 Start-Process "vscode://anthropic.claude-code/open"

271 ```

254 272 

255Use `xdg-open` on Linux or `start` on Windows.273 In `cmd.exe`, `start` treats its first quoted argument as a window title, so pass an empty title before the URL:

274 

275 ```cmd theme={null}

276 start "" "vscode://anthropic.claude-code/open"

277 ```

278 </Tab>

279</Tabs>

256 280 

257The handler accepts two optional query parameters:281The handler accepts two optional query parameters:

258 282 


267vscode://anthropic.claude-code/open?prompt=review%20my%20changes291vscode://anthropic.claude-code/open?prompt=review%20my%20changes

268```292```

269 293 

294To launch a terminal session instead of a VS Code tab, use the CLI's `claude-cli://` handler. See [Launch sessions from links](/en/deep-links).

295 

270## Configure settings296## Configure settings

271 297 

272The extension has two types of settings:298The extension has two types of settings:


294| `environmentVariables` | `[]` | Set environment variables for the Claude process. Use Claude Code settings instead for shared config. |320| `environmentVariables` | `[]` | Set environment variables for the Claude process. Use Claude Code settings instead for shared config. |

295| `disableLoginPrompt` | `false` | Skip authentication prompts (for third-party provider setups) |321| `disableLoginPrompt` | `false` | Skip authentication prompts (for third-party provider setups) |

296| `allowDangerouslySkipPermissions` | `false` | Adds [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) and Bypass permissions to the mode selector. Auto mode has [plan, admin, model, and provider requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), so it may remain unavailable even with this toggle on. Use Bypass permissions only in sandboxes with no internet access. |322| `allowDangerouslySkipPermissions` | `false` | Adds [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) and Bypass permissions to the mode selector. Auto mode has [plan, admin, model, and provider requirements](/en/permission-modes#eliminate-prompts-with-auto-mode), so it may remain unavailable even with this toggle on. Use Bypass permissions only in sandboxes with no internet access. |

297| `claudeProcessWrapper` | - | Executable path used to launch the Claude process |323| `claudeProcessWrapper` | - | Executable used to launch the Claude process. The bundled binary path is passed as an argument when present. Set this to a separately installed `claude` binary if the extension build doesn't include one for your platform. |

298 324 

299## VS Code extension vs. Claude Code CLI325## VS Code extension vs. Claude Code CLI

300 326 


340 366 

341MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs.367MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs.

342 368 

343To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run:369To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run `claude mcp add`. The example below adds GitHub's remote MCP server, which authenticates with a [personal access token](https://github.com/settings/personal-access-tokens) passed as a header:

344 370 

345```bash theme={null}371```bash theme={null}

346claude mcp add --transport http github https://api.githubcopilot.com/mcp/372claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \

373 --header "Authorization: Bearer YOUR_GITHUB_PAT"

347```374```

348 375 

349Once configured, ask Claude to use the tools (e.g., "Review PR #456").376Once configured, ask Claude to use the tools (e.g., "Review PR #456").


374claude --worktree feature-auth401claude --worktree feature-auth

375```402```

376 403 

377Each 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).404Each 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/worktrees).

378 405 

379## Use third-party providers406## Use third-party providers

380 407 


451 478 

452Alternatively, click "✱ Claude Code" in the **Status Bar** (bottom-right corner). This works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type "Claude Code".479Alternatively, click "✱ Claude Code" in the **Status Bar** (bottom-right corner). This works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type "Claude Code".

453 480 

481### Cmd+Esc does nothing on macOS

482 

483On macOS Tahoe and later, the system Game Overlay shortcut is bound to `Cmd+Esc` by default and intercepts the keypress before it reaches VS Code. To free the shortcut:

484 

4851. Open System Settings

4862. Go to Keyboard, then Keyboard Shortcuts, then Game Controllers

4873. Clear the Game Overlay checkbox

488 

489Alternatively, rebind the extension to a different key: open the VS Code [Keyboard Shortcuts editor](https://code.visualstudio.com/docs/configure/keybindings) (`Cmd+K Cmd+S`), search for `Claude Code: Focus input`, and assign a new binding.

490 

454### Claude Code never responds491### Claude Code never responds

455 492 

456If Claude Code isn't responding to your prompts:493If Claude Code isn't responding to your prompts:

Details

71 * **Name**: a display label. Useful when you have multiple environments for different projects or access levels.71 * **Name**: a display label. Useful when you have multiple environments for different projects or access levels.

72 * **Network access**: controls what the session can reach on the internet. The default, `Trusted`, allows connections to [common package registries](/en/claude-code-on-the-web#default-allowed-domains) like npm, PyPI, and RubyGems while blocking general internet access.72 * **Network access**: controls what the session can reach on the internet. The default, `Trusted`, allows connections to [common package registries](/en/claude-code-on-the-web#default-allowed-domains) like npm, PyPI, and RubyGems while blocking general internet access.

73 * **Environment variables**: optional variables available in every session, in `.env` format. Don't wrap values in quotes, since quotes are stored as part of the value. These are visible to anyone who can edit this environment.73 * **Environment variables**: optional variables available in every session, in `.env` format. Don't wrap values in quotes, since quotes are stored as part of the value. These are visible to anyone who can edit this environment.

74 * **Setup script**: an optional Bash script that runs before Claude Code launches when a new session is created. Use it to install system tools the cloud VM doesn't include, like `apt install -y gh`, or to start services your project needs. See [Setup scripts](/en/claude-code-on-the-web#setup-scripts) for examples and debugging tips.74 * **Setup script**: an optional Bash script that runs before Claude Code launches. Use it to install system tools the cloud VM doesn't include, like `apt install -y gh`. The result is [cached](/en/claude-code-on-the-web#environment-caching), so the script doesn't re-run on every session. See [Setup scripts](/en/claude-code-on-the-web#setup-scripts) for examples and debugging tips.

75 75 

76 For a first project, leave the defaults and click **Create environment**. You can [edit it later or create additional environments](/en/claude-code-on-the-web#configure-your-environment) for different projects.76 For a first project, leave the defaults and click **Create environment**. You can [edit it later or create additional environments](/en/claude-code-on-the-web#configure-your-environment) for different projects.

77 </Step>77 </Step>


133 </Step>133 </Step>

134</Steps>134</Steps>

135 135 

136## Pre-fill sessions

137 

138You can prefill the prompt, repositories, and environment for a new session by adding query parameters to the [claude.ai/code](https://claude.ai/code) URL. Use this to build integrations such as a button in your issue tracker that opens Claude Code with the issue description as the prompt.

139 

140| Parameter | Description |

141| :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |

142| `prompt` | Prompt text to prefill in the input box. The alias `q` is also accepted. |

143| `prompt_url` | URL to fetch the prompt text from, for prompts too long to embed in a query string. The URL must allow cross-origin requests. Ignored when `prompt` is also set. |

144| `repositories` | Comma-separated list of `owner/repo` slugs to preselect. The alias `repo` is also accepted. |

145| `environment` | Name or ID of the [environment](#connect-github-and-create-an-environment) to preselect. |

146 

147URL-encode each value. The example below opens the form with a prompt and a repository already selected:

148 

149```text theme={null}

150https://claude.ai/code?prompt=Fix%20the%20login%20bug&repositories=acme/webapp

151```

152 

136## Review and iterate153## Review and iterate

137 154 

138When Claude finishes, review the changes, leave feedback on specific lines, and keep going until the diff looks right.155When Claude finishes, review the changes, leave feedback on specific lines, and keep going until the diff looks right.


189 206 

190To debug, add `set -x` at the top of the script to see which command failed. For non-critical commands, append `|| true` so they don't block session start.207To debug, add `set -x` at the top of the script to see which command failed. For non-critical commands, append `|| true` so they don't block session start.

191 208 

209### New sessions hang or time out during setup

210 

211If new sessions stall on the setup script step or fail with a generic container error before the script finishes, the script is likely exceeding the roughly five-minute time budget for building the [environment cache](/en/claude-code-on-the-web#environment-caching). Heavy steps such as pulling large Docker images, syncing full dependency trees, or downloading model weights often push the total over the limit, especially when they run one after another.

212 

213To fix this, trim the script so it reliably finishes in under five minutes:

214 

215* Run independent installs in parallel with `&` and a final `wait` instead of running them serially.

216* Move the largest downloads out of the setup script and into a [SessionStart hook](/en/claude-code-on-the-web#setup-scripts-vs-sessionstart-hooks) that launches them in the background, so the session becomes usable while they finish.

217* Remove long retry sleeps from the setup script, since a stalled retry loop counts against the budget.

218 

192### Session keeps running after closing the tab219### Session keeps running after closing the tab

193 220 

194This is by design. Closing the tab or navigating away doesn't stop the session. It continues running in the background until Claude finishes the current task, then idles. From the sidebar, you can [archive a session](/en/claude-code-on-the-web#archive-sessions) to hide it from your list, or [delete it](/en/claude-code-on-the-web#delete-sessions) to remove it permanently.221This is by design. Closing the tab or navigating away doesn't stop the session. It continues running in the background until Claude finishes the current task, then idles. From the sidebar, you can [archive a session](/en/claude-code-on-the-web#archive-sessions) to hide it from your list, or [delete it](/en/claude-code-on-the-web#delete-sessions) to remove it permanently.

whats-new.md +32 −0

Details

8 8 

9The weekly dev digest highlights the features most likely to change how you work. Each entry includes runnable code, a short demo, and a link to the full docs. For every bug fix and minor improvement, see the [changelog](/en/changelog).9The weekly dev digest highlights the features most likely to change how you work. Each entry includes runnable code, a short demo, and a link to the full docs. For every bug fix and minor improvement, see the [changelog](/en/changelog).

10 10 

11<Update label="Week 19" description="May 4–8, 2026" tags={["v2.1.128–v2.1.136"]}>

12 **Plugins load from `.zip` archives and URLs**: `--plugin-dir` now accepts `.zip` files, and `--plugin-url` fetches a plugin archive for the current session.

13 

14 Also this week: **`worktree.baseRef`** chooses whether new worktrees branch from the remote default or local `HEAD`; **auto mode hard deny rules** block actions unconditionally regardless of allow exceptions; and **hooks see the active effort level** via `effort.level` and `$CLAUDE_EFFORT`.

15 

16 [Read the Week 19 digest →](/en/whats-new/2026-w19)

17</Update>

18 

19<Update label="Week 18" description="April 27 – May 1, 2026" tags={["v2.1.120–v2.1.126"]}>

20 **Windows without Git Bash**: Git for Windows is no longer required, and Claude Code uses PowerShell as the shell tool when Bash is absent.

21 

22 Also this week: **`claude ultrareview`** brings cloud code review to CI and scripts; **`claude project purge`** cleans up local state for a project; and pasting a **PR URL into `/resume`** finds the session that created it.

23 

24 [Read the Week 18 digest →](/en/whats-new/2026-w18)

25</Update>

26 

27<Update label="Week 17" description="April 20–24, 2026" tags={["v2.1.114–v2.1.119"]}>

28 **`/ultrareview`** opens as a public research preview: a fleet of bug-hunting agents runs in the cloud and findings land back in your CLI or Desktop automatically.

29 

30 Also this week: **session recap** shows you what happened while a terminal was unfocused; **custom themes** let you build and ship color palettes from `/theme` or a plugin; and **Claude Code on the web** gets a redesign with a new sessions sidebar and drag-and-drop layout.

31 

32 [Read the Week 17 digest →](/en/whats-new/2026-w17)

33</Update>

34 

35<Update label="Week 16" description="April 13–17, 2026" tags={["v2.1.105–v2.1.113"]}>

36 **Claude Opus 4.7** lands as the new default on Max and Team Premium, with a new `xhigh` effort level that's the recommended setting for most coding work and an interactive `/effort` slider to dial it in.

37 

38 Also this week: **Routines** on Claude Code on the web fire templated cloud agents from a schedule, GitHub event, or API call; **mobile push notifications** ping your phone when a long task finishes or Claude needs you; `/usage` shows what's driving your limits; and the CLI moves to native binaries.

39 

40 [Read the Week 16 digest →](/en/whats-new/2026-w16)

41</Update>

42 

11<Update label="Week 15" description="April 6–10, 2026" tags={["v2.1.92–v2.1.101"]}>43<Update label="Week 15" description="April 6–10, 2026" tags={["v2.1.92–v2.1.101"]}>

12 **Ultraplan** enters early preview: draft a plan in the cloud from your CLI, review and comment on it in a web editor, then run it remotely or pull it back local. The first run now auto-creates a cloud environment for you.44 **Ultraplan** enters early preview: draft a plan in the cloud from your CLI, review and comment on it in a web editor, then run it remotely or pull it back local. The first run now auto-creates a cloud environment for you.

13 45 

Details

7> Auto mode for hands-off permissions, computer use built in, PR auto-fix in the cloud, transcript search, and a PowerShell tool for Windows.7> Auto mode for hands-off permissions, computer use built in, PR auto-fix in the cloud, transcript search, and a PowerShell tool for Windows.

8 8 

9<div className="digest-meta">9<div className="digest-meta">

10 <span>Releases <a href="/en/changelog#2-1-83">v2.1.83 → v2.1.85</a></span>10 <span>Releases <a href="/docs/en/changelog#2-1-83">v2.1.83 → v2.1.85</a></span>

11 <span>6 features · March 23–27</span>11 <span>6 features · March 23–27</span>

12</div>12</div>

13 13 


33 }33 }

34 ```34 ```

35 35 

36 <a className="digest-feature-link" href="/en/permission-modes">Permission modes guide</a>36 <a className="digest-feature-link" href="/docs/en/permission-modes">Permission modes guide</a>

37</div>37</div>

38 38 

39<div className="digest-feature">39<div className="digest-feature">


54 > Open the iOS simulator, tap through the onboarding flow, and screenshot each step54 > Open the iOS simulator, tap through the onboarding flow, and screenshot each step

55 ```55 ```

56 56 

57 <a className="digest-feature-link" href="/en/desktop#let-claude-use-your-computer">Computer use guide</a>57 <a className="digest-feature-link" href="/docs/en/desktop#let-claude-use-your-computer">Computer use guide</a>

58</div>58</div>

59 59 

60<div className="digest-feature">60<div className="digest-feature">


71 71 

72 <p className="digest-feature-try">After creating a PR on Claude Code web, toggle Auto fix in the CI panel.</p>72 <p className="digest-feature-try">After creating a PR on Claude Code web, toggle Auto fix in the CI panel.</p>

73 73 

74 <a className="digest-feature-link" href="/en/claude-code-on-the-web#auto-fix-pull-requests">Auto-fix pull requests</a>74 <a className="digest-feature-link" href="/docs/en/claude-code-on-the-web#auto-fix-pull-requests">Auto-fix pull requests</a>

75</div>75</div>

76 76 

77<div className="digest-feature">77<div className="digest-feature">


91 N # previous match91 N # previous match

92 ```92 ```

93 93 

94 <a className="digest-feature-link" href="/en/fullscreen#search-and-review-the-conversation">Fullscreen guide</a>94 <a className="digest-feature-link" href="/docs/en/fullscreen#search-and-review-the-conversation">Fullscreen guide</a>

95</div>95</div>

96 96 

97<div className="digest-feature">97<div className="digest-feature">


113 }113 }

114 ```114 ```

115 115 

116 <a className="digest-feature-link" href="/en/tools-reference#powershell-tool">PowerShell tool docs</a>116 <a className="digest-feature-link" href="/docs/en/tools-reference#powershell-tool">PowerShell tool docs</a>

117</div>117</div>

118 118 

119<div className="digest-feature">119<div className="digest-feature">


140 }140 }

141 ```141 ```

142 142 

143 <a className="digest-feature-link" href="/en/hooks">Hooks reference</a>143 <a className="digest-feature-link" href="/docs/en/hooks">Hooks reference</a>

144</div>144</div>

145 145 

146<div className="digest-wins">146<div className="digest-wins">

Details

7> Computer use in the CLI, interactive in-product lessons, flicker-free rendering, per-tool MCP result-size overrides, and plugin executables on PATH.7> Computer use in the CLI, interactive in-product lessons, flicker-free rendering, per-tool MCP result-size overrides, and plugin executables on PATH.

8 8 

9<div className="digest-meta">9<div className="digest-meta">

10 <span>Releases <a href="/en/changelog#2-1-86">v2.1.86 → v2.1.91</a></span>10 <span>Releases <a href="/docs/en/changelog#2-1-86">v2.1.86 → v2.1.91</a></span>

11 <span>5 features · March 30 – April 3</span>11 <span>5 features · March 30 – April 3</span>

12</div>12</div>

13 13 


29 > Open the iOS simulator, tap through onboarding, and screenshot each step29 > Open the iOS simulator, tap through onboarding, and screenshot each step

30 ```30 ```

31 31 

32 <a className="digest-feature-link" href="/en/computer-use">Computer use guide</a>32 <a className="digest-feature-link" href="/docs/en/computer-use">Computer use guide</a>

33</div>33</div>

34 34 

35<div className="digest-feature">35<div className="digest-feature">


50 > /powerup50 > /powerup

51 ```51 ```

52 52 

53 <a className="digest-feature-link" href="/en/commands">Commands reference</a>53 <a className="digest-feature-link" href="/docs/en/commands">Commands reference</a>

54</div>54</div>

55 55 

56<div className="digest-feature">56<div className="digest-feature">


72 claude72 claude

73 ```73 ```

74 74 

75 <a className="digest-feature-link" href="/en/fullscreen">Fullscreen rendering</a>75 <a className="digest-feature-link" href="/docs/en/fullscreen">Fullscreen rendering</a>

76</div>76</div>

77 77 

78<div className="digest-feature">78<div className="digest-feature">


95 }95 }

96 ```96 ```

97 97 

98 <a className="digest-feature-link" href="/en/mcp#raise-the-limit-for-a-specific-tool">MCP reference</a>98 <a className="digest-feature-link" href="/docs/en/mcp#raise-the-limit-for-a-specific-tool">MCP reference</a>

99</div>99</div>

100 100 

101<div className="digest-feature">101<div className="digest-feature">


116 └── my-tool116 └── my-tool

117 ```117 ```

118 118 

119 <a className="digest-feature-link" href="/en/plugins-reference#file-locations-reference">Plugins reference</a>119 <a className="digest-feature-link" href="/docs/en/plugins-reference#file-locations-reference">Plugins reference</a>

120</div>120</div>

121 121 

122<div className="digest-wins">122<div className="digest-wins">

Details

7> Ultraplan cloud planning, the Monitor tool with self-pacing /loop, /team-onboarding for packaging your setup, and /autofix-pr from your terminal.7> Ultraplan cloud planning, the Monitor tool with self-pacing /loop, /team-onboarding for packaging your setup, and /autofix-pr from your terminal.

8 8 

9<div className="digest-meta">9<div className="digest-meta">

10 <span>Releases <a href="/en/changelog#2-1-92">v2.1.92 → v2.1.101</a></span>10 <span>Releases <a href="/docs/en/changelog#2-1-92">v2.1.92 → v2.1.101</a></span>

11 <span>4 features · April 6–10</span>11 <span>4 features · April 6–10</span>

12</div>12</div>

13 13 


29 > /ultraplan migrate the auth service from sessions to JWTs29 > /ultraplan migrate the auth service from sessions to JWTs

30 ```30 ```

31 31 

32 <a className="digest-feature-link" href="/en/ultraplan">Ultraplan guide</a>32 <a className="digest-feature-link" href="/docs/en/ultraplan">Ultraplan guide</a>

33</div>33</div>

34 34 

35<div className="digest-feature">35<div className="digest-feature">


56 > /loop check CI on my PR56 > /loop check CI on my PR

57 ```57 ```

58 58 

59 <a className="digest-feature-link" href="/en/tools-reference#monitor-tool">Monitor tool reference</a>59 <a className="digest-feature-link" href="/docs/en/tools-reference#monitor-tool">Monitor tool reference</a>

60</div>60</div>

61 61 

62<div className="digest-feature">62<div className="digest-feature">


77 > /autofix-pr77 > /autofix-pr

78 ```78 ```

79 79 

80 <a className="digest-feature-link" href="/en/claude-code-on-the-web#auto-fix-pull-requests">Auto-fix pull requests</a>80 <a className="digest-feature-link" href="/docs/en/claude-code-on-the-web#auto-fix-pull-requests">Auto-fix pull requests</a>

81</div>81</div>

82 82 

83<div className="digest-feature">83<div className="digest-feature">


94 > /team-onboarding94 > /team-onboarding

95 ```95 ```

96 96 

97 <a className="digest-feature-link" href="/en/commands">Commands reference</a>97 <a className="digest-feature-link" href="/docs/en/commands">Commands reference</a>

98</div>98</div>

99 99 

100<div className="digest-wins">100<div className="digest-wins">


102 102 

103 <div className="digest-wins-grid">103 <div className="digest-wins-grid">

104 <div>Focus view: press <code>Ctrl+O</code> in flicker-free mode to collapse the view to your last prompt, a one-line tool summary with diffstats, and Claude's final response</div>104 <div>Focus view: press <code>Ctrl+O</code> in flicker-free mode to collapse the view to your last prompt, a one-line tool summary with diffstats, and Claude's final response</div>

105 <div>Guided <a href="/en/amazon-bedrock">Bedrock</a> and <a href="/en/google-vertex-ai">Vertex AI</a> setup wizards on the login screen: pick "3rd-party platform" for step-by-step auth, region, credential check, and model pinning</div>105 <div>Guided <a href="/docs/en/amazon-bedrock">Bedrock</a> and <a href="/docs/en/google-vertex-ai">Vertex AI</a> setup wizards on the login screen: pick "3rd-party platform" for step-by-step auth, region, credential check, and model pinning</div>

106 <div><code>/agents</code> gets a tabbed layout: a Running tab shows live subagents with a <code>● N running</code> count, plus Run agent and View running instance actions in the Library tab</div>106 <div><code>/agents</code> gets a tabbed layout: a Running tab shows live subagents with a <code>● N running</code> count, plus Run agent and View running instance actions in the Library tab</div>

107 <div>Default effort level is now <code>high</code> for API-key, Bedrock, Vertex, Foundry, Team, and Enterprise users (control with <code>/effort</code>)</div>107 <div>Default effort level is now <code>high</code> for API-key, Bedrock, Vertex, Foundry, Team, and Enterprise users (control with <code>/effort</code>)</div>

108 <div><code>/cost</code> shows a per-model and cache-hit breakdown for subscription users</div>108 <div><code>/cost</code> shows a per-model and cache-hit breakdown for subscription users</div>

whats-new/2026-w16.md +133 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Week 16 · April 13–17, 2026

6 

7> Claude Opus 4.7 with the new xhigh effort level, Routines on Claude Code on the web, mobile push notifications that ping your phone when Claude needs you, a /usage breakdown that shows what's driving your limits, and native binaries replacing the bundled JavaScript.

8 

9<div className="digest-meta">

10 <span>Releases <a href="/docs/en/changelog#2-1-105">v2.1.105 → v2.1.113</a></span>

11 <span>5 features · April 13–17</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Claude Opus 4.7</span>

17 <span className="digest-feature-pill">new model</span>

18 </div>

19 

20 <p className="digest-feature-lede">Anthropic's strongest coding model yet is now the default on Max and Team Premium, and available everywhere else from <code>/model</code>. It adds a new <code>xhigh</code> effort level that sits between <code>high</code> and <code>max</code>: best results for most coding and agentic tasks, applied as the default the first time you switch to 4.7. <code>/effort</code> now opens an interactive arrow-key slider when you call it without arguments, so you can dial intelligence against speed without remembering the level names.</p>

21 

22 <p className="digest-feature-try">Switch model and effort in one go:</p>

23 

24 ```text Claude Code theme={null}

25 > /model opus

26 > /effort xhigh

27 ```

28 

29 <a className="digest-feature-link" href="/docs/en/model-config#adjust-effort-level">Model config: effort levels</a>

30</div>

31 

32<div className="digest-feature">

33 <div className="digest-feature-header">

34 <span className="digest-feature-title">Routines</span>

35 <span className="digest-feature-pill">web</span>

36 </div>

37 

38 <p className="digest-feature-lede">Templated cloud agents that fire on a schedule, a GitHub event, or an API call. Define a routine once on Claude Code on the web with a prompt, the repos it can touch, and the connectors it needs, then let PR-opened, release-published, or your own webhook trigger it without your machine running. The trigger picker now covers GitHub events with optional filters and gives every routine a tokened <code>/fire</code> endpoint for external systems.</p>

39 

40 <Frame>

41 <img className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/routines.png?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=2ba818ea9280c549511cb48b9b4d1dc5" alt="Creating a routine on Claude Code on the web with schedule, GitHub event, and API triggers" width="1440" height="810" data-path="images/whats-new/routines.png" />

42 </Frame>

43 

44 <p className="digest-feature-try">Create one from the web UI, or scaffold from your terminal:</p>

45 

46 ```text Claude Code theme={null}

47 > /schedule daily PR review at 9am

48 ```

49 

50 <a className="digest-feature-link" href="/docs/en/routines">Routines guide</a>

51</div>

52 

53<div className="digest-feature">

54 <div className="digest-feature-header">

55 <span className="digest-feature-title">/usage breakdown</span>

56 <span className="digest-feature-pill">CLI</span>

57 </div>

58 

59 <p className="digest-feature-lede">More visibility into where your Claude Code usage goes. <code>/usage</code> now shows what's driving your limits: parallel sessions, subagents, cache misses, and long context, each with a percentage of your last 24 hours and a tip to optimize it. Press <code>d</code> or <code>w</code> to switch between day and week views.</p>

60 

61 <Frame>

62 <img className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/usage.png?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=792a4b43cbef4e2931974831f076bca6" alt="The /usage command showing a breakdown of what's contributing to limits usage" width="1204" height="1182" data-path="images/whats-new/usage.png" />

63 </Frame>

64 

65 <p className="digest-feature-try">Run it any time:</p>

66 

67 ```text Claude Code theme={null}

68 > /usage

69 ```

70 

71 <a className="digest-feature-link" href="/docs/en/commands">Commands reference</a>

72</div>

73 

74<div className="digest-feature">

75 <div className="digest-feature-header">

76 <span className="digest-feature-title">Mobile push notifications</span>

77 <span className="digest-feature-pill">mobile</span>

78 </div>

79 

80 <p className="digest-feature-lede">With <a href="/docs/en/remote-control">Remote Control</a> connected, Claude can send a push notification to your phone when a long task finishes or it needs a decision to keep going. Turn it on with "Push when Claude decides" in <code>/config</code>, or ask for one in your prompt. Useful when you kick off a long agent run and want to step away from the terminal.</p>

81 

82 <Frame>

83 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/uII1TETOZxBUZ3lB/images/whats-new/push-notifications.mp4?fit=max&auto=format&n=uII1TETOZxBUZ3lB&q=85&s=c91a967139596500cbdb581a53822ac1" data-path="images/whats-new/push-notifications.mp4" />

84 </Frame>

85 

86 <p className="digest-feature-try">Ask Claude to ping you when it's done:</p>

87 

88 ```text Claude Code theme={null}

89 > notify me when the tests pass

90 ```

91 

92 <a className="digest-feature-link" href="/docs/en/remote-control#mobile-push-notifications">Remote Control: mobile push notifications</a>

93</div>

94 

95<div className="digest-feature">

96 <div className="digest-feature-header">

97 <span className="digest-feature-title">Native binaries</span>

98 <span className="digest-feature-pill">v2.1.113</span>

99 </div>

100 

101 <p className="digest-feature-lede">The <code>claude</code> CLI now spawns a native per-platform binary instead of bundled JavaScript, so the installed <code>claude</code> command no longer invokes Node. The npm package pulls the right binary in through an optional dependency such as <code>@anthropic-ai/claude-code-darwin-arm64</code>, so your install command doesn't change. The standalone installer already shipped this binary; npm now matches it.</p>

102 

103 <p className="digest-feature-try">Upgrade and check what you're running:</p>

104 

105 ```bash theme={null}

106 claude update

107 claude --version

108 ```

109 

110 <a className="digest-feature-link" href="/docs/en/setup">Setup guide</a>

111</div>

112 

113<div className="digest-wins">

114 <p className="digest-wins-title">Other wins</p>

115 

116 <div className="digest-wins-grid">

117 <div>New <a href="/docs/en/ultrareview"><code>/ultrareview</code></a>: comprehensive code review in the cloud using parallel multi-agent analysis and an adversarial critique pass. Run it bare to review your current branch, or <code>/ultrareview \<PR#></code> for a specific PR</div>

118 <div><a href="/docs/en/permission-modes#eliminate-prompts-with-auto-mode">Auto mode</a> is now available for Max subscribers on Opus 4.7, and the <code>--enable-auto-mode</code> flag is no longer required</div>

119 <div><a href="/docs/en/interactive-mode#session-recap">Session recap</a> shows a one-line summary of what happened while you were away; run <code>/recap</code> on demand or turn it off from <code>/config</code></div>

120 <div>New <code>/tui</code> command and <code>tui</code> setting switch between classic and flicker-free rendering mid-conversation; focus view moved from <code>Ctrl+O</code> to its own <code>/focus</code> command</div>

121 <div>Plugins can ship background watchers via a top-level <code>monitors</code> manifest key that auto-arms at session start or on skill invoke</div>

122 <div>"Auto (match terminal)" option in <code>/theme</code> follows your terminal's dark/light mode</div>

123 <div><code>/fewer-permission-prompts</code> scans your transcripts for common read-only Bash and MCP calls and proposes an allowlist for <code>.claude/settings.json</code></div>

124 <div>Claude can now discover and run built-in commands like <code>/init</code>, <code>/review</code>, and <code>/security-review</code> via the Skill tool</div>

125 <div><code>PreCompact</code> hooks can block compaction by exiting with code 2 or returning <code>{"{"}"decision":"block"{"}"}</code></div>

126 <div><code>ENABLE\_PROMPT\_CACHING\_1H</code> opts API key, Bedrock, Vertex, and Foundry users into 1-hour prompt cache TTL</div>

127 <div><code>sandbox.network.deniedDomains</code> setting carves specific domains out of a broader <code>allowedDomains</code> wildcard</div>

128 <div><code>/undo</code> is now an alias for <code>/rewind</code>, and <code>/proactive</code> is an alias for <code>/loop</code></div>

129 <div>Hardened Bash permissions: deny rules now match through <code>env</code>/<code>sudo</code>/<code>watch</code> wrappers, and <code>Bash(find:\*)</code> allow rules no longer auto-approve <code>-exec</code> or <code>-delete</code></div>

130 </div>

131</div>

132 

133[Full changelog for v2.1.105–v2.1.113 →](/en/changelog#2-1-105)

whats-new/2026-w17.md +113 −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# Week 17 · April 20–24, 2026

6 

7> /ultrareview opens as a research preview, automatic session recaps when you return to a terminal, custom color themes you can build and ship in plugins, and a redesigned Claude Code on the web.

8 

9<div className="digest-meta">

10 <span>Releases <a href="/docs/en/changelog#2-1-114">v2.1.114 → v2.1.119</a></span>

11 <span>4 features · April 20–24</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">/ultrareview</span>

17 <span className="digest-feature-pill">research preview</span>

18 </div>

19 

20 <p className="digest-feature-lede">Now in public research preview. Ultrareview runs a fleet of bug-hunting agents in the cloud against your branch or a PR, and findings land back in the CLI or Desktop automatically. Run it before merging critical changes such as auth or data migrations.</p>

21 

22 <Frame>

23 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/ultrareview.mp4?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=0fb1271365d38f414ad155aeb8edb08e" data-path="images/whats-new/ultrareview.mp4" />

24 </Frame>

25 

26 <p className="digest-feature-try">Review the branch you're on:</p>

27 

28 ```text Claude Code theme={null}

29 > /ultrareview

30 ```

31 

32 <p className="digest-feature-try">Or point it at a PR:</p>

33 

34 ```text Claude Code theme={null}

35 > /ultrareview 1234

36 ```

37 

38 <a className="digest-feature-link" href="/docs/en/ultrareview">Ultrareview guide</a>

39</div>

40 

41<div className="digest-feature">

42 <div className="digest-feature-header">

43 <span className="digest-feature-title">Session recap</span>

44 <span className="digest-feature-pill">CLI</span>

45 </div>

46 

47 <p className="digest-feature-lede">Switch focus away from a session and come back to a one-line recap of what happened while you were gone. Helpful for staying in flow while running several Claude sessions at once.</p>

48 

49 <Frame>

50 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/session-recap.mp4?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=0a8db1470bd0161a47efeb2f322af76f" data-path="images/whats-new/session-recap.mp4" />

51 </Frame>

52 

53 <p className="digest-feature-try">Generate a recap on demand, or turn the automatic one off from <code>/config</code>:</p>

54 

55 ```text Claude Code theme={null}

56 > /recap

57 ```

58 

59 <a className="digest-feature-link" href="/docs/en/interactive-mode#session-recap">Interactive mode: session recap</a>

60</div>

61 

62<div className="digest-feature">

63 <div className="digest-feature-header">

64 <span className="digest-feature-title">Custom themes</span>

65 <span className="digest-feature-pill">v2.1.118</span>

66 </div>

67 

68 <p className="digest-feature-lede">Build and switch between named color themes from <code>/theme</code>, or hand-edit JSON files in <code>\~/.claude/themes/</code>. Each theme picks a base preset and overrides only the tokens you care about. Plugins can ship themes too.</p>

69 

70 <p className="digest-feature-try">Open the theme picker and create a new one:</p>

71 

72 ```text Claude Code theme={null}

73 > /theme

74 ```

75 

76 <a className="digest-feature-link" href="/docs/en/terminal-config#create-a-custom-theme">Terminal config: create a custom theme</a>

77</div>

78 

79<div className="digest-feature">

80 <div className="digest-feature-header">

81 <span className="digest-feature-title">Claude Code on the web</span>

82 <span className="digest-feature-pill">web</span>

83 </div>

84 

85 <p className="digest-feature-lede">A new look for <a href="https://claude.ai/code">claude.ai/code</a> that matches the redesigned desktop app: sessions sidebar, drag-and-drop layout, and a refreshed routines view. Key parts were rebuilt for quicker responses and a more reliable experience.</p>

86 

87 <Frame>

88 <img className="w-full" src="https://mintcdn.com/claude-code/FTi4SBJ9YRs7d-5X/images/whats-new/web-redesign.jpeg?fit=max&auto=format&n=FTi4SBJ9YRs7d-5X&q=85&s=a2aca1b49e295b7337f5779038db8e2c" alt="Claude Code on the web redesign overview: new UI, speed and reliability, work across web, mobile, and CLI" width="1602" height="1610" data-path="images/whats-new/web-redesign.jpeg" />

89 </Frame>

90 

91 <a className="digest-feature-link" href="/docs/en/claude-code-on-the-web">Claude Code on the web</a>

92</div>

93 

94<div className="digest-wins">

95 <p className="digest-wins-title">Other wins</p>

96 

97 <div className="digest-wins-grid">

98 <div><a href="/docs/en/interactive-mode#vim-editor-mode">Vim visual mode</a>: press <code>v</code> for character selection or <code>V</code> for line selection in the prompt input, with operators and visual feedback</div>

99 <div>Hooks can now call MCP tools directly via <a href="/docs/en/hooks#mcp-tool-hook-fields"><code>type: "mcp\_tool"</code></a>, so a hook can hit an already-connected server without spawning a process</div>

100 <div><code>/cost</code> and <code>/stats</code> are merged into <a href="/docs/en/commands"><code>/usage</code></a>; the old names still work as typing shortcuts that open the relevant tab</div>

101 <div><code>/config</code> changes (theme, editor mode, verbose, and similar) now persist to <code>\~/.claude/settings.json</code> and follow the same project/local/policy precedence as other <a href="/docs/en/settings">settings</a></div>

102 <div><a href="/docs/en/sub-agents#fork-the-current-conversation">Forked subagents</a> can be enabled on external builds with <code>CLAUDE\_CODE\_FORK\_SUBAGENT=1</code>: a fork inherits your full conversation context instead of starting fresh</div>

103 <div>Default <a href="/docs/en/model-config#adjust-effort-level">effort level</a> for Pro and Max subscribers on Opus 4.6 and Sonnet 4.6 is now <code>high</code> (was <code>medium</code>)</div>

104 <div>Native macOS and Linux builds replace the <code>Glob</code> and <code>Grep</code> tools with embedded <code>bfs</code> and <code>ugrep</code> available through Bash, for faster searches without a separate tool round-trip</div>

105 <div><code>--from-pr</code> now accepts GitLab merge request, Bitbucket pull request, and GitHub Enterprise PR URLs in addition to github.com</div>

106 <div>Auto mode: include <code>"\$defaults"</code> in <a href="/docs/en/auto-mode-config"><code>autoMode.allow</code>, <code>soft\_deny</code>, or <code>environment</code></a> to add custom rules alongside the built-in list instead of replacing it</div>

107 <div>New <a href="/docs/en/plugin-dependencies#tag-plugin-releases-for-version-resolution"><code>claude plugin tag</code></a> command creates release git tags for plugins with version validation</div>

108 <div>Opus 4.7 sessions now compute against the model's native 1M context window, fixing inflated <code>/context</code> percentages and premature autocompaction</div>

109 <div><code>/resume</code> on large sessions is up to 67% faster and now offers to summarize stale, large sessions before re-reading them</div>

110 </div>

111</div>

112 

113[Full changelog for v2.1.114–v2.1.119 →](/en/changelog#2-1-114)

whats-new/2026-w18.md +113 −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# Week 18 · April 27 – May 1, 2026

6 

7> Claude Code on Windows runs without Git Bash, claude auth login accepts a pasted OAuth code when the browser callback can't reach localhost, claude project purge cleans up local state per project, and pasting a PR URL into /resume finds the session that created it.

8 

9<div className="digest-meta">

10 <span>Releases <a href="/docs/en/changelog#2-1-120">v2.1.120 → v2.1.126</a></span>

11 <span>4 features · April 27 – May 1</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Sign in without a browser callback</span>

17 <span className="digest-feature-pill">v2.1.126</span>

18 </div>

19 

20 <p className="digest-feature-lede"><code>claude auth login</code> now accepts the OAuth code pasted directly into the terminal when the browser callback can't reach localhost. That covers WSL2, SSH sessions, and containers, where the redirect to a local port doesn't work. The same release also fixes login timeouts on slow or proxied connections and in IPv6-only devcontainers.</p>

21 

22 <p className="digest-feature-try">Sign in, then paste the code from the browser:</p>

23 

24 ```bash theme={null}

25 claude auth login

26 ```

27 

28 <a className="digest-feature-link" href="/docs/en/cli-reference#cli-commands">CLI reference</a>

29</div>

30 

31<div className="digest-feature">

32 <div className="digest-feature-header">

33 <span className="digest-feature-title">claude project purge</span>

34 <span className="digest-feature-pill">v2.1.126</span>

35 </div>

36 

37 <p className="digest-feature-lede">Delete all Claude Code state for a project: transcripts, tasks, file history, and the project's config entry. Supports `--dry-run` to preview, `-y`/`--yes` to skip confirmation, `-i`/`--interactive` to choose, and `--all` to clear every project.</p>

38 

39 <p className="digest-feature-try">Preview what would be removed:</p>

40 

41 ```bash theme={null}

42 claude project purge --dry-run

43 ```

44 

45 <p className="digest-feature-try">Then run it for real:</p>

46 

47 ```bash theme={null}

48 claude project purge

49 ```

50 

51 <a className="digest-feature-link" href="/docs/en/cli-reference">CLI reference</a>

52</div>

53 

54<div className="digest-feature">

55 <div className="digest-feature-header">

56 <span className="digest-feature-title">Resume by PR URL</span>

57 <span className="digest-feature-pill">v2.1.122</span>

58 </div>

59 

60 <p className="digest-feature-lede">When you create a pull request with <code>gh pr create</code>, Claude Code links it to the session that produced it. Now you can get back to that session from the PR URL alone, without remembering its name.</p>

61 

62 <p className="digest-feature-try">Open the session picker:</p>

63 

64 ```text Claude Code theme={null}

65 > /resume

66 ```

67 

68 <p className="digest-feature-try">Paste the PR URL into the picker. The first character of the paste drops you into search mode, and the list filters to the session that created that PR. Press Enter to resume it. GitHub, GitHub Enterprise, GitLab, and Bitbucket pull and merge request URLs all work.</p>

69 

70 ```text Claude Code theme={null}

71 https://github.com/your-org/your-repo/pull/1234

72 ```

73 

74 <p className="digest-feature-try">To skip the picker, pass the PR number on the command line instead:</p>

75 

76 ```bash theme={null}

77 claude --from-pr 1234

78 ```

79 

80 <a className="digest-feature-link" href="/docs/en/sessions#use-the-session-picker">Sessions: use the session picker</a>

81</div>

82 

83<div className="digest-feature">

84 <div className="digest-feature-header">

85 <span className="digest-feature-title">Windows without Git Bash</span>

86 <span className="digest-feature-pill">Windows</span>

87 </div>

88 

89 <p className="digest-feature-lede">Git for Windows is no longer required. When Bash is absent, Claude Code uses PowerShell as the shell tool, and when the PowerShell tool is enabled it is treated as the primary shell. PowerShell 7 installed via the Microsoft Store, MSI without PATH, or a <code>.NET</code> global tool is now detected automatically.</p>

90 

91 <a className="digest-feature-link" href="/docs/en/setup">Setup guide</a>

92</div>

93 

94<div className="digest-wins">

95 <p className="digest-wins-title">Other wins</p>

96 

97 <div className="digest-wins-grid">

98 <div>MCP servers can opt out of tool-search deferral with <code>alwaysLoad: true</code> in their config so all of that server's tools are always available</div>

99 <div>New <code>claude plugin prune</code> removes orphaned auto-installed plugin dependencies, and <code>plugin uninstall --prune</code> cascades</div>

100 <div><code>/skills</code> now has a type-to-filter search box so you can find a skill in a long list without scrolling</div>

101 <div><code>PostToolUse</code> hooks can replace tool output for any tool via <code>hookSpecificOutput.updatedToolOutput</code>, not only MCP tools</div>

102 <div>New <a href="/docs/en/ultrareview"><code>claude ultrareview</code></a> subcommand runs <code>/ultrareview</code> non-interactively from CI or scripts: prints findings to stdout (<code>--json</code> for raw output) and exits 0 on completion or 1 on failure</div>

103 <div><code>--dangerously-skip-permissions</code> now bypasses prompts for writes to <code>.claude/</code>, <code>.git/</code>, <code>.vscode/</code>, shell config files, and other previously protected paths, while catastrophic removal commands still prompt as a safety net</div>

104 <div>The <code>/model</code> picker can list models from your gateway's <code>/v1/models</code> endpoint when <code>ANTHROPIC\_BASE\_URL</code> points at an Anthropic-compatible gateway; opt in with <code>CLAUDE\_CODE\_ENABLE\_GATEWAY\_MODEL\_DISCOVERY=1</code> since v2.1.129</div>

105 <div>MCP servers that hit a transient error during startup now auto-retry up to 3 times instead of staying disconnected</div>

106 <div><code>ANTHROPIC\_BEDROCK\_SERVICE\_TIER</code> selects a Bedrock service tier: <code>default</code>, <code>flex</code>, or <code>priority</code></div>

107 <div><code>/terminal-setup</code> enables iTerm2's clipboard access setting so <code>/copy</code> works, including from tmux</div>

108 <div>Vertex AI now supports X.509 certificate-based Workload Identity Federation (mTLS ADC)</div>

109 <div>Significant memory leak fixes: image-heavy sessions, <code>/usage</code> on large transcript histories, and long-running tools without progress events</div>

110 </div>

111</div>

112 

113[Full changelog for v2.1.120–v2.1.126 →](/en/changelog#2-1-120)

whats-new/2026-w19.md +60 −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# Week 19 · May 4–8, 2026

6 

7> Load plugins from .zip archives and URLs, search command history across every project with Ctrl+R, branch new worktrees from local HEAD or the remote default, and block actions unconditionally with auto mode hard deny rules.

8 

9<div className="digest-meta">

10 <span>Releases <a href="/en/changelog#2-1-128">v2.1.128 → v2.1.136</a></span>

11 <span>2 features · May 4–8</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Plugins from .zip archives and URLs</span>

17 </div>

18 

19 <p className="digest-feature-lede">`--plugin-dir` now accepts a <code>.zip</code> plugin archive in addition to a directory, and the new `--plugin-url` flag fetches a plugin archive from a URL for the current session. Useful for trying a plugin before adding it to a marketplace, or for shipping internal plugins from an artifact store.</p>

20 

21 <p className="digest-feature-try">Load a plugin straight from a URL:</p>

22 

23 ```bash terminal theme={null}

24 claude --plugin-url https://example.com/my-plugin.zip

25 ```

26 

27 <a className="digest-feature-link" href="/en/plugins">Plugins guide</a>

28</div>

29 

30<div className="digest-feature">

31 <div className="digest-feature-header">

32 <span className="digest-feature-title">History search across all your projects</span>

33 <span className="digest-feature-pill">v2.1.129</span>

34 </div>

35 

36 <p className="digest-feature-lede"><code>Ctrl+R</code> reverse-search now defaults to all prompts across every project, restoring the behavior from before v2.1.124. Press <code>Ctrl+S</code> while searching to narrow back to the current project or session. Handy when you remember a command you ran in another repo last week and don't want to go digging for it.</p>

37 

38 <a className="digest-feature-link" href="/en/interactive-mode#command-history">Interactive mode: command history</a>

39</div>

40 

41<div className="digest-wins">

42 <p className="digest-wins-title">Other wins</p>

43 

44 <div className="digest-wins-grid">

45 <div>New <code>worktree.baseRef</code> setting (<code>fresh</code> | <code>head</code>) controls whether <code>--worktree</code>, the <code>EnterWorktree</code> tool, and agent-isolation worktrees branch from the remote default branch or local <code>HEAD</code>; the default <code>fresh</code> keeps unpushed commits out of new worktrees</div>

46 <div>New <code>settings.autoMode.hard\_deny</code> rules block matching actions unconditionally in auto mode, regardless of allow exceptions, for actions that should never run automatically even when broader allow rules apply</div>

47 <div>Hooks now receive the active effort level via the `effort.level` JSON input field and the `$CLAUDE_EFFORT` environment variable, and Bash tool commands can read <code>\$CLAUDE\_EFFORT</code></div>

48 <div><code>CLAUDE\_CODE\_DISABLE\_ALTERNATE\_SCREEN=1</code> opts out of the fullscreen alternate-screen renderer and keeps the conversation in the terminal's native scrollback</div>

49 <div><code>CLAUDE\_CODE\_PACKAGE\_MANAGER\_AUTO\_UPDATE</code> lets Homebrew or WinGet installations run the upgrade in the background and prompt to restart</div>

50 <div><code>CLAUDE\_CODE\_SESSION\_ID</code> is now in the Bash tool subprocess environment, matching the <code>session\_id</code> passed to hooks</div>

51 <div><code>/mcp</code> now shows the tool count for connected servers and flags servers that connected with 0 tools</div>

52 <div><code>--channels</code> now works with console (API key) authentication</div>

53 <div>Subprocesses such as Bash, hooks, MCP, and LSP no longer inherit <code>OTEL\_\*</code> environment variables, so OTEL-instrumented apps run via the Bash tool no longer pick up the CLI's own OTLP endpoint</div>

54 <div>Sub-agent progress summaries now hit the prompt cache, cutting <code>cache\_creation</code> token cost by roughly 3x</div>

55 <div>Several OAuth and credential reliability fixes: parallel sessions no longer dead-end at 401 after a refresh-token race, MCP OAuth refresh tokens are no longer lost when multiple servers refresh concurrently, and a rare login loop from a concurrent credential write is fixed</div>

56 <div>New <code>parentSettingsBehavior</code> admin key lets admins opt SDK <code>managedSettings</code> into the policy merge</div>

57 </div>

58</div>

59 

60[Full changelog for v2.1.128–v2.1.136 →](/en/changelog#2-1-128)

Details

15* [Server-managed settings](/en/server-managed-settings)15* [Server-managed settings](/en/server-managed-settings)

16* Audit logs16* Audit logs

17 17 

18ZDR for Claude Code on Claude for Enterprise applies only to Anthropic's direct platform. For Claude deployments on AWS Bedrock, Google Vertex AI, or Microsoft Foundry, refer to those platforms' data retention policies.18ZDR for Claude Code on Claude for Enterprise applies only to Anthropic's direct platform. For Claude deployments on Amazon Bedrock, Google Vertex AI, or Microsoft Foundry, refer to those platforms' data retention policies.

19 19 

20## ZDR scope20## ZDR scope

21 21 


61 61 

62## Request ZDR62## Request ZDR

63 63 

64To request ZDR for Claude Code on Claude for Enterprise, contact your Anthropic account team. Your account team will submit the request internally, and Anthropic will review and enable ZDR on your organization after confirming eligibility. All enablement actions are audit-logged.64To request ZDR for Claude Code on Claude for Enterprise, [contact sales](https://www.anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=zero_data_retention_request) or your Anthropic account team. Your account team will submit the request internally, and Anthropic will review and enable ZDR on your organization after confirming eligibility. All enablement actions are audit-logged.

65 65 

66If you are currently using ZDR for Claude Code via pay-as-you-go API keys, you can transition to Claude for Enterprise to gain access to administrative features while maintaining ZDR for Claude Code. Contact your account team to coordinate the migration.66If you are currently using ZDR for Claude Code via pay-as-you-go API keys, you can transition to Claude for Enterprise to gain access to administrative features while maintaining ZDR for Claude Code. Contact your account team to coordinate the migration.