SpyBara
Go Premium Account
2026
3 Nov 2025, 12:03
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
4 Apr 2026, 03:46
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
Wed 1 00:11 Wed 1 04:00 Wed 1 18:13 Wed 1 21:12 Thu 2 03:53 Thu 2 06:21 Thu 2 09:19 Thu 2 18:12 Thu 2 21:08 Fri 3 00:11 Fri 3 03:54 Fri 3 18:08 Fri 3 21:07 Sat 4 00:09 Sat 4 03:46 Sat 4 18:05 Tue 7 21:14 Wed 8 00:12 Wed 8 15:27 Wed 8 18:21 Wed 8 21:13 Thu 9 00:09 Thu 9 03:55 Thu 9 15:29 Thu 9 18:17 Thu 9 21:14 Fri 10 00:12 Fri 10 06:32 Fri 10 18:13 Fri 10 21:09 Sat 11 00:11 Mon 13 18:21 Mon 13 21:14 Tue 14 00:16 Tue 14 04:00 Tue 14 06:32 Tue 14 18:21 Tue 14 21:14 Wed 15 04:00 Wed 15 09:29 Wed 15 15:24 Wed 15 18:20 Thu 16 00:16 Thu 16 04:02 Thu 16 15:30 Thu 16 18:21 Thu 16 21:13 Fri 17 00:15 Fri 17 18:14 Fri 17 21:13 Sat 18 00:13 Sat 18 18:09 Mon 20 18:16 Mon 20 21:14 Tue 21 04:01 Tue 21 09:30 Tue 21 21:14 Wed 22 00:13 Wed 22 04:00 Wed 22 21:15 Thu 23 00:17 Thu 23 04:04 Thu 23 18:19 Fri 24 00:17 Fri 24 06:34 Fri 24 18:11 Sat 25 21:10 Sun 26 04:08 Mon 27 18:23 Mon 27 21:20 Tue 28 06:49 Tue 28 15:45 Tue 28 18:28 Tue 28 21:21 Wed 29 00:20 Wed 29 04:11 Wed 29 09:39 Wed 29 15:36 Wed 29 21:21

agent-teams.md +428 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Orchestrate teams of Claude Code sessions

6 

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

8 

9<Warning>

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

11</Warning>

12 

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

14 

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

16 

17<Note>

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

19</Note>

20 

21This page covers:

22 

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

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

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

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

27 

28## When to use agent teams

29 

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

31 

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

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

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

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

36 

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

38 

39### Compare with subagents

40 

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

42 

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

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

45 

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

47</Frame>

48 

49| | Subagents | Agent teams |

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

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

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

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

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

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

56 

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

58 

59## Enable agent teams

60 

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

62 

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

64{

65 "env": {

66 "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"

67 }

68}

69```

70 

71## Start your first agent team

72 

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

74 

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

76 

77```text theme={null}

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

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

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

81```

82 

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

84 

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

86 

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

88 

89## Control your agent team

90 

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

92 

93### Choose a display mode

94 

95Agent teams support two display modes:

96 

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

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

99 

100<Note>

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

102</Note>

103 

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

105 

106```json theme={null}

107{

108 "teammateMode": "in-process"

109}

110```

111 

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

113 

114```bash theme={null}

115claude --teammate-mode in-process

116```

117 

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

119 

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

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

122 

123### Specify teammates and models

124 

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

126 

127```text theme={null}

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

129Use Sonnet for each teammate.

130```

131 

132### Require plan approval for teammates

133 

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

135 

136```text theme={null}

137Spawn an architect teammate to refactor the authentication module.

138Require plan approval before they make any changes.

139```

140 

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

142 

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

144 

145### Talk to teammates directly

146 

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

148 

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

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

151 

152### Assign and claim tasks

153 

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

155 

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

157 

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

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

160 

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

162 

163### Shut down teammates

164 

165To gracefully end a teammate's session:

166 

167```text theme={null}

168Ask the researcher teammate to shut down

169```

170 

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

172 

173### Clean up the team

174 

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

176 

177```text theme={null}

178Clean up the team

179```

180 

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

182 

183<Warning>

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

185</Warning>

186 

187### Enforce quality gates with hooks

188 

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

190 

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

192* [`TaskCreated`](/en/hooks#taskcreated): runs when a task is being created. Exit with code 2 to prevent creation and send feedback.

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

194 

195## How agent teams work

196 

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

198 

199### How Claude starts agent teams

200 

201There are two ways agent teams get started:

202 

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

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

205 

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

207 

208### Architecture

209 

210An agent team consists of:

211 

212| Component | Role |

213| :------------ | :----------------------------------------------------------------------------------------- |

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

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

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

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

218 

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

220 

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

222 

223Teams and tasks are stored locally:

224 

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

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

227 

228Claude Code generates both of these automatically when you create a team and updates them as teammates join, go idle, or leave. The team config holds runtime state such as session IDs and tmux pane IDs, so don't edit it by hand or pre-author it: your changes are overwritten on the next state update.

229 

230To define reusable teammate roles, use [subagent definitions](#use-subagent-definitions-for-teammates) instead.

231 

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

233 

234There is no project-level equivalent of the team config. A file like `.claude/teams/teams.json` in your project directory is not recognized as configuration; Claude treats it as an ordinary file.

235 

236### Use subagent definitions for teammates

237 

238When spawning a teammate, you can reference a [subagent](/en/sub-agents) type from any [subagent scope](/en/sub-agents#choose-the-subagent-scope): project, user, plugin, or CLI-defined. This lets you define a role once, such as a security-reviewer or test-runner, and reuse it both as a delegated subagent and as an agent team teammate.

239 

240To use a subagent definition, mention it by name when asking Claude to spawn the teammate:

241 

242```text theme={null}

243Spawn a teammate using the security-reviewer agent type to audit the auth module.

244```

245 

246The teammate honors that definition's `tools` allowlist and `model`, and the definition's body is appended to the teammate's system prompt as additional instructions rather than replacing it. Team coordination tools such as `SendMessage` and the task management tools are always available to a teammate even when `tools` restricts other tools.

247 

248<Note>

249 The `skills` and `mcpServers` frontmatter fields in a subagent definition are not applied when that definition runs as a teammate. Teammates load skills and MCP servers from your project and user settings, the same as a regular session.

250</Note>

251 

252### Permissions

253 

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

255 

256### Context and communication

257 

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

259 

260**How teammates share information:**

261 

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.

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

265 

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 

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.

272 

273### Token usage

274 

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

276 

277## Use case examples

278 

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

280 

281### Run a parallel code review

282 

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

284 

285```text theme={null}

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

287- One focused on security implications

288- One checking performance impact

289- One validating test coverage

290Have them each review and report findings.

291```

292 

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

294 

295### Investigate with competing hypotheses

296 

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

298 

299```text theme={null}

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

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

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

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

304```

305 

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

307 

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

309 

310## Best practices

311 

312### Give teammates enough context

313 

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

315 

316```text theme={null}

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

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

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

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

321```

322 

323### Choose an appropriate team size

324 

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

326 

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

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

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

330 

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

332 

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

334 

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

336 

337### Size tasks appropriately

338 

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

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

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

342 

343<Tip>

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

345</Tip>

346 

347### Wait for teammates to finish

348 

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

350 

351```text theme={null}

352Wait for your teammates to complete their tasks before proceeding

353```

354 

355### Start with research and review

356 

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

358 

359### Avoid file conflicts

360 

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

362 

363### Monitor and steer

364 

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

366 

367## Troubleshooting

368 

369### Teammates not appearing

370 

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

372 

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

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

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

376 ```bash theme={null}

377 which tmux

378 ```

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

380 

381### Too many permission prompts

382 

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

384 

385### Teammates stopping on errors

386 

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

388 

389* Give them additional instructions directly

390* Spawn a replacement teammate to continue the work

391 

392### Lead shuts down before work is done

393 

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

395 

396### Orphaned tmux sessions

397 

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

399 

400```bash theme={null}

401tmux ls

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

403```

404 

405## Limitations

406 

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

408 

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.

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.

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

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

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.

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

417 

418<Tip>

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

420</Tip>

421 

422## Next steps

423 

424Explore related approaches for parallel work and delegation:

425 

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

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

amazon-bedrock.md +98 −37

Details

1> ## Documentation Index

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

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

4 

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

2 6 

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


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

8 12 

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

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

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

12* Appropriate IAM permissions16* Appropriate IAM permissions

13 17 

18<Note>

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

20</Note>

21 

14## Setup22## Setup

15 23 

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

17 25 

18First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per account.26First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per AWS account.

19 27 

201. Ensure you have the right IAM permissions (see more on that below)281. Ensure you have the right IAM permissions described below

212. Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/)292. Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/)

223. Select **Chat/Text playground**303. Select an Anthropic model from the **Model catalog**

234. Choose any Anthropic model and you will be prompted to fill out the use case form314. Complete the use case form. Access is granted immediately after submission.

32 

33If you use AWS Organizations, you can submit the form once from the management account using the [`PutUseCaseForModelAccess` API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_PutUseCaseForModelAccess.html). This call requires the `bedrock:PutUseCaseForModelAccess` IAM permission. Approval extends to child accounts automatically.

24 34 

25### 2. Configure AWS credentials35### 2. Configure AWS credentials

26 36 


48export AWS_PROFILE=your-profile-name58export AWS_PROFILE=your-profile-name

49```59```

50 60 

51**Option D: Bedrock API keys**61**Option D: AWS Management Console credentials**

62 

63```bash theme={null}

64aws login

65```

66 

67[Learn more](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) about `aws login`.

68 

69**Option E: Bedrock API keys**

52 70 

53```bash theme={null}71```bash theme={null}

54export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key72export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key


58 76 

59#### Advanced credential configuration77#### Advanced credential configuration

60 78 

61Claude Code supports automatic credential refresh for AWS SSO and corporate identity providers. Add these settings to your Claude Code settings file (see [Settings](/en/docs/claude-code/settings) for file locations).79Claude Code supports automatic credential refresh for AWS SSO and corporate identity providers. Add these settings to your Claude Code settings file (see [Settings](/en/settings) for file locations).

62 80 

63When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request.81When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request.

64 82 


75 93 

76##### Configuration settings explained94##### Configuration settings explained

77 95 

78**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory (e.g., updating credentials, SSO cache, or config files). Output is shown to the user (but user input is not supported), making it suitable for browser-based authentication flows where the CLI displays a code to enter in the browser.96**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command's output is displayed to the user, but interactive input isn't supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser.

79 97 

80**`awsCredentialExport`**: Only use this if you cannot modify `.aws` and must directly return credentials. Output is captured silently (not shown to the user). The command must output JSON in this format:98**`awsCredentialExport`**: Only use this if you can't modify `.aws` and must directly return credentials. Output is captured silently and not shown to the user. The command must output JSON in this format:

81 99 

82```json theme={null}100```json theme={null}

83{101{


100 118 

101# Optional: Override the region for the small/fast model (Haiku)119# Optional: Override the region for the small/fast model (Haiku)

102export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2120export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2

121 

122# Optional: Override the Bedrock endpoint URL for custom endpoints or gateways

123# export ANTHROPIC_BEDROCK_BASE_URL=https://bedrock-runtime.us-east-1.amazonaws.com

103```124```

104 125 

105When enabling Bedrock for Claude Code, keep the following in mind:126When enabling Bedrock for Claude Code, keep the following in mind:

106 127 

107* `AWS_REGION` is a required environment variable. Claude Code does not read from the `.aws` config file for this setting.128* `AWS_REGION` is a required environment variable. Claude Code does not read from the `.aws` config file for this setting.

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

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

131 

132### 4. Pin model versions

110 133 

111### 4. Model configuration134<Warning>

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

136</Warning>

112 137 

113Claude Code uses these default models for Bedrock:138Set these environment variables to specific Bedrock model IDs:

139 

140```bash theme={null}

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

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

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

144```

145 

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

147 

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

114 149 

115| Model type | Default value |150| Model type | Default value |

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

117| Primary model | `global.anthropic.claude-sonnet-4-5-20250929-v1:0` |152| Primary model | `us.anthropic.claude-sonnet-4-5-20250929-v1:0` |

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

119 154 

120<Note>155To customize models further, use one of these methods:

121 For Bedrock users, Claude Code will not automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (e.g., `us.anthropic.claude-haiku-4-5-20251001-v1:0`).

122</Note>

123 

124To customize models, use one of these methods:

125 156 

126```bash theme={null}157```bash theme={null}

127# Using inference profile ID158# Using inference profile ID

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

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

130 161 

131# Using application inference profile ARN162# Using application inference profile ARN

132export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'163export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'


135export DISABLE_PROMPT_CACHING=1166export DISABLE_PROMPT_CACHING=1

136```167```

137 168 

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

139 [Prompt caching](/en/docs/build-with-claude/prompt-caching) may not be available in all regions

140</Note>

141 170 

142### 5. Output token configuration171#### Map each model version to an inference profile

143 172 

144When using Claude Code with Amazon Bedrock, we recommend the following token settings:173The `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.

145 174 

146```bash theme={null}175This example maps three Opus versions to distinct ARNs so users can switch between them without bypassing your organization's inference profiles:

147# Recommended output token settings for Bedrock

148export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096

149export MAX_THINKING_TOKENS=1024

150```

151 176 

152**Why these values:**177```json theme={null}

153 178{

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

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

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

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

183 }

184}

185```

155 186 

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

157 188 

158## IAM configuration189## IAM configuration

159 190 


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

201 232 

202<Note>233<Note>

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

204</Note>235</Note>

205 236 

237## 1M token context window

238 

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

240 

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

242 

243## AWS Guardrails

244 

245[Amazon Bedrock Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html) let you implement content filtering for Claude Code. Create a Guardrail in the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/), publish a version, then add the Guardrail headers to your [settings file](/en/settings). Enable Cross-Region inference on your Guardrail if you're using cross-region inference profiles.

246 

247Example configuration:

248 

249```json theme={null}

250{

251 "env": {

252 "ANTHROPIC_CUSTOM_HEADERS": "X-Amzn-Bedrock-GuardrailIdentifier: your-guardrail-id\nX-Amzn-Bedrock-GuardrailVersion: 1"

253 }

254}

255```

256 

206## Troubleshooting257## Troubleshooting

207 258 

259### Authentication loop with SSO and corporate proxies

260 

261If browser tabs spawn repeatedly when using AWS SSO, remove the `awsAuthRefresh` setting from your [settings file](/en/settings). This can occur when corporate VPNs or TLS inspection proxies interrupt the SSO browser flow. Claude Code treats the interrupted connection as an authentication failure, re-runs `awsAuthRefresh`, and loops indefinitely.

262 

263If your network environment interferes with automatic browser-based SSO flows, use `aws sso login` manually before starting Claude Code instead of relying on `awsAuthRefresh`.

264 

265### Region issues

266 

208If you encounter region issues:267If you encounter region issues:

209 268 

210* Check model availability: `aws bedrock list-inference-profiles --region your-region`269* Check model availability: `aws bedrock list-inference-profiles --region your-region`


222* [Bedrock documentation](https://docs.aws.amazon.com/bedrock/)281* [Bedrock documentation](https://docs.aws.amazon.com/bedrock/)

223* [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)282* [Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)

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

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

285* [Claude Code on Amazon Bedrock: Quick Setup Guide](https://community.aws/content/2tXkZKrZzlrlu0KfH8gST5Dkppq/claude-code-on-amazon-bedrock-quick-setup-guide)

286* [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md)

analytics.md +182 −45

Details

1# Analytics1> ## Documentation Index

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

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

2 4 

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

4 6 

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

8 

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

10 

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

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

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

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

15 

16## Access analytics for Team and Enterprise

17 

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

19 

20The Team and Enterprise dashboard includes:

21 

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

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

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

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

26 

27### Enable contribution metrics

6 28 

7<Note>29<Note>

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

9</Note>31</Note>

10 32 

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

34 

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

36 

37<Warning>

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

39</Warning>

40 

41<Steps>

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

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

44 </Step>

45 

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

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

48 </Step>

49 

50 <Step title="Enable GitHub analytics">

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

52 </Step>

53 

54 <Step title="Authenticate with GitHub">

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

56 </Step>

57</Steps>

12 58 

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

14 60 

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

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

16 63 

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

18* **Owner**65 

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

20* **Admin**

21* **Developer**

22 67 

23<Note>68<Note>

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

25</Note>70</Note>

26 71 

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

73 

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

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

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

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

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

79 

80### Explore the charts

81 

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

83 

84#### Track adoption

85 

86The Adoption chart shows daily usage trends:

87 

88* **users**: daily active users

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

90 

91#### Measure PRs per user

92 

93This chart displays individual developer activity over time:

94 

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

96* **users**: daily active users

97 

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

99 

100#### View pull requests breakdown

101 

102The Pull requests chart shows a daily breakdown of merged PRs:

28 103 

29### Lines of code accepted104* **PRs with CC**: pull requests containing Claude Code-assisted code

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

30 106 

31Total lines of code written by Claude Code that users have accepted in their sessions.107Toggle to **Lines of code** view to see the same breakdown by lines of code rather than PR count.

32 108 

33* Excludes rejected code suggestions109#### Find top contributors

34* Doesn't track subsequent deletions

35 110 

36### Suggestion accept rate111The Leaderboard shows the top 10 users ranked by contribution volume. Toggle between:

37 112 

38Percentage of times users accept code editing tool usage, including:113* **Pull requests**: shows PRs with Claude Code vs All PRs for each user

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

39 115 

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

41* Write

42* NotebookEdit

43 117 

44### Activity118### PR attribution

45 119 

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

47 121 

48**sessions**: Number of active sessions in a given day (number on right Y-axis)122#### Tagging criteria

49 123 

50### Spend124PRs are tagged as "with Claude Code" if they contain at least one line of code written during a Claude Code session. The system uses conservative matching: only code where there is high confidence in Claude Code's involvement is counted as assisted.

51 125 

52**users**: Number of active users in a given day (number on left Y-axis)126#### Attribution process

53 127 

54**spend**: Total dollars spent in a given day (number on right Y-axis)128When a pull request is merged:

55 129 

56### Team insights1301. Added lines are extracted from the PR diff

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

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

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

57 134 

58**Members**: All users who have authenticated to Claude Code135Before comparison, lines are normalized: whitespace is trimmed, multiple spaces are collapsed, quotes are standardized, and text is converted to lowercase.

59 136 

60* API key users are displayed by **API key identifier**137Merged pull requests containing Claude Code-assisted lines are labeled as `claude-code-assisted` in GitHub.

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

62 138 

63**Spend this month:** Per-user total spend for the current month.139#### Time window

64 140 

65**Lines this month:** Per-user total of accepted code lines for the current month.141Sessions from 21 days before to 2 days after the PR merge date are considered for attribution matching.

66 142 

67## Using analytics effectively143#### Excluded files

68 144 

69### Monitor adoption145Certain files are automatically excluded from analysis because they are auto-generated:

70 146 

71Track team member status to identify:147* Lock files: package-lock.json, yarn.lock, Cargo.lock, and similar

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

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

150* Test fixtures: snapshots, cassettes, mock data

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

152 

153#### Attribution notes

154 

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

156 

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

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

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

160 

161### Get the most from analytics

162 

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

164 

165#### Monitor adoption

166 

167Track the Adoption chart and user counts to identify:

72 168 

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

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

171* Dips in usage that may indicate friction or issues

172 

173#### Measure ROI

174 

175Contribution metrics help answer "Is this tool worth the investment?" with data from your own codebase:

176 

177* Track changes in PRs per user over time as adoption increases

178* Compare PRs and lines of code shipped with vs. without Claude Code

179* Use alongside [DORA metrics](https://dora.dev/), sprint velocity, or other engineering KPIs to understand changes from adopting Claude Code

180 

181#### Identify power users

182 

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

184 

185* Share prompting techniques and workflows with the team

186* Provide feedback on what's working well

187* Help onboard new users

75 188 

76### Measure productivity189#### Access data programmatically

77 190 

78Tool acceptance rates and code metrics help you:191To query this data through GitHub, search for PRs labeled with `claude-code-assisted`.

79 192 

80* Understand developer satisfaction with Claude Code suggestions193## Access analytics for API customers

81* Track code generation effectiveness194 

82* Identify opportunities for training or process improvements195API customers using the Claude Console can access analytics at [platform.claude.com/claude-code](https://platform.claude.com/claude-code). You need the UsageView permission to access the dashboard, which is granted to Developer, Billing, Admin, Owner, and Primary Owner roles.

196 

197<Note>

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

199</Note>

200 

201The Console dashboard displays:

202 

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

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

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

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

207 

208### View team insights

209 

210The team insights table shows per-user metrics:

211 

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

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

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

215 

216<Note>

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

218</Note>

83 219 

84## Related resources220## Related resources

85 221 

86* [Monitoring usage with OpenTelemetry](/en/docs/claude-code/monitoring-usage) for custom metrics and alerting222* [Monitoring with OpenTelemetry](/en/monitoring-usage): export real-time metrics and events to your observability stack

87* [Identity and access management](/en/docs/claude-code/iam) for role configuration223* [Manage costs effectively](/en/costs): set spend limits and optimize token usage

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

authentication.md +134 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Authentication

6 

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

8 

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

10 

11## Log in to Claude Code

12 

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

14 

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

16 

17You can authenticate with any of these account types:

18 

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

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

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

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

23 

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

25 

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

27 

28## Set up team authentication

29 

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

31 

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

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

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

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

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

37 

38### Claude for Teams or Enterprise

39 

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

41 

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

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

44 

45<Steps>

46 <Step title="Subscribe">

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

48 </Step>

49 

50 <Step title="Invite team members">

51 Invite team members from the admin dashboard.

52 </Step>

53 

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

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

56 </Step>

57</Steps>

58 

59### Claude Console authentication

60 

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

62 

63<Steps>

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

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

66 </Step>

67 

68 <Step title="Add users">

69 You can add users through either method:

70 

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

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

73 </Step>

74 

75 <Step title="Assign roles">

76 When inviting users, assign one of:

77 

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

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

80 </Step>

81 

82 <Step title="Users complete setup">

83 Each invited user needs to:

84 

85 * Accept the Console invite

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

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

88 * Log in with Console account credentials

89 </Step>

90</Steps>

91 

92### Cloud provider authentication

93 

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

95 

96<Steps>

97 <Step title="Follow provider setup">

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

99 </Step>

100 

101 <Step title="Distribute configuration">

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

103 </Step>

104 

105 <Step title="Install Claude Code">

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

107 </Step>

108</Steps>

109 

110## Credential management

111 

112Claude Code securely manages your authentication credentials:

113 

114* **Storage location**: on macOS, credentials are stored in the encrypted macOS Keychain. 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.

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

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

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

118* **Slow helper notice**: if `apiKeyHelper` takes longer than 10 seconds to return a key, Claude Code displays a warning notice in the prompt bar showing the elapsed time. If you see this notice regularly, check whether your credential script can be optimized.

119 

120`apiKeyHelper`, `ANTHROPIC_API_KEY`, and `ANTHROPIC_AUTH_TOKEN` apply to terminal CLI sessions only. Claude Desktop and remote sessions use OAuth exclusively and do not call `apiKeyHelper` or read API key environment variables.

121 

122### Authentication precedence

123 

124When multiple credentials are present, Claude Code chooses one in this order:

125 

1261. Cloud provider credentials, when `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is set. See [third-party integrations](/en/third-party-integrations) for setup.

1272. `ANTHROPIC_AUTH_TOKEN` environment variable. Sent as the `Authorization: Bearer` header. Use this when routing through an [LLM gateway or proxy](/en/llm-gateway) that authenticates with bearer tokens rather than Anthropic API keys.

1283. `ANTHROPIC_API_KEY` environment variable. Sent as the `X-Api-Key` header. Use this for direct Anthropic API access with a key from the [Claude Console](https://platform.claude.com). In interactive mode, you are prompted once to approve or decline the key, and your choice is remembered. To change it later, use the "Use custom API key" toggle in `/config`. In non-interactive mode (`-p`), the key is always used when present.

1294. [`apiKeyHelper`](/en/settings#available-settings) script output. Use this for dynamic or rotating credentials, such as short-lived tokens fetched from a vault.

1305. Subscription OAuth credentials from `/login`. This is the default for Claude Pro, Max, Team, and Enterprise users.

131 

132If you have an active Claude subscription but also have `ANTHROPIC_API_KEY` set in your environment, the API key takes precedence once approved. This can cause authentication failures if the key belongs to a disabled or expired organization. Run `unset ANTHROPIC_API_KEY` to fall back to your subscription, and check `/status` to confirm which method is active.

133 

134[Claude Code on the Web](/en/claude-code-on-the-web) always uses your subscription credentials. `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` in the sandbox environment do not override them.

best-practices.md +583 −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# Best Practices for Claude Code

6 

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

8 

9Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.

10 

11This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.

12 

13But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.

14 

15This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see [How Claude Code works](/en/how-claude-code-works).

16 

17***

18 

19Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.

20 

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

22 

23This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. To see how a session fills up in practice, [watch an interactive walkthrough](/en/context-window) of what loads at startup and what each file read costs. Track context usage continuously with a [custom status line](/en/statusline), and see [Reduce token usage](/en/costs#reduce-token-usage) for strategies on reducing token usage.

24 

25***

26 

27## Give Claude a way to verify its work

28 

29<Tip>

30 Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.

31</Tip>

32 

33Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.

34 

35Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention.

36 

37| Strategy | Before | After |

38| ------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

39| **Provide verification criteria** | *"implement a function that validates email addresses"* | *"write a validateEmail function. example test cases: [user@example.com](mailto:user@example.com) is true, invalid is false, [user@.com](mailto:user@.com) is false. run the tests after implementing"* |

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

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

42 

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

44 

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

46 

47***

48 

49## Explore first, then plan, then code

50 

51<Tip>

52 Separate research and planning from implementation to avoid solving the wrong problem.

53</Tip>

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.

56 

57The recommended workflow has four phases:

58 

59<Steps>

60 <Step title="Explore">

61 Enter Plan Mode. Claude reads files and answers questions without making changes.

62 

63 ```txt claude (Plan Mode) theme={null}

64 read /src/auth and understand how we handle sessions and login.

65 also look at how we manage environment variables for secrets.

66 ```

67 </Step>

68 

69 <Step title="Plan">

70 Ask Claude to create a detailed implementation plan.

71 

72 ```txt claude (Plan Mode) theme={null}

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

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

75 ```

76 

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

78 </Step>

79 

80 <Step title="Implement">

81 Switch back to Normal Mode and let Claude code, verifying against its plan.

82 

83 ```txt claude (Normal Mode) theme={null}

84 implement the OAuth flow from your plan. write tests for the

85 callback handler, run the test suite and fix any failures.

86 ```

87 </Step>

88 

89 <Step title="Commit">

90 Ask Claude to commit with a descriptive message and create a PR.

91 

92 ```txt claude (Normal Mode) theme={null}

93 commit with a descriptive message and open a PR

94 ```

95 </Step>

96</Steps>

97 

98<Callout>

99 Plan Mode is useful, but also adds overhead.

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.

102 

103 Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.

104</Callout>

105 

106***

107 

108## Provide specific context in your prompts

109 

110<Tip>

111 The more precise your instructions, the fewer corrections you'll need.

112</Tip>

113 

114Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.

115 

116| Strategy | Before | After |

117| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

118| **Scope the task.** Specify which file, what scenario, and testing preferences. | *"add tests for foo.py"* | *"write a test for foo.py covering the edge case where the user is logged out. avoid mocks."* |

119| **Point to sources.** Direct Claude to the source that can answer a question. | *"why does ExecutionFactory have such a weird api?"* | *"look through ExecutionFactory's git history and summarize how its api came to be"* |

120| **Reference existing patterns.** Point Claude to patterns in your codebase. | *"add a calendar widget"* | *"look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase."* |

121| **Describe the symptom.** Provide the symptom, the likely location, and what "fixed" looks like. | *"fix the login bug"* | *"users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it"* |

122 

123Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like `"what would you improve in this file?"` can surface things you wouldn't have thought to ask about.

124 

125### Provide rich content

126 

127<Tip>

128 Use `@` to reference files, paste screenshots/images, or pipe data directly.

129</Tip>

130 

131You can provide rich data to Claude in several ways:

132 

133* **Reference files with `@`** instead of describing where code lives. Claude reads the file before responding.

134* **Paste images directly**. Copy/paste or drag and drop images into the prompt.

135* **Give URLs** for documentation and API references. Use `/permissions` to allowlist frequently-used domains.

136* **Pipe in data** by running `cat error.log | claude` to send file contents directly.

137* **Let Claude fetch what it needs**. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.

138 

139***

140 

141## Configure your environment

142 

143A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see [Extend Claude Code](/en/features-overview).

144 

145### Write an effective CLAUDE.md

146 

147<Tip>

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

149</Tip>

150 

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

152 

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

154 

155There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:

156 

157```markdown CLAUDE.md theme={null}

158# Code style

159- Use ES modules (import/export) syntax, not CommonJS (require)

160- Destructure imports when possible (eg. import { foo } from 'bar')

161 

162# Workflow

163- Be sure to typecheck when you're done making a series of code changes

164- Prefer running single tests, and not the whole test suite, for performance

165```

166 

167CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use [skills](/en/skills) instead. Claude loads them on demand without bloating every conversation.

168 

169Keep it concise. For each line, ask: *"Would removing this cause Claude to make mistakes?"* If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!

170 

171| ✅ Include | ❌ Exclude |

172| ---------------------------------------------------- | -------------------------------------------------- |

173| Bash commands Claude can't guess | Anything Claude can figure out by reading code |

174| Code style rules that differ from defaults | Standard language conventions Claude already knows |

175| Testing instructions and preferred test runners | Detailed API documentation (link to docs instead) |

176| Repository etiquette (branch naming, PR conventions) | Information that changes frequently |

177| Architectural decisions specific to your project | Long explanations or tutorials |

178| Developer environment quirks (required env vars) | File-by-file descriptions of the codebase |

179| Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" |

180 

181If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts.

182 

183You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.

184 

185CLAUDE.md files can import additional files using `@path/to/import` syntax:

186 

187```markdown CLAUDE.md theme={null}

188See @README.md for project overview and @package.json for available npm commands.

189 

190# Additional Instructions

191- Git workflow: @docs/git-instructions.md

192- Personal overrides: @~/.claude/my-project-instructions.md

193```

194 

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

196 

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

198* **Project root (`./CLAUDE.md`)**: check into git to share with your team

199* **Project root (`./CLAUDE.local.md`)**: personal project-specific notes; add this file to your `.gitignore` so it isn't shared with your team

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

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

202 

203### Configure permissions

204 

205<Tip>

206 Use [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) to let a classifier handle approvals, `/permissions` to allowlist specific commands, or `/sandbox` for OS-level isolation. Each reduces interruptions while keeping you in control.

207</Tip>

208 

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

210 

211* **Auto mode**: a separate classifier model reviews commands and blocks only what looks risky: scope escalation, unknown infrastructure, or hostile-content-driven actions. Best when you trust the general direction of a task but don't want to click through every step

212* **Permission allowlists**: permit specific tools you know are safe, like `npm run lint` or `git commit`

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

214 

215Read more about [permission modes](/en/permission-modes), [permission rules](/en/permissions), and [sandboxing](/en/sandboxing).

216 

217### Use CLI tools

218 

219<Tip>

220 Tell Claude Code to use CLI tools like `gh`, `aws`, `gcloud`, and `sentry-cli` when interacting with external services.

221</Tip>

222 

223CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the `gh` CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without `gh`, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.

224 

225Claude is also effective at learning CLI tools it doesn't already know. Try prompts like `Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.`

226 

227### Connect MCP servers

228 

229<Tip>

230 Run `claude mcp add` to connect external tools like Notion, Figma, or your database.

231</Tip>

232 

233With [MCP servers](/en/mcp), you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.

234 

235### Set up hooks

236 

237<Tip>

238 Use hooks for actions that must happen every time with zero exceptions.

239</Tip>

240 

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

242 

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

244 

245### Create skills

246 

247<Tip>

248 Create `SKILL.md` files in `.claude/skills/` to give Claude domain knowledge and reusable workflows.

249</Tip>

250 

251[Skills](/en/skills) extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with `/skill-name`.

252 

253Create a skill by adding a directory with a `SKILL.md` to `.claude/skills/`:

254 

255```markdown .claude/skills/api-conventions/SKILL.md theme={null}

256---

257name: api-conventions

258description: REST API design conventions for our services

259---

260# API Conventions

261- Use kebab-case for URL paths

262- Use camelCase for JSON properties

263- Always include pagination for list endpoints

264- Version APIs in the URL path (/v1/, /v2/)

265```

266 

267Skills can also define repeatable workflows you invoke directly:

268 

269```markdown .claude/skills/fix-issue/SKILL.md theme={null}

270---

271name: fix-issue

272description: Fix a GitHub issue

273disable-model-invocation: true

274---

275Analyze and fix the GitHub issue: $ARGUMENTS.

276 

2771. Use `gh issue view` to get the issue details

2782. Understand the problem described in the issue

2793. Search the codebase for relevant files

2804. Implement the necessary changes to fix the issue

2815. Write and run tests to verify the fix

2826. Ensure code passes linting and type checking

2837. Create a descriptive commit message

2848. Push and create a PR

285```

286 

287Run `/fix-issue 1234` to invoke it. Use `disable-model-invocation: true` for workflows with side effects that you want to trigger manually.

288 

289### Create custom subagents

290 

291<Tip>

292 Define specialized assistants in `.claude/agents/` that Claude can delegate to for isolated tasks.

293</Tip>

294 

295[Subagents](/en/sub-agents) run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation.

296 

297```markdown .claude/agents/security-reviewer.md theme={null}

298---

299name: security-reviewer

300description: Reviews code for security vulnerabilities

301tools: Read, Grep, Glob, Bash

302model: opus

303---

304You are a senior security engineer. Review code for:

305- Injection vulnerabilities (SQL, XSS, command injection)

306- Authentication and authorization flaws

307- Secrets or credentials in code

308- Insecure data handling

309 

310Provide specific line references and suggested fixes.

311```

312 

313Tell Claude to use subagents explicitly: *"Use a subagent to review this code for security issues."*

314 

315### Install plugins

316 

317<Tip>

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

319</Tip>

320 

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

322 

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

324 

325***

326 

327## Communicate effectively

328 

329The way you communicate with Claude Code significantly impacts the quality of results.

330 

331### Ask codebase questions

332 

333<Tip>

334 Ask Claude questions you'd ask a senior engineer.

335</Tip>

336 

337When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:

338 

339* How does logging work?

340* How do I make a new API endpoint?

341* What does `async move { ... }` do on line 134 of `foo.rs`?

342* What edge cases does `CustomerOnboardingFlowImpl` handle?

343* Why does this code call `foo()` instead of `bar()` on line 333?

344 

345Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.

346 

347### Let Claude interview you

348 

349<Tip>

350 For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the `AskUserQuestion` tool.

351</Tip>

352 

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

354 

355```text theme={null}

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

357 

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

359 

360Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.

361```

362 

363Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.

364 

365***

366 

367## Manage your session

368 

369Conversations are persistent and reversible. Use this to your advantage!

370 

371### Course-correct early and often

372 

373<Tip>

374 Correct Claude as soon as you notice it going off track.

375</Tip>

376 

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

378 

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

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

381* **`"Undo that"`**: have Claude revert its changes.

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

383 

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

385 

386### Manage context aggressively

387 

388<Tip>

389 Run `/clear` between unrelated tasks to reset context.

390</Tip>

391 

392Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.

393 

394During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.

395 

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

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

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.

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

402 

403### Use subagents for investigation

404 

405<Tip>

406 Delegate research with `"use subagents to investigate X"`. They explore in a separate context, keeping your main conversation clean for implementation.

407</Tip>

408 

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

410 

411```text theme={null}

412Use subagents to investigate how our authentication system handles token

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

414```

415 

416The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.

417 

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

419 

420```text theme={null}

421use a subagent to review this code for edge cases

422```

423 

424### Rewind with checkpoints

425 

426<Tip>

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

428</Tip>

429 

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

431 

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

433 

434<Warning>

435 Checkpoints only track changes made *by Claude*, not external processes. This isn't a replacement for git.

436</Warning>

437 

438### Resume conversations

439 

440<Tip>

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

442</Tip>

443 

444Claude Code saves conversations locally. When a task spans multiple sessions, you don't have to re-explain the context:

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 

453***

454 

455## Automate and scale

456 

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

458 

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

460 

461### Run non-interactive mode

462 

463<Tip>

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

465</Tip>

466 

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.

468 

469```bash theme={null}

470# One-off queries

471claude -p "Explain what this project does"

472 

473# Structured output for scripts

474claude -p "List all API endpoints" --output-format json

475 

476# Streaming for real-time processing

477claude -p "Analyze this log file" --output-format stream-json

478```

479 

480### Run multiple Claude sessions

481 

482<Tip>

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

484</Tip>

485 

486There are three main ways to run parallel sessions:

487 

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

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

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

491 

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.

493 

494For example, use a Writer/Reviewer pattern:

495 

496| Session A (Writer) | Session B (Reviewer) |

497| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

498| `Implement a rate limiter for our API endpoints` | |

499| | `Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns.` |

500| `Here's the review feedback: [Session B output]. Address these issues.` | |

501 

502You can do something similar with tests: have one Claude write tests, then another write code to pass them.

503 

504### Fan out across files

505 

506<Tip>

507 Loop through tasks calling `claude -p` for each. Use `--allowedTools` to scope permissions for batch operations.

508</Tip>

509 

510For large migrations or analyses, you can distribute work across many parallel Claude invocations:

511 

512<Steps>

513 <Step title="Generate a task list">

514 Have Claude list all files that need migrating (e.g., `list all 2,000 Python files that need migrating`)

515 </Step>

516 

517 <Step title="Write a script to loop through the list">

518 ```bash theme={null}

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

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

521 --allowedTools "Edit,Bash(git commit *)"

522 done

523 ```

524 </Step>

525 

526 <Step title="Test on a few files, then run at scale">

527 Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The `--allowedTools` flag restricts what Claude can do, which matters when you're running unattended.

528 </Step>

529</Steps>

530 

531You can also integrate Claude into existing data/processing pipelines:

532 

533```bash theme={null}

534claude -p "<your prompt>" --output-format json | your_command

535```

536 

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

538 

539### Run autonomously with auto mode

540 

541For uninterrupted execution with background safety checks, use [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode). A classifier model reviews commands before they run, blocking scope escalation, unknown infrastructure, and hostile-content-driven actions while letting routine work proceed without prompts.

542 

543```bash theme={null}

544claude --permission-mode auto -p "fix all lint errors"

545```

546 

547For non-interactive runs with the `-p` flag, auto mode aborts if the classifier repeatedly blocks actions, since there is no user to fall back to. See [when auto mode falls back](/en/permission-modes#when-auto-mode-falls-back) for thresholds.

548 

549***

550 

551## Avoid common failure patterns

552 

553These are common mistakes. Recognizing them early saves time:

554 

555* **The kitchen sink session.** You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.

556 > **Fix**: `/clear` between unrelated tasks.

557* **Correcting over and over.** Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches.

558 > **Fix**: After two failed corrections, `/clear` and write a better initial prompt incorporating what you learned.

559* **The over-specified CLAUDE.md.** If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.

560 > **Fix**: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.

561* **The trust-then-verify gap.** Claude produces a plausible-looking implementation that doesn't handle edge cases.

562 > **Fix**: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.

563* **The infinite exploration.** You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context.

564 > **Fix**: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.

565 

566***

567 

568## Develop your intuition

569 

570The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation.

571 

572Sometimes you *should* let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.

573 

574Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?

575 

576Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.

577 

578## Related resources

579 

580* [How Claude Code works](/en/how-claude-code-works): the agentic loop, tools, and context management

581* [Extend Claude Code](/en/features-overview): skills, hooks, MCP, subagents, and plugins

582* [Common workflows](/en/common-workflows): step-by-step recipes for debugging, testing, PRs, and more

583* [CLAUDE.md](/en/memory): store project conventions and persistent context

channels.md +357 −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# Push events into a running session with channels

6 

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 

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

11</Note>

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.

14 

15Unlike integrations that spawn a fresh cloud session or wait to be polled, the event arrives in the session you already have open: see [how channels compare](#how-channels-compare).

16 

17You install a channel as a plugin and configure it with your own credentials. Telegram, Discord, and iMessage are included in the research preview.

18 

19When Claude replies through a channel, you see the inbound message in your terminal but not the reply text. The terminal shows the tool call and a confirmation (like "sent"), and the actual reply appears on the other platform.

20 

21This page covers:

22 

23* [Supported channels](#supported-channels): Telegram, Discord, and iMessage setup

24* [Install and run a channel](#quickstart) with fakechat, a localhost demo

25* [Who can push messages](#security): sender allowlists and how you pair

26* [Enable channels for your organization](#enterprise-controls) on Team and Enterprise

27* [How channels compare](#how-channels-compare) to web sessions, Slack, MCP, and Remote Control

28 

29To build your own channel, see the [Channels reference](/en/channels-reference).

30 

31## Supported channels

32 

33Each supported channel is a plugin that requires [Bun](https://bun.sh). For a hands-on demo of the plugin flow before connecting a real platform, try the [fakechat quickstart](#quickstart).

34 

35<Tabs>

36 <Tab title="Telegram">

37 View the full [Telegram plugin source](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram).

38 

39 <Steps>

40 <Step title="Create a Telegram bot">

41 Open [BotFather](https://t.me/BotFather) in Telegram and send `/newbot`. Give it a display name and a unique username ending in `bot`. Copy the token BotFather returns.

42 </Step>

43 

44 <Step title="Install the plugin">

45 In Claude Code, run:

46 

47 ```

48 /plugin install telegram@claude-plugins-official

49 ```

50 

51 If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

52 

53 After installing, run `/reload-plugins` to activate the plugin's configure command.

54 </Step>

55 

56 <Step title="Configure your token">

57 Run the configure command with the token from BotFather:

58 

59 ```

60 /telegram:configure <token>

61 ```

62 

63 This saves it to `~/.claude/channels/telegram/.env`. You can also set `TELEGRAM_BOT_TOKEN` in your shell environment before launching Claude Code.

64 </Step>

65 

66 <Step title="Restart with channels enabled">

67 Exit Claude Code and restart with the channel flag. This starts the Telegram plugin, which begins polling for messages from your bot:

68 

69 ```bash theme={null}

70 claude --channels plugin:telegram@claude-plugins-official

71 ```

72 </Step>

73 

74 <Step title="Pair your account">

75 Open Telegram and send any message to your bot. The bot replies with a pairing code.

76 

77 <Note>If your bot doesn't respond, make sure Claude Code is running with `--channels` from the previous step. The bot can only reply while the channel is active.</Note>

78 

79 Back in Claude Code, run:

80 

81 ```

82 /telegram:access pair <code>

83 ```

84 

85 Then lock down access so only your account can send messages:

86 

87 ```

88 /telegram:access policy allowlist

89 ```

90 </Step>

91 </Steps>

92 </Tab>

93 

94 <Tab title="Discord">

95 View the full [Discord plugin source](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord).

96 

97 <Steps>

98 <Step title="Create a Discord bot">

99 Go to the [Discord Developer Portal](https://discord.com/developers/applications), click **New Application**, and name it. In the **Bot** section, create a username, then click **Reset Token** and copy the token.

100 </Step>

101 

102 <Step title="Enable Message Content Intent">

103 In your bot's settings, scroll to **Privileged Gateway Intents** and enable **Message Content Intent**.

104 </Step>

105 

106 <Step title="Invite the bot to your server">

107 Go to **OAuth2 > URL Generator**. Select the `bot` scope and enable these permissions:

108 

109 * View Channels

110 * Send Messages

111 * Send Messages in Threads

112 * Read Message History

113 * Attach Files

114 * Add Reactions

115 

116 Open the generated URL to add the bot to your server.

117 </Step>

118 

119 <Step title="Install the plugin">

120 In Claude Code, run:

121 

122 ```

123 /plugin install discord@claude-plugins-official

124 ```

125 

126 If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

127 

128 After installing, run `/reload-plugins` to activate the plugin's configure command.

129 </Step>

130 

131 <Step title="Configure your token">

132 Run the configure command with the bot token you copied:

133 

134 ```

135 /discord:configure <token>

136 ```

137 

138 This saves it to `~/.claude/channels/discord/.env`. You can also set `DISCORD_BOT_TOKEN` in your shell environment before launching Claude Code.

139 </Step>

140 

141 <Step title="Restart with channels enabled">

142 Exit Claude Code and restart with the channel flag. This connects the Discord plugin so your bot can receive and respond to messages:

143 

144 ```bash theme={null}

145 claude --channels plugin:discord@claude-plugins-official

146 ```

147 </Step>

148 

149 <Step title="Pair your account">

150 DM your bot on Discord. The bot replies with a pairing code.

151 

152 <Note>If your bot doesn't respond, make sure Claude Code is running with `--channels` from the previous step. The bot can only reply while the channel is active.</Note>

153 

154 Back in Claude Code, run:

155 

156 ```

157 /discord:access pair <code>

158 ```

159 

160 Then lock down access so only your account can send messages:

161 

162 ```

163 /discord:access policy allowlist

164 ```

165 </Step>

166 </Steps>

167 </Tab>

168 

169 <Tab title="iMessage">

170 View the full [iMessage plugin source](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage).

171 

172 The iMessage channel reads your Messages database directly and sends replies through AppleScript. It requires macOS and needs no bot token or external service.

173 

174 <Steps>

175 <Step title="Grant Full Disk Access">

176 The Messages database at `~/Library/Messages/chat.db` is protected by macOS. The first time the server reads it, macOS prompts for access: click **Allow**. The prompt names whichever app launched Bun, such as Terminal, iTerm, or your IDE.

177 

178 If the prompt doesn't appear or you clicked Don't Allow, grant access manually under **System Settings > Privacy & Security > Full Disk Access** and add your terminal. Without this, the server exits immediately with `authorization denied`.

179 </Step>

180 

181 <Step title="Install the plugin">

182 In Claude Code, run:

183 

184 ```

185 /plugin install imessage@claude-plugins-official

186 ```

187 

188 If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

189 </Step>

190 

191 <Step title="Restart with channels enabled">

192 Exit Claude Code and restart with the channel flag:

193 

194 ```bash theme={null}

195 claude --channels plugin:imessage@claude-plugins-official

196 ```

197 </Step>

198 

199 <Step title="Text yourself">

200 Open Messages on any device signed into your Apple ID and send a message to yourself. It reaches Claude immediately: self-chat bypasses access control with no setup.

201 

202 <Note>The first reply Claude sends triggers a macOS Automation prompt asking if your terminal can control Messages. Click **OK**.</Note>

203 </Step>

204 

205 <Step title="Allow other senders">

206 By default, only your own messages pass through. To let another contact reach Claude, add their handle:

207 

208 ```

209 /imessage:access allow +15551234567

210 ```

211 

212 Handles are phone numbers in `+country` format or Apple ID emails like `user@example.com`.

213 </Step>

214 </Steps>

215 </Tab>

216</Tabs>

217 

218You can also [build your own channel](/en/channels-reference) for systems that don't have a plugin yet.

219 

220## Quickstart

221 

222Fakechat is an officially supported demo channel that runs a chat UI on localhost, with nothing to authenticate and no external service to configure.

223 

224Once you install and enable fakechat, you can type in the browser and the message arrives in your Claude Code session. Claude replies, and the reply shows up back in the browser. After you've tested the fakechat interface, try out [Telegram](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram), [Discord](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord), or [iMessage](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage).

225 

226To try the fakechat demo, you'll need:

227 

228* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code) with a claude.ai account

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 settings

231 

232<Steps>

233 <Step title="Install the fakechat channel plugin">

234 Start a Claude Code session and run the install command:

235 

236 ```text theme={null}

237 /plugin install fakechat@claude-plugins-official

238 ```

239 

240 If Claude Code reports that the plugin is not found in any marketplace, your marketplace is either missing or outdated. Run `/plugin marketplace update claude-plugins-official` to refresh it, or `/plugin marketplace add anthropics/claude-plugins-official` if you haven't added it before. Then retry the install.

241 </Step>

242 

243 <Step title="Restart with the channel enabled">

244 Exit Claude Code, then restart with `--channels` and pass the fakechat plugin you installed:

245 

246 ```bash theme={null}

247 claude --channels plugin:fakechat@claude-plugins-official

248 ```

249 

250 The fakechat server starts automatically.

251 

252 <Tip>

253 You can pass several plugins to `--channels`, space-separated.

254 </Tip>

255 </Step>

256 

257 <Step title="Push a message in">

258 Open the fakechat UI at [http://localhost:8787](http://localhost:8787) and type a message:

259 

260 ```text theme={null}

261 hey, what's in my working directory?

262 ```

263 

264 The message arrives in your Claude Code session as a `<channel source="fakechat">` event. Claude reads it, does the work, and calls fakechat's `reply` tool. The answer shows up in the chat UI.

265 </Step>

266</Steps>

267 

268If Claude hits a permission prompt while you're away from the terminal, the session pauses until you respond. Channel servers that declare the [permission relay capability](/en/channels-reference#relay-permission-prompts) can forward these prompts to you so you can approve or deny remotely. For unattended use, [`--dangerously-skip-permissions`](/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) bypasses prompts entirely, but only use it in environments you trust.

269 

270## Security

271 

272Every approved channel plugin maintains a sender allowlist: only IDs you've added can push messages, and everyone else is silently dropped.

273 

274Telegram and Discord bootstrap the list by pairing:

275 

2761. Find your bot in Telegram or Discord and send it any message

2772. The bot replies with a pairing code

2783. In your Claude Code session, approve the code when prompted

2794. Your sender ID is added to the allowlist

280 

281iMessage works differently: texting yourself bypasses the gate automatically, and you add other contacts by handle with `/imessage:access allow`.

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

284 

285Being in `.mcp.json` isn't enough to push messages: a server also has to be named in `--channels`.

286 

287The allowlist also gates [permission relay](/en/channels-reference#relay-permission-prompts) if the channel declares it. Anyone who can reply through the channel can approve or deny tool use in your session, so only allowlist senders you trust with that authority.

288 

289## Enterprise controls

290 

291On Team and Enterprise plans, channels are off by default. Admins control availability through two [managed settings](/en/settings) that users cannot override:

292 

293| Setting | Purpose | When not configured |

294| :---------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |

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 |

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 |

297 

298Pro and Max users without an organization skip these checks entirely: channels are available and users opt in per session with `--channels`.

299 

300### Enable channels for your organization

301 

302Admins can enable channels from [**claude.ai → Admin settings → Claude Code → Channels**](https://claude.ai/admin-settings/claude-code), or by setting `channelsEnabled` to `true` in managed settings.

303 

304Once enabled, users in your organization can use `--channels` to opt channel servers into individual sessions. If the setting is disabled or unset, the MCP server still connects and its tools work, but channel messages won't arrive. A startup warning tells the user to have an admin enable the setting.

305 

306### Restrict which channel plugins can run

307 

308By default, any plugin on the Anthropic-maintained allowlist can register as a channel. Admins on Team and Enterprise plans can replace that allowlist with their own by setting `allowedChannelPlugins` in managed settings. Use this to restrict which official plugins are allowed, approve channels from your own internal marketplace, or both. Each entry names a plugin and the marketplace it comes from:

309 

310```json theme={null}

311{

312 "channelsEnabled": true,

313 "allowedChannelPlugins": [

314 { "marketplace": "claude-plugins-official", "plugin": "telegram" },

315 { "marketplace": "claude-plugins-official", "plugin": "discord" },

316 { "marketplace": "acme-corp-plugins", "plugin": "internal-alerts" }

317 ]

318}

319```

320 

321When `allowedChannelPlugins` is set, it replaces the Anthropic allowlist entirely: only the listed plugins can register. Leave it unset to fall back to the default Anthropic allowlist. An empty array blocks all channel plugins from the allowlist, but `--dangerously-load-development-channels` can still bypass it for local testing. To block channels entirely including the development flag, leave `channelsEnabled` unset instead.

322 

323This setting requires `channelsEnabled: true`. If a user passes a plugin to `--channels` that isn't on your list, Claude Code starts normally but the channel doesn't register, and the startup notice explains that the plugin isn't on the organization's approved list.

324 

325## Research preview

326 

327Channels are a research preview feature. Availability is rolling out gradually, and the `--channels` flag syntax and protocol contract may change based on feedback.

328 

329During the preview, `--channels` only accepts plugins from an Anthropic-maintained allowlist, or from your organization's allowlist if an admin has set [`allowedChannelPlugins`](#restrict-which-channel-plugins-can-run). The channel plugins in [claude-plugins-official](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins) are the default approved set. If you pass something that isn't on the effective allowlist, Claude Code starts normally but the channel doesn't register, and the startup notice tells you why.

330 

331To test a channel you're building, use `--dangerously-load-development-channels`. See [Test during the research preview](/en/channels-reference#test-during-the-research-preview) for information about testing custom channels that you build.

332 

333Report issues or feedback on the [Claude Code GitHub repository](https://github.com/anthropics/claude-code/issues).

334 

335## How channels compare

336 

337Several Claude Code features connect to systems outside the terminal, each suited to a different kind of work:

338 

339| Feature | What it does | Good for |

340| ---------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------- |

341| [Claude Code on the web](/en/claude-code-on-the-web) | Runs tasks in a fresh cloud sandbox, cloned from GitHub | Delegating self-contained async work you check on later |

342| [Claude in Slack](/en/slack) | Spawns a web session from an `@Claude` mention in a channel or thread | Starting tasks directly from team conversation context |

343| Standard [MCP server](/en/mcp) | Claude queries it during a task; nothing is pushed to the session | Giving Claude on-demand access to read or query a system |

344| [Remote Control](/en/remote-control) | You drive your local session from claude.ai or the Claude mobile app | Steering an in-progress session while away from your desk |

345 

346Channels fill the gap in that list by pushing events from non-Claude sources into your already-running local session.

347 

348* **Chat bridge**: ask Claude something from your phone via Telegram, Discord, or iMessage, and the answer comes back in the same chat while the work runs on your machine against your real files.

349* **[Webhook receiver](/en/channels-reference#example-build-a-webhook-receiver)**: a webhook from CI, your error tracker, a deploy pipeline, or other external service arrives where Claude already has your files open and remembers what you were debugging.

350 

351## Next steps

352 

353Once you have a channel running, explore these related features:

354 

355* [Build your own channel](/en/channels-reference) for systems that don't have plugins yet

356* [Remote Control](/en/remote-control) to drive a local session from your phone instead of forwarding events into it

357* [Scheduled tasks](/en/scheduled-tasks) to poll on a timer instead of reacting to pushed events

channels-reference.md +749 −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# Channels reference

6 

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 

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

11</Note>

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.

14 

15You can build a one-way or two-way channel. One-way channels forward alerts, webhooks, or monitoring events for Claude to act on. Two-way channels like chat bridges also [expose a reply tool](#expose-a-reply-tool) so Claude can send messages back. A channel with a trusted sender path can also opt in to [relay permission prompts](#relay-permission-prompts) so you can approve or deny tool use remotely.

16 

17This page covers:

18 

19* [Overview](#overview): how channels work

20* [What you need](#what-you-need): requirements and general steps

21* [Example: build a webhook receiver](#example-build-a-webhook-receiver): a minimal one-way walkthrough

22* [Server options](#server-options): the constructor fields

23* [Notification format](#notification-format): the event payload

24* [Expose a reply tool](#expose-a-reply-tool): let Claude send messages back

25* [Gate inbound messages](#gate-inbound-messages): sender checks to prevent prompt injection

26* [Relay permission prompts](#relay-permission-prompts): forward tool approval prompts to remote channels

27 

28To use an existing channel instead of building one, see [Channels](/en/channels). Telegram, Discord, iMessage, and fakechat are included in the research preview.

29 

30## Overview

31 

32A channel is an [MCP](https://modelcontextprotocol.io) server that runs on the same machine as Claude Code. Claude Code spawns it as a subprocess and communicates over stdio. Your channel server is the bridge between external systems and the Claude Code session:

33 

34* **Chat platforms** (Telegram, Discord): your plugin runs locally and polls the platform's API for new messages. When someone DMs your bot, the plugin receives the message and forwards it to Claude. No URL to expose.

35* **Webhooks** (CI, monitoring): your server listens on a local HTTP port. External systems POST to that port, and your server pushes the payload to Claude.

36 

37<img src="https://mintcdn.com/claude-code/zbUxPYi8065L3Y_P/en/images/channel-architecture.svg?fit=max&auto=format&n=zbUxPYi8065L3Y_P&q=85&s=fd6b6b949eab38264043d2a96285a57c" alt="Architecture diagram showing external systems connecting to your local channel server, which communicates with Claude Code over stdio" width="600" height="220" data-path="en/images/channel-architecture.svg" />

38 

39## What you need

40 

41The only hard requirement is the [`@modelcontextprotocol/sdk`](https://www.npmjs.com/package/@modelcontextprotocol/sdk) package and a Node.js-compatible runtime. [Bun](https://bun.sh), [Node](https://nodejs.org), and [Deno](https://deno.com) all work. The pre-built plugins in the research preview use Bun, but your channel doesn't have to.

42 

43Your server needs to:

44 

451. Declare the `claude/channel` capability so Claude Code registers a notification listener

462. Emit `notifications/claude/channel` events when something happens

473. Connect over [stdio transport](https://modelcontextprotocol.io/docs/concepts/transports#standard-io) (Claude Code spawns your server as a subprocess)

48 

49The [Server options](#server-options) and [Notification format](#notification-format) sections cover each of these in detail. See [Example: build a webhook receiver](#example-build-a-webhook-receiver) for a full walkthrough.

50 

51During the research preview, custom channels aren't on the [approved allowlist](/en/channels#supported-channels). Use `--dangerously-load-development-channels` to test locally. See [Test during the research preview](#test-during-the-research-preview) for details.

52 

53## Example: build a webhook receiver

54 

55This walkthrough builds a single-file server that listens for HTTP requests and forwards them into your Claude Code session. By the end, anything that can send an HTTP POST, like a CI pipeline, a monitoring alert, or a `curl` command, can push events to Claude.

56 

57This example uses [Bun](https://bun.sh) as the runtime for its built-in HTTP server and TypeScript support. You can use [Node](https://nodejs.org) or [Deno](https://deno.com) instead; the only requirement is the [MCP SDK](https://www.npmjs.com/package/@modelcontextprotocol/sdk).

58 

59<Steps>

60 <Step title="Create the project">

61 Create a new directory and install the MCP SDK:

62 

63 ```bash theme={null}

64 mkdir webhook-channel && cd webhook-channel

65 bun add @modelcontextprotocol/sdk

66 ```

67 </Step>

68 

69 <Step title="Write the channel server">

70 Create a file called `webhook.ts`. This is your entire channel server: it connects to Claude Code over stdio, and it listens for HTTP POSTs on port 8788. When a request arrives, it pushes the body to Claude as a channel event.

71 

72 ```ts title="webhook.ts" theme={null}

73 #!/usr/bin/env bun

74 import { Server } from '@modelcontextprotocol/sdk/server/index.js'

75 import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

76 

77 // Create the MCP server and declare it as a channel

78 const mcp = new Server(

79 { name: 'webhook', version: '0.0.1' },

80 {

81 // this key is what makes it a channel — Claude Code registers a listener for it

82 capabilities: { experimental: { 'claude/channel': {} } },

83 // added to Claude's system prompt so it knows how to handle these events

84 instructions: 'Events from the webhook channel arrive as <channel source="webhook" ...>. They are one-way: read them and act, no reply expected.',

85 },

86 )

87 

88 // Connect to Claude Code over stdio (Claude Code spawns this process)

89 await mcp.connect(new StdioServerTransport())

90 

91 // Start an HTTP server that forwards every POST to Claude

92 Bun.serve({

93 port: 8788, // any open port works

94 // localhost-only: nothing outside this machine can POST

95 hostname: '127.0.0.1',

96 async fetch(req) {

97 const body = await req.text()

98 await mcp.notification({

99 method: 'notifications/claude/channel',

100 params: {

101 content: body, // becomes the body of the <channel> tag

102 // each key becomes a tag attribute, e.g. <channel path="/" method="POST">

103 meta: { path: new URL(req.url).pathname, method: req.method },

104 },

105 })

106 return new Response('ok')

107 },

108 })

109 ```

110 

111 The file does three things in order:

112 

113 * **Server configuration**: creates the MCP server with `claude/channel` in its capabilities, which is what tells Claude Code this is a channel. The [`instructions`](#server-options) string goes into Claude's system prompt: tell Claude what events to expect, whether to reply, and how to route replies if it should.

114 * **Stdio connection**: connects to Claude Code over stdin/stdout. This is standard for any [MCP server](https://modelcontextprotocol.io/docs/concepts/transports#standard-io): Claude Code spawns it as a subprocess.

115 * **HTTP listener**: starts a local web server on port 8788. Every POST body gets forwarded to Claude as a channel event via `mcp.notification()`. The `content` becomes the event body, and each `meta` entry becomes an attribute on the `<channel>` tag. The listener needs access to the `mcp` instance, so it runs in the same process. You could split it into separate modules for a larger project.

116 </Step>

117 

118 <Step title="Register your server with Claude Code">

119 Add the server to your MCP config so Claude Code knows how to start it. For a project-level `.mcp.json` in the same directory, use a relative path. For user-level config in `~/.claude.json`, use the full absolute path so the server can be found from any project:

120 

121 ```json title=".mcp.json" theme={null}

122 {

123 "mcpServers": {

124 "webhook": { "command": "bun", "args": ["./webhook.ts"] }

125 }

126 }

127 ```

128 

129 Claude Code reads your MCP config at startup and spawns each server as a subprocess.

130 </Step>

131 

132 <Step title="Test it">

133 During the research preview, custom channels aren't on the allowlist, so start Claude Code with the development flag:

134 

135 ```bash theme={null}

136 claude --dangerously-load-development-channels server:webhook

137 ```

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.

140 

141 If you see "blocked by org policy," your Team or Enterprise admin needs to [enable channels](/en/channels#enterprise-controls) first.

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

144 

145 ```bash theme={null}

146 curl -X POST localhost:8788 -d "build failed on main: https://ci.example.com/run/1234"

147 ```

148 

149 The payload arrives in your Claude Code session as a `<channel>` tag:

150 

151 ```text theme={null}

152 <channel source="webhook" path="/" method="POST">build failed on main: https://ci.example.com/run/1234</channel>

153 ```

154 

155 In your Claude Code terminal, you'll see Claude receive the message and start responding: reading files, running commands, or whatever the message calls for. This is a one-way channel, so Claude acts in your session but doesn't send anything back through the webhook. To add replies, see [Expose a reply tool](#expose-a-reply-tool).

156 

157 If the event doesn't arrive, the diagnosis depends on what `curl` returned:

158 

159 * **`curl` succeeds but nothing reaches Claude**: run `/mcp` in your session to check the server's status. "Failed to connect" usually means a dependency or import error in your server file; check the debug log at `~/.claude/debug/<session-id>.txt` for the stderr trace.

160 * **`curl` fails with "connection refused"**: the port is either not bound yet or a stale process from an earlier run is holding it. `lsof -i :<port>` shows what's listening; `kill` the stale process before restarting your session.

161 </Step>

162</Steps>

163 

164The [fakechat server](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat) extends this pattern with a web UI, file attachments, and a reply tool for two-way chat.

165 

166## Test during the research preview

167 

168During the research preview, every channel must be on the [approved allowlist](/en/channels#research-preview) to register. The development flag bypasses the allowlist for specific entries after a confirmation prompt. This example shows both entry types:

169 

170```bash theme={null}

171# Testing a plugin you're developing

172claude --dangerously-load-development-channels plugin:yourplugin@yourmarketplace

173 

174# Testing a bare .mcp.json server (no plugin wrapper yet)

175claude --dangerously-load-development-channels server:webhook

176```

177 

178The bypass is per-entry. Combining this flag with `--channels` doesn't extend the bypass to the `--channels` entries. During the research preview, the approved allowlist is Anthropic-curated, so your channel stays on the development flag while you build and test.

179 

180<Note>

181 This flag skips the allowlist only. The `channelsEnabled` organization policy still applies. Don't use it to run channels from untrusted sources.

182</Note>

183 

184## Server options

185 

186A channel sets these options in the [`Server`](https://modelcontextprotocol.io/docs/concepts/servers) constructor. The `instructions` and `capabilities.tools` fields are [standard MCP](https://modelcontextprotocol.io/docs/concepts/servers); `capabilities.experimental['claude/channel']` and `capabilities.experimental['claude/channel/permission']` are the channel-specific additions:

187 

188| Field | Type | Description |

189| :------------------------------------------------------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

190| `capabilities.experimental['claude/channel']` | `object` | Required. Always `{}`. Presence registers the notification listener. |

191| `capabilities.experimental['claude/channel/permission']` | `object` | Optional. Always `{}`. Declares that this channel can receive permission relay requests. When declared, Claude Code forwards tool approval prompts to your channel so you can approve or deny them remotely. See [Relay permission prompts](#relay-permission-prompts). |

192| `capabilities.tools` | `object` | Two-way only. Always `{}`. Standard MCP tool capability. See [Expose a reply tool](#expose-a-reply-tool). |

193| `instructions` | `string` | Recommended. Added to Claude's system prompt. Tell Claude what events to expect, what the `<channel>` tag attributes mean, whether to reply, and if so which tool to use and which attribute to pass back (like `chat_id`). |

194 

195To create a one-way channel, omit `capabilities.tools`. This example shows a two-way setup with the channel capability, tools, and instructions set:

196 

197```ts theme={null}

198import { Server } from '@modelcontextprotocol/sdk/server/index.js'

199 

200const mcp = new Server(

201 { name: 'your-channel', version: '0.0.1' },

202 {

203 capabilities: {

204 experimental: { 'claude/channel': {} }, // registers the channel listener

205 tools: {}, // omit for one-way channels

206 },

207 // added to Claude's system prompt so it knows how to handle your events

208 instructions: 'Messages arrive as <channel source="your-channel" ...>. Reply with the reply tool.',

209 },

210)

211```

212 

213To push an event, call `mcp.notification()` with method `notifications/claude/channel`. The params are in the next section.

214 

215## Notification format

216 

217Your server emits `notifications/claude/channel` with two params:

218 

219| Field | Type | Description |

220| :-------- | :----------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

221| `content` | `string` | The event body. Delivered as the body of the `<channel>` tag. |

222| `meta` | `Record<string, string>` | Optional. Each entry becomes an attribute on the `<channel>` tag for routing context like chat ID, sender name, or alert severity. Keys must be identifiers: letters, digits, and underscores only. Keys containing hyphens or other characters are silently dropped. |

223 

224Your server pushes events by calling `mcp.notification()` on the `Server` instance. This example pushes a CI failure alert with two meta keys:

225 

226```ts theme={null}

227await mcp.notification({

228 method: 'notifications/claude/channel',

229 params: {

230 content: 'build failed on main: https://ci.example.com/run/1234',

231 meta: { severity: 'high', run_id: '1234' },

232 },

233})

234```

235 

236The event arrives in Claude's context wrapped in a `<channel>` tag. The `source` attribute is set automatically from your server's configured name:

237 

238```text theme={null}

239<channel source="your-channel" severity="high" run_id="1234">

240build failed on main: https://ci.example.com/run/1234

241</channel>

242```

243 

244## Expose a reply tool

245 

246If your channel is two-way, like a chat bridge rather than an alert forwarder, expose a standard [MCP tool](https://modelcontextprotocol.io/docs/concepts/tools) that Claude can call to send messages back. Nothing about the tool registration is channel-specific. A reply tool has three components:

247 

2481. A `tools: {}` entry in your `Server` constructor capabilities so Claude Code discovers the tool

2492. Tool handlers that define the tool's schema and implement the send logic

2503. An `instructions` string in your `Server` constructor that tells Claude when and how to call the tool

251 

252To add these to the [webhook receiver above](#example-build-a-webhook-receiver):

253 

254<Steps>

255 <Step title="Enable tool discovery">

256 In your `Server` constructor in `webhook.ts`, add `tools: {}` to the capabilities so Claude Code knows your server offers tools:

257 

258 ```ts theme={null}

259 capabilities: {

260 experimental: { 'claude/channel': {} },

261 tools: {}, // enables tool discovery

262 },

263 ```

264 </Step>

265 

266 <Step title="Register the reply tool">

267 Add the following to `webhook.ts`. The `import` goes at the top of the file with your other imports; the two handlers go between the `Server` constructor and `mcp.connect()`. This registers a `reply` tool that Claude can call with a `chat_id` and `text`:

268 

269 ```ts theme={null}

270 // Add this import at the top of webhook.ts

271 import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

272 

273 // Claude queries this at startup to discover what tools your server offers

274 mcp.setRequestHandler(ListToolsRequestSchema, async () => ({

275 tools: [{

276 name: 'reply',

277 description: 'Send a message back over this channel',

278 // inputSchema tells Claude what arguments to pass

279 inputSchema: {

280 type: 'object',

281 properties: {

282 chat_id: { type: 'string', description: 'The conversation to reply in' },

283 text: { type: 'string', description: 'The message to send' },

284 },

285 required: ['chat_id', 'text'],

286 },

287 }],

288 }))

289 

290 // Claude calls this when it wants to invoke a tool

291 mcp.setRequestHandler(CallToolRequestSchema, async req => {

292 if (req.params.name === 'reply') {

293 const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }

294 // send() is your outbound: POST to your chat platform, or for local

295 // testing the SSE broadcast shown in the full example below.

296 send(`Reply to ${chat_id}: ${text}`)

297 return { content: [{ type: 'text', text: 'sent' }] }

298 }

299 throw new Error(`unknown tool: ${req.params.name}`)

300 })

301 ```

302 </Step>

303 

304 <Step title="Update the instructions">

305 Update the `instructions` string in your `Server` constructor so Claude knows to route replies back through the tool. This example tells Claude to pass `chat_id` from the inbound tag:

306 

307 ```ts theme={null}

308 instructions: 'Messages arrive as <channel source="webhook" chat_id="...">. Reply with the reply tool, passing the chat_id from the tag.'

309 ```

310 </Step>

311</Steps>

312 

313Here's the complete `webhook.ts` with two-way support. Outbound replies stream over `GET /events` using [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE), so `curl -N localhost:8788/events` can watch them live; inbound chat arrives on `POST /`:

314 

315```ts title="Full webhook.ts with reply tool" expandable theme={null}

316#!/usr/bin/env bun

317import { Server } from '@modelcontextprotocol/sdk/server/index.js'

318import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

319import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

320 

321// --- Outbound: write to any curl -N listeners on /events --------------------

322// A real bridge would POST to your chat platform instead.

323const listeners = new Set<(chunk: string) => void>()

324function send(text: string) {

325 const chunk = text.split('\n').map(l => `data: ${l}\n`).join('') + '\n'

326 for (const emit of listeners) emit(chunk)

327}

328 

329const mcp = new Server(

330 { name: 'webhook', version: '0.0.1' },

331 {

332 capabilities: {

333 experimental: { 'claude/channel': {} },

334 tools: {},

335 },

336 instructions: 'Messages arrive as <channel source="webhook" chat_id="...">. Reply with the reply tool, passing the chat_id from the tag.',

337 },

338)

339 

340mcp.setRequestHandler(ListToolsRequestSchema, async () => ({

341 tools: [{

342 name: 'reply',

343 description: 'Send a message back over this channel',

344 inputSchema: {

345 type: 'object',

346 properties: {

347 chat_id: { type: 'string', description: 'The conversation to reply in' },

348 text: { type: 'string', description: 'The message to send' },

349 },

350 required: ['chat_id', 'text'],

351 },

352 }],

353}))

354 

355mcp.setRequestHandler(CallToolRequestSchema, async req => {

356 if (req.params.name === 'reply') {

357 const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }

358 send(`Reply to ${chat_id}: ${text}`)

359 return { content: [{ type: 'text', text: 'sent' }] }

360 }

361 throw new Error(`unknown tool: ${req.params.name}`)

362})

363 

364await mcp.connect(new StdioServerTransport())

365 

366let nextId = 1

367Bun.serve({

368 port: 8788,

369 hostname: '127.0.0.1',

370 idleTimeout: 0, // don't close idle SSE streams

371 async fetch(req) {

372 const url = new URL(req.url)

373 

374 // GET /events: SSE stream so curl -N can watch Claude's replies live

375 if (req.method === 'GET' && url.pathname === '/events') {

376 const stream = new ReadableStream({

377 start(ctrl) {

378 ctrl.enqueue(': connected\n\n') // so curl shows something immediately

379 const emit = (chunk: string) => ctrl.enqueue(chunk)

380 listeners.add(emit)

381 req.signal.addEventListener('abort', () => listeners.delete(emit))

382 },

383 })

384 return new Response(stream, {

385 headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },

386 })

387 }

388 

389 // POST: forward to Claude as a channel event

390 const body = await req.text()

391 const chat_id = String(nextId++)

392 await mcp.notification({

393 method: 'notifications/claude/channel',

394 params: {

395 content: body,

396 meta: { chat_id, path: url.pathname, method: req.method },

397 },

398 })

399 return new Response('ok')

400 },

401})

402```

403 

404The [fakechat server](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/fakechat) shows a more complete example with file attachments and message editing.

405 

406## Gate inbound messages

407 

408An ungated channel is a prompt injection vector. Anyone who can reach your endpoint can put text in front of Claude. A channel listening to a chat platform or a public endpoint needs a real sender check before it emits anything.

409 

410Check the sender against an allowlist before calling `mcp.notification()`. This example drops any message from a sender not in the set:

411 

412```ts theme={null}

413const allowed = new Set(loadAllowlist()) // from your access.json or equivalent

414 

415// inside your message handler, before emitting:

416if (!allowed.has(message.from.id)) { // sender, not room

417 return // drop silently

418}

419await mcp.notification({ ... })

420```

421 

422Gate on the sender's identity, not the chat or room identity: `message.from.id` in the example, not `message.chat.id`. In group chats, these differ, and gating on the room would let anyone in an allowlisted group inject messages into the session.

423 

424The [Telegram](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/telegram) and [Discord](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/discord) channels gate on a sender allowlist the same way. They bootstrap the list by pairing: the user DMs the bot, the bot replies with a pairing code, the user approves it in their Claude Code session, and their platform ID is added. See either implementation for the full pairing flow. The [iMessage](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins/imessage) channel takes a different approach: it detects the user's own addresses from the Messages database at startup and lets them through automatically, with other senders added by handle.

425 

426## Relay permission prompts

427 

428<Note>

429 Permission relay requires Claude Code v2.1.81 or later. Earlier versions ignore the `claude/channel/permission` capability.

430</Note>

431 

432When Claude calls a tool that needs approval, the local terminal dialog opens and the session waits. A two-way channel can opt in to receive the same prompt in parallel and relay it to you on another device. Both stay live: you can answer in the terminal or on your phone, and Claude Code applies whichever answer arrives first and closes the other.

433 

434Relay covers tool-use approvals like `Bash`, `Write`, and `Edit`. Project trust and MCP server consent dialogs don't relay; those only appear in the local terminal.

435 

436### How relay works

437 

438When a permission prompt opens, the relay loop has four steps:

439 

4401. Claude Code generates a short request ID and notifies your server

4412. Your server forwards the prompt and ID to your chat app

4423. The remote user replies with a yes or no and that ID

4434. Your inbound handler parses the reply into a verdict, and Claude Code applies it only if the ID matches an open request

444 

445The local terminal dialog stays open through all of this. If someone at the terminal answers before the remote verdict arrives, that answer is applied instead and the pending remote request is dropped.

446 

447<img src="https://mintcdn.com/claude-code/DsZvsJII1OmzIjIs/en/images/channel-permission-relay.svg?fit=max&auto=format&n=DsZvsJII1OmzIjIs&q=85&s=c1d75f6ee34c2757983e2cca899b90d1" alt="Sequence diagram: Claude Code sends a permission_request notification to the channel server, the server formats and sends the prompt to the chat app, the human replies with a verdict, and the server parses that reply into a permission notification back to Claude Code" width="600" height="230" data-path="en/images/channel-permission-relay.svg" />

448 

449### Permission request fields

450 

451The outbound notification from Claude Code is `notifications/claude/channel/permission_request`. Like the [channel notification](#notification-format), the transport is standard MCP but the method and schema are Claude Code extensions. The `params` object has four string fields your server formats into the outgoing prompt:

452 

453| Field | Description |

454| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

455| `request_id` | Five lowercase letters drawn from `a`-`z` without `l`, so it never reads as a `1` or `I` when typed on a phone. Include it in your outgoing prompt so it can be echoed in the reply. Claude Code only accepts a verdict that carries an ID it issued. The local terminal dialog doesn't display this ID, so your outbound handler is the only way to learn it. |

456| `tool_name` | Name of the tool Claude wants to use, for example `Bash` or `Write`. |

457| `description` | Human-readable summary of what this specific tool call does, the same text the local terminal dialog shows. For a Bash call this is Claude's description of the command, or the command itself if none was given. |

458| `input_preview` | The tool's arguments as a JSON string, truncated to 200 characters. For Bash this is the command; for Write it's the file path and a prefix of the content. Omit it from your prompt if you only have room for a one-line message. Your server decides what to show. |

459 

460The verdict your server sends back is `notifications/claude/channel/permission` with two fields: `request_id` echoing the ID above, and `behavior` set to `'allow'` or `'deny'`. Allow lets the tool call proceed; deny rejects it, the same as answering No in the local dialog. Neither verdict affects future calls.

461 

462### Add relay to a chat bridge

463 

464Adding permission relay to a two-way channel takes three components:

465 

4661. A `claude/channel/permission: {}` entry under `experimental` capabilities in your `Server` constructor so Claude Code knows to forward prompts

4672. A notification handler for `notifications/claude/channel/permission_request` that formats the prompt and sends it out through your platform API

4683. A check in your inbound message handler that recognizes `yes <id>` or `no <id>` and emits a `notifications/claude/channel/permission` verdict instead of forwarding the text to Claude

469 

470Only declare the capability if your channel [authenticates the sender](#gate-inbound-messages), because anyone who can reply through your channel can approve or deny tool use in your session.

471 

472To add these to a two-way chat bridge like the one assembled in [Expose a reply tool](#expose-a-reply-tool):

473 

474<Steps>

475 <Step title="Declare the permission capability">

476 In your `Server` constructor, add `claude/channel/permission: {}` alongside `claude/channel` under `experimental`:

477 

478 ```ts theme={null}

479 capabilities: {

480 experimental: {

481 'claude/channel': {},

482 'claude/channel/permission': {}, // opt in to permission relay

483 },

484 tools: {},

485 },

486 ```

487 </Step>

488 

489 <Step title="Handle the incoming request">

490 Register a notification handler between your `Server` constructor and `mcp.connect()`. Claude Code calls it with the [four request fields](#permission-request-fields) when a permission dialog opens. Your handler formats the prompt for your platform and includes instructions for replying with the ID:

491 

492 ```ts theme={null}

493 import { z } from 'zod'

494 

495 // setNotificationHandler routes by z.literal on the method field,

496 // so this schema is both the validator and the dispatch key

497 const PermissionRequestSchema = z.object({

498 method: z.literal('notifications/claude/channel/permission_request'),

499 params: z.object({

500 request_id: z.string(), // five lowercase letters, include verbatim in your prompt

501 tool_name: z.string(), // e.g. "Bash", "Write"

502 description: z.string(), // human-readable summary of this call

503 input_preview: z.string(), // tool args as JSON, truncated to ~200 chars

504 }),

505 })

506 

507 mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {

508 // send() is your outbound: POST to your chat platform, or for local

509 // testing the SSE broadcast shown in the full example below.

510 send(

511 `Claude wants to run ${params.tool_name}: ${params.description}\n\n` +

512 // the ID in the instruction is what your inbound handler parses in Step 3

513 `Reply "yes ${params.request_id}" or "no ${params.request_id}"`,

514 )

515 })

516 ```

517 </Step>

518 

519 <Step title="Intercept the verdict in your inbound handler">

520 Your inbound handler is the loop or callback that receives messages from your platform: the same place you [gate on sender](#gate-inbound-messages) and emit `notifications/claude/channel` to forward chat to Claude. Add a check before the chat-forwarding call that recognizes the verdict format and emits the permission notification instead.

521 

522 The regex matches the ID format Claude Code generates: five letters, never `l`. The `/i` flag tolerates phone autocorrect capitalizing the reply; lowercase the captured ID before sending it back.

523 

524 ```ts theme={null}

525 // matches "y abcde", "yes abcde", "n abcde", "no abcde"

526 // [a-km-z] is the ID alphabet Claude Code uses (lowercase, skips 'l')

527 // /i tolerates phone autocorrect; lowercase the capture before sending

528 const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i

529 

530 async function onInbound(message: PlatformMessage) {

531 if (!allowed.has(message.from.id)) return // gate on sender first

532 

533 const m = PERMISSION_REPLY_RE.exec(message.text)

534 if (m) {

535 // m[1] is the verdict word, m[2] is the request ID

536 // emit the verdict notification back to Claude Code instead of chat

537 await mcp.notification({

538 method: 'notifications/claude/channel/permission',

539 params: {

540 request_id: m[2].toLowerCase(), // normalize in case of autocorrect caps

541 behavior: m[1].toLowerCase().startsWith('y') ? 'allow' : 'deny',

542 },

543 })

544 return // handled as verdict, don't also forward as chat

545 }

546 

547 // didn't match verdict format: fall through to the normal chat path

548 await mcp.notification({

549 method: 'notifications/claude/channel',

550 params: { content: message.text, meta: { chat_id: String(message.chat.id) } },

551 })

552 }

553 ```

554 </Step>

555</Steps>

556 

557Claude Code also keeps the local terminal dialog open, so you can answer in either place, and the first answer to arrive is applied. A remote reply that doesn't exactly match the expected format fails in one of two ways, and in both cases the dialog stays open:

558 

559* **Different format**: your inbound handler's regex fails to match, so text like `approve it` or `yes` without an ID falls through as a normal message to Claude.

560* **Right format, wrong ID**: your server emits a verdict, but Claude Code finds no open request with that ID and drops it silently.

561 

562### Full example

563 

564The assembled `webhook.ts` below combines all three extensions from this page: the reply tool, sender gating, and permission relay. If you're starting here, you'll also need the [project setup and `.mcp.json` entry](#example-build-a-webhook-receiver) from the initial walkthrough.

565 

566To make both directions testable from curl, the HTTP listener serves two paths:

567 

568* **`GET /events`**: holds an SSE stream open and pushes each outbound message as a `data:` line, so `curl -N` can watch Claude's replies and permission prompts arrive live.

569* **`POST /`**: the inbound side, the same handler as earlier, now with the verdict-format check inserted before the chat-forward branch.

570 

571```ts title="Full webhook.ts with permission relay" expandable theme={null}

572#!/usr/bin/env bun

573import { Server } from '@modelcontextprotocol/sdk/server/index.js'

574import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'

575import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'

576import { z } from 'zod'

577 

578// --- Outbound: write to any curl -N listeners on /events --------------------

579// A real bridge would POST to your chat platform instead.

580const listeners = new Set<(chunk: string) => void>()

581function send(text: string) {

582 const chunk = text.split('\n').map(l => `data: ${l}\n`).join('') + '\n'

583 for (const emit of listeners) emit(chunk)

584}

585 

586// Sender allowlist. For the local walkthrough we trust the single X-Sender

587// header value "dev"; a real bridge would check the platform's user ID.

588const allowed = new Set(['dev'])

589 

590const mcp = new Server(

591 { name: 'webhook', version: '0.0.1' },

592 {

593 capabilities: {

594 experimental: {

595 'claude/channel': {},

596 'claude/channel/permission': {}, // opt in to permission relay

597 },

598 tools: {},

599 },

600 instructions:

601 'Messages arrive as <channel source="webhook" chat_id="...">. ' +

602 'Reply with the reply tool, passing the chat_id from the tag.',

603 },

604)

605 

606// --- reply tool: Claude calls this to send a message back -------------------

607mcp.setRequestHandler(ListToolsRequestSchema, async () => ({

608 tools: [{

609 name: 'reply',

610 description: 'Send a message back over this channel',

611 inputSchema: {

612 type: 'object',

613 properties: {

614 chat_id: { type: 'string', description: 'The conversation to reply in' },

615 text: { type: 'string', description: 'The message to send' },

616 },

617 required: ['chat_id', 'text'],

618 },

619 }],

620}))

621 

622mcp.setRequestHandler(CallToolRequestSchema, async req => {

623 if (req.params.name === 'reply') {

624 const { chat_id, text } = req.params.arguments as { chat_id: string; text: string }

625 send(`Reply to ${chat_id}: ${text}`)

626 return { content: [{ type: 'text', text: 'sent' }] }

627 }

628 throw new Error(`unknown tool: ${req.params.name}`)

629})

630 

631// --- permission relay: Claude Code (not Claude) calls this when a dialog opens

632const PermissionRequestSchema = z.object({

633 method: z.literal('notifications/claude/channel/permission_request'),

634 params: z.object({

635 request_id: z.string(),

636 tool_name: z.string(),

637 description: z.string(),

638 input_preview: z.string(),

639 }),

640})

641 

642mcp.setNotificationHandler(PermissionRequestSchema, async ({ params }) => {

643 send(

644 `Claude wants to run ${params.tool_name}: ${params.description}\n\n` +

645 `Reply "yes ${params.request_id}" or "no ${params.request_id}"`,

646 )

647})

648 

649await mcp.connect(new StdioServerTransport())

650 

651// --- HTTP on :8788: GET /events streams outbound, POST routes inbound -------

652const PERMISSION_REPLY_RE = /^\s*(y|yes|n|no)\s+([a-km-z]{5})\s*$/i

653let nextId = 1

654 

655Bun.serve({

656 port: 8788,

657 hostname: '127.0.0.1',

658 idleTimeout: 0, // don't close idle SSE streams

659 async fetch(req) {

660 const url = new URL(req.url)

661 

662 // GET /events: SSE stream so curl -N can watch replies and prompts live

663 if (req.method === 'GET' && url.pathname === '/events') {

664 const stream = new ReadableStream({

665 start(ctrl) {

666 ctrl.enqueue(': connected\n\n') // so curl shows something immediately

667 const emit = (chunk: string) => ctrl.enqueue(chunk)

668 listeners.add(emit)

669 req.signal.addEventListener('abort', () => listeners.delete(emit))

670 },

671 })

672 return new Response(stream, {

673 headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },

674 })

675 }

676 

677 // everything else is inbound: gate on sender first

678 const body = await req.text()

679 const sender = req.headers.get('X-Sender') ?? ''

680 if (!allowed.has(sender)) return new Response('forbidden', { status: 403 })

681 

682 // check for verdict format before treating as chat

683 const m = PERMISSION_REPLY_RE.exec(body)

684 if (m) {

685 await mcp.notification({

686 method: 'notifications/claude/channel/permission',

687 params: {

688 request_id: m[2].toLowerCase(),

689 behavior: m[1].toLowerCase().startsWith('y') ? 'allow' : 'deny',

690 },

691 })

692 return new Response('verdict recorded')

693 }

694 

695 // normal chat: forward to Claude as a channel event

696 const chat_id = String(nextId++)

697 await mcp.notification({

698 method: 'notifications/claude/channel',

699 params: { content: body, meta: { chat_id, path: url.pathname } },

700 })

701 return new Response('ok')

702 },

703})

704```

705 

706Test the verdict path in three terminals. The first is your Claude Code session, started with the [development flag](#test-during-the-research-preview) so it spawns `webhook.ts`:

707 

708```bash theme={null}

709claude --dangerously-load-development-channels server:webhook

710```

711 

712In the second, stream the outbound side so you can see Claude's replies and any permission prompts as they fire:

713 

714```bash theme={null}

715curl -N localhost:8788/events

716```

717 

718In the third, send a message that will make Claude try to run a command:

719 

720```bash theme={null}

721curl -d "list the files in this directory" -H "X-Sender: dev" localhost:8788

722```

723 

724The local permission dialog opens in your Claude Code terminal. A moment later the prompt appears in the `/events` stream, including the five-letter ID. Approve it from the remote side:

725 

726```bash theme={null}

727curl -d "yes <id>" -H "X-Sender: dev" localhost:8788

728```

729 

730The local dialog closes and the tool runs. Claude's reply comes back through the `reply` tool and lands in the stream too.

731 

732The three channel-specific pieces in this file:

733 

734* **Capabilities** in the `Server` constructor: `claude/channel` registers the notification listener, `claude/channel/permission` opts in to permission relay, `tools` lets Claude discover the reply tool.

735* **Outbound paths**: the `reply` tool handler is what Claude calls for conversational responses; the `PermissionRequestSchema` notification handler is what Claude Code calls when a permission dialog opens. Both call `send()` to broadcast over `/events`, but they're triggered by different parts of the system.

736* **HTTP handler**: `GET /events` holds an SSE stream open so curl can watch outbound live; `POST` is inbound, gated on the `X-Sender` header. A `yes <id>` or `no <id>` body goes to Claude Code as a verdict notification and never reaches Claude; anything else is forwarded to Claude as a channel event.

737 

738## Package as a plugin

739 

740To make your channel installable and shareable, wrap it in a [plugin](/en/plugins) and publish it to a [marketplace](/en/plugin-marketplaces). Users install it with `/plugin install`, then enable it per session with `--channels plugin:<name>@<marketplace>`.

741 

742A channel published to your own marketplace still needs `--dangerously-load-development-channels` to run, since it isn't on the [approved allowlist](/en/channels#supported-channels). To get it added, [submit it to the official marketplace](/en/plugins#submit-your-plugin-to-the-official-marketplace). Channel plugins go through security review before being approved. On Team and Enterprise plans, an admin can instead include your plugin in the organization's own [`allowedChannelPlugins`](/en/channels#restrict-which-channel-plugins-can-run) list, which replaces the default Anthropic allowlist.

743 

744## See also

745 

746* [Channels](/en/channels) to install and use Telegram, Discord, iMessage, or the fakechat demo, and to enable channels for a Team or Enterprise org

747* [Working channel implementations](https://github.com/anthropics/claude-plugins-official/tree/main/external_plugins) for complete server code with pairing flows, reply tools, and file attachments

748* [MCP](/en/mcp) for the underlying protocol that channel servers implement

749* [Plugins](/en/plugins) to package your channel so users can install it with `/plugin install`

checkpointing.md +36 −12

Details

1> ## Documentation Index

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

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

4 

1# Checkpointing5# Checkpointing

2 6 

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

4 8 

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

6 10 


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

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

18 22 

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

24 

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

26 

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

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

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

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

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

32 

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

34 

35#### Restore vs. summarize

36 

37The three restore options revert state: they undo code changes, conversation history, or both. "Summarize from here" works differently:

38 

39* Messages before the selected message stay intact

40* The selected message and all subsequent messages get replaced with a compact AI-generated summary

41* No files on disk are changed

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

20 43 

21Press `Esc` twice (`Esc` + `Esc`) or use the `/rewind` command to open up the rewind menu. You can choose to restore: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.

22 45 

23* **Conversation only**: Rewind to a user message while keeping code changes46<Note>

24* **Code only**: Revert file changes while keeping the conversation47 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`).

25* **Both code and conversation**: Restore both to a prior point in the session48</Note>

26 49 

27## Common use cases50## Common use cases

28 51 

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

30 53 

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

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

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

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

34 58 

35## Limitations59## Limitations

36 60 


60 84 

61## See also85## See also

62 86 

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

64* [Slash commands](/en/docs/claude-code/slash-commands) - Accessing checkpoints using `/rewind`88* [Built-in commands](/en/commands) - Accessing checkpoints using `/rewind`

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

chrome.md +232 −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# Use Claude Code with Chrome (beta)

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.

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.

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.

12 

13<Note>

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

15</Note>

16 

17## Capabilities

18 

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

20 

21* **Live debugging**: read console errors and DOM state directly, then fix the code that caused them

22* **Design verification**: build a UI from a Figma mock, then open it in the browser to verify it matches

23* **Web app testing**: test form validation, check for visual regressions, or verify user flows

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

25* **Data extraction**: pull structured information from web pages and save it locally

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

27* **Session recording**: record browser interactions as GIFs to document or share what happened

28 

29## Prerequisites

30 

31Before using Claude Code with Chrome, you need:

32 

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

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

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

36* A direct Anthropic plan (Pro, Max, Team, or Enterprise)

37 

38<Note>

39 Chrome integration is not available through third-party providers like Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature.

40</Note>

41 

42## Get started in the CLI

43 

44<Steps>

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

46 Start Claude Code with the `--chrome` flag:

47 

48 ```bash theme={null}

49 claude --chrome

50 ```

51 

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

53 </Step>

54 

55 <Step title="Ask Claude to use the browser">

56 This example navigates to a page, interacts with it, and reports what it finds, all from your terminal or editor:

57 

58 ```text theme={null}

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

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

61 ```

62 </Step>

63</Steps>

64 

65Run `/chrome` at any time to check the connection status, manage permissions, or reconnect the extension.

66 

67For VS Code, see [browser automation in VS Code](/en/vs-code#automate-browser-tasks-with-chrome).

68 

69### Enable Chrome by default

70 

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

72 

73In the [VS Code extension](/en/vs-code#automate-browser-tasks-with-chrome), Chrome is available whenever the Chrome extension is installed. No additional flag is needed.

74 

75<Note>

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

77</Note>

78 

79### Manage site permissions

80 

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

82 

83## Example workflows

84 

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

86 

87### Test a local web application

88 

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

90 

91```text theme={null}

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

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

94messages appear correctly?

95```

96 

97Claude navigates to your local server, interacts with the form, and reports what it observes.

98 

99### Debug with console logs

100 

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

102 

103```text theme={null}

104Open the dashboard page and check the console for any errors when

105the page loads.

106```

107 

108Claude reads the console messages and can filter for specific patterns or error types.

109 

110### Automate form filling

111 

112Speed up repetitive data entry tasks:

113 

114```text theme={null}

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

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

117name, email, and phone fields.

118```

119 

120Claude reads your local file, navigates the web interface, and enters the data for each record.

121 

122### Draft content in Google Docs

123 

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

125 

126```text theme={null}

127Draft a project update based on the recent commits and add it to my

128Google Doc at docs.google.com/document/d/abc123

129```

130 

131Claude opens the document, clicks into the editor, and types the content. This works with any web app you're logged into: Gmail, Notion, Sheets, and more.

132 

133### Extract data from web pages

134 

135Pull structured information from websites:

136 

137```text theme={null}

138Go to the product listings page and extract the name, price, and

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

140```

141 

142Claude navigates to the page, reads the content, and compiles the data into a structured format.

143 

144### Run multi-site workflows

145 

146Coordinate tasks across multiple websites:

147 

148```text theme={null}

149Check my calendar for meetings tomorrow, then for each meeting with

150an external attendee, look up their company website and add a note

151about what they do.

152```

153 

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

155 

156### Record a demo GIF

157 

158Create shareable recordings of browser interactions:

159 

160```text theme={null}

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

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

163```

164 

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

166 

167## Troubleshooting

168 

169### Extension not detected

170 

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

172 

1731. Verify the Chrome extension is installed and enabled in `chrome://extensions`

1742. Verify Claude Code is up to date by running `claude --version`

1753. Check that Chrome is running

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

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

178 

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

180 

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

182 

183For Chrome:

184 

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

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

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

188 

189For Edge:

190 

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

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

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

194 

195### Browser not responding

196 

197If Claude's browser commands stop working:

198 

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

2002. Ask Claude to create a new tab and try again

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

202 

203### Connection drops during long sessions

204 

205The Chrome extension's service worker can go idle during extended sessions, which breaks the connection. If browser tools stop working after a period of inactivity, run `/chrome` and select "Reconnect extension".

206 

207### Windows-specific issues

208 

209On Windows, you may encounter:

210 

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

212* **Native messaging host errors**: if the native messaging host crashes on startup, try reinstalling Claude Code to regenerate the host configuration.

213 

214### Common error messages

215 

216These are the most frequently encountered errors and how to resolve them:

217 

218| Error | Cause | Fix |

219| ------------------------------------ | ------------------------------------------------ | --------------------------------------------------------------- |

220| "Browser extension is not connected" | Native messaging host cannot reach the extension | Restart Chrome and Claude Code, then run `/chrome` to reconnect |

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

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

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

224 

225## See also

226 

227* [Computer use](/en/computer-use): control native macOS apps when a task can't be done in a browser

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

229* [CLI reference](/en/cli-reference): command-line flags including `--chrome`

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

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

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

Details

1> ## Documentation Index

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

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

4 

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

2 6 

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


11Claude Code on the web lets developers kick off Claude Code from the Claude app. This is perfect for:15Claude Code on the web lets developers kick off Claude Code from the Claude app. This is perfect for:

12 16 

13* **Answering questions**: Ask about code architecture and how features are implemented17* **Answering questions**: Ask about code architecture and how features are implemented

14* **Bugfixes and routine tasks**: Well-defined tasks that don't require frequent steering18* **Bug fixes and routine tasks**: Well-defined tasks that don't require frequent steering

15* **Parallel work**: Tackle multiple bug fixes in parallel19* **Parallel work**: Tackle multiple bug fixes in parallel

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

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

18 22 

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

20 

21* **On the go**: Kick off tasks while commuting or away from laptop

22* **Monitoring**: Watch the trajectory and steer the agent's work

23 24 

24Developers can also move Claude Code sessions from the Claude app to their terminal to continue tasks locally.25You can [kick off new tasks on the web from your terminal](#from-terminal-to-web) with `--remote`, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally. To use the web interface while running Claude Code on your own machine instead of cloud infrastructure, see [Remote Control](/en/remote-control).

25 26 

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

27 28 


29 30 

30* **Pro users**31* **Pro users**

31* **Max users**32* **Max users**

32 33* **Team users**

33Coming soon to Team and Enterprise premium seat users.34* **Enterprise users** with premium seats or Chat + Claude Code seats

34 35 

35## Getting started36## Getting started

36 37 

38Set up Claude Code on the web from the browser or from your terminal.

39 

40### From the browser

41 

371. Visit [claude.ai/code](https://claude.ai/code)421. Visit [claude.ai/code](https://claude.ai/code)

382. Connect your GitHub account432. Connect your GitHub account

393. Install the Claude GitHub app in your repositories443. Install the Claude GitHub App in your repositories

404. Select your default environment454. Select your default environment

415. Submit your coding task465. Submit your coding task

426. Review changes and create a pull request in GitHub476. Review changes in diff view, iterate with comments, then create a pull request

48 

49### From the terminal

50 

51Run `/web-setup` inside Claude Code to connect GitHub using your local `gh` CLI credentials. The command syncs your `gh auth token` to Claude Code on the web, creates a default cloud environment, and opens claude.ai/code in your browser when it finishes.

52 

53This path requires the `gh` CLI to be installed and authenticated with `gh auth login`. If `gh` is not available, `/web-setup` opens claude.ai/code so you can connect GitHub from the browser instead.

54 

55Your `gh` credentials give Claude access to clone and push, so you can skip the GitHub App for basic sessions. Install the App later if you want [Auto-fix](#auto-fix-pull-requests), which uses the App to receive PR webhooks.

56 

57<Note>

58 Team and Enterprise admins can disable terminal setup with the Quick web setup toggle at [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code).

59</Note>

43 60 

44## How it works61## How it works

45 62 

46When you start a task on Claude Code on the web:63When you start a task on Claude Code on the web:

47 64 

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

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

503. **Network configuration**: Internet access is configured based on your settings673. **Network configuration**: Internet access is configured based on your settings

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

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

536. **Results**: Changes are pushed to a branch, ready for pull request creation706. **Results**: Changes are pushed to a branch, ready for pull request creation

54 71 

72## Review changes with diff view

73 

74Diff view lets you see exactly what Claude changed before creating a pull request. Instead of clicking "Create PR" to review changes in GitHub, view the diff directly in the app and iterate with Claude until the changes are ready.

75 

76When Claude makes changes to files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Select this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.

77 

78From the diff view, you can:

79 

80* Review changes file by file

81* Comment on specific changes to request modifications

82* Continue iterating with Claude based on what you see

83 

84This lets you refine changes through multiple rounds of feedback without creating draft PRs or switching to GitHub.

85 

86## Auto-fix pull requests

87 

88Claude can watch a pull request and automatically respond to CI failures and review comments. Claude subscribes to GitHub activity on the PR, and when a check fails or a reviewer leaves a comment, Claude investigates and pushes a fix if one is clear.

89 

90<Note>

91 Auto-fix requires the Claude GitHub App to be installed on your repository. If you haven't already, install it from the [GitHub App page](https://github.com/apps/claude) or when prompted during [setup](#getting-started).

92</Note>

93 

94There are a few ways to turn on auto-fix depending on where the PR came from and what device you're using:

95 

96* **PRs created in Claude Code on the web**: open the CI status bar and select **Auto-fix**

97* **From the mobile app**: tell Claude to auto-fix the PR, for example "watch this PR and fix any CI failures or review comments"

98* **Any existing PR**: paste the PR URL into a session and tell Claude to auto-fix it

99 

100### How Claude responds to PR activity

101 

102When auto-fix is active, Claude receives GitHub events for the PR including new review comments and CI check failures. For each event, Claude investigates and decides how to proceed:

103 

104* **Clear fixes**: if Claude is confident in a fix and it doesn't conflict with earlier instructions, Claude makes the change, pushes it, and explains what was done in the session

105* **Ambiguous requests**: if a reviewer's comment could be interpreted multiple ways or involves something architecturally significant, Claude asks you before acting

106* **Duplicate or no-action events**: if an event is a duplicate or requires no change, Claude notes it in the session and moves on

107 

108Claude may reply to review comment threads on GitHub as part of resolving them. These replies are posted using your GitHub account, so they appear under your username, but each reply is labeled as coming from Claude Code so reviewers know it was written by the agent and not by you directly.

109 

110<Warning>

111 If your repository uses comment-triggered automation such as Atlantis, Terraform Cloud, or custom GitHub Actions that run on `issue_comment` events, be aware that Claude can reply on your behalf, which can trigger those workflows. Review your repository's automation before enabling auto-fix, and consider disabling auto-fix for repositories where a PR comment can deploy infrastructure or run privileged operations.

112</Warning>

113 

55## Moving tasks between web and terminal114## Moving tasks between web and terminal

56 115 

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

117 

118<Note>

119 Session handoff is one-way: you can pull web sessions into your terminal, but you can't push an existing terminal session to the web. The `--remote` flag creates a *new* web session for your current repository.

120</Note>

121 

122### From terminal to web

123 

124Start a web session from the command line with the `--remote` flag:

125 

126```bash theme={null}

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

128```

129 

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

131 

132#### Tips for remote tasks

133 

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

135 

136```bash theme={null}

137claude --permission-mode plan

138```

139 

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

141 

142```bash theme={null}

143claude --remote "Execute the migration plan in docs/migration-plan.md"

144```

145 

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

147 

148**Plan in the cloud with ultraplan**: To draft and review the plan itself in a web session, use [ultraplan](/en/ultraplan). Claude generates the plan on Claude Code on the web while you keep working, then you comment on sections in your browser and choose to execute remotely or send the plan back to your terminal.

149 

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

151 

152```bash theme={null}

153claude --remote "Fix the flaky test in auth.spec.ts"

154claude --remote "Update the API documentation"

155claude --remote "Refactor the logger to use structured output"

156```

157 

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

159 

57### From web to terminal160### From web to terminal

58 161 

59After starting a task on the web:162There are several ways to pull a web session into your terminal:

163 

164* **Using `/teleport`**: From within Claude Code, run `/teleport` (or `/tp`) to see an interactive picker of your web sessions. If you have uncommitted changes, you'll be prompted to stash them first.

165* **Using `--teleport`**: From the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport <session-id>` to resume a specific session directly.

166* **From `/tasks`**: Run `/tasks` to see your background sessions, then press `t` to teleport into one

167* **From the web interface**: Click "Open in CLI" to copy a command you can paste into your terminal

168 

169When you teleport a session, Claude verifies you're in the correct repository, fetches and checks out the branch from the remote session, and loads the full conversation history into your terminal.

170 

171#### Requirements for teleporting

172 

173Teleport checks these requirements before resuming a session. If any requirement isn't met, you'll see an error or be prompted to resolve the issue.

174 

175| Requirement | Details |

176| ------------------ | ---------------------------------------------------------------------------------------------------------------------- |

177| Clean git state | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed. |

178| Correct repository | You must run `--teleport` from a checkout of the same repository, not a fork. |

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

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

181 

182### Sharing sessions

183 

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

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

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

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

188 

189#### Sharing from an Enterprise or Team account

190 

191For Enterprise and Team accounts, the two visibility options are **Private**

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

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

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

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

196sessions are automatically shared with Team visibility.

60 197 

611. Click the "Open in CLI" button198#### Sharing from a Max or Pro account

622. Paste and run the command in your terminal in a checkout of the repo199 

633. Any existing local changes will be stashed, and the remote session will be loaded200For Max and Pro accounts, the two visibility options are **Private**

644. Continue working locally201and **Public**. Public visibility makes the session visible to any user logged

202into claude.ai.

203 

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

205code and credentials from private GitHub repositories. Repository access

206verification is not enabled by default.

207 

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

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

210 

211## Schedule recurring tasks

212 

213Run Claude on a recurring schedule to automate work like daily PR reviews, dependency audits, and CI failure analysis. See [Schedule tasks on the web](/en/web-scheduled-tasks) for the full guide.

214 

215## Managing sessions

216 

217### Archiving sessions

218 

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

220 

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

222 

223### Deleting sessions

224 

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

226 

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

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

229 

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

65 231 

66## Cloud environment232## Cloud environment

67 233 


92The universal image includes pre-configured environments for:258The universal image includes pre-configured environments for:

93 259 

94* **Python**: Python 3.x with pip, poetry, and common scientific libraries260* **Python**: Python 3.x with pip, poetry, and common scientific libraries

95* **Node.js**: Latest LTS versions with npm, yarn, and pnpm261* **Node.js**: Latest LTS versions with npm, yarn, pnpm, and bun

262* **Ruby**: Versions 3.1.6, 3.2.6, 3.3.6 (default: 3.3.6) with gem, bundler, and rbenv for version management

263* **PHP**: Version 8.4.14

96* **Java**: OpenJDK with Maven and Gradle264* **Java**: OpenJDK with Maven and Gradle

97* **Go**: Latest stable version with module support265* **Go**: Latest stable version with module support

98* **Rust**: Rust toolchain with cargo266* **Rust**: Rust toolchain with cargo

99* **C++**: GCC and Clang compilers267* **C++**: GCC and Clang compilers

100 268 

269#### Databases

270 

271The universal image includes the following databases:

272 

273* **PostgreSQL**: Version 16

274* **Redis**: Version 7.0

275 

101### Environment configuration276### Environment configuration

102 277 

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

104 279 

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

106 281 

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

108 283 


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

115</Note>290</Note>

116 291 

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

118 293 

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

295 

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

120 297 

121<Note>298<Note>

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

123 300 

124 ```301 ```text theme={null}

125 API_KEY=your_api_key302 API_KEY=your_api_key

126 DEBUG=true303 DEBUG=true

127 ```304 ```

128</Note>305</Note>

129 306 

307### Setup scripts

308 

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

310 

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

312 

313<Tip>

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

315</Tip>

316 

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

318 

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

320 

321```bash theme={null}

322#!/bin/bash

323apt update && apt install -y gh

324```

325 

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

327 

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

329 

330<Note>

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

332</Note>

333 

334#### Setup scripts vs. SessionStart hooks

335 

336Use 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`.

337 

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

339 

340| | Setup scripts | SessionStart hooks |

341| ------------- | ------------------------------------------------- | -------------------------------------------------------------- |

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

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

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

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

346 

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

348 

130### Dependency management349### Dependency management

131 350 

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

352 

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

354 

355```bash theme={null}

356#!/bin/bash

357npm install

358pip install -r requirements.txt

359```

360 

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

133 362 

134```json theme={null}363```json theme={null}

135{364{


151 380 

152Create the corresponding script at `scripts/install_pkgs.sh`:381Create the corresponding script at `scripts/install_pkgs.sh`:

153 382 

154```bash theme={null}

155#!/bin/bash

156npm install

157pip install -r requirements.txt

158exit 0

159```

160 

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

162 

163#### Local vs remote execution

164 

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

166 

167```bash theme={null}383```bash theme={null}

168#!/bin/bash384#!/bin/bash

169 385 

170# Example: Only run in remote environments386# Only run in remote environments

171if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then387if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then

172 exit 0388 exit 0

173fi389fi

174 390 

175npm install391npm install

176pip install -r requirements.txt392pip install -r requirements.txt

393exit 0

177```394```

178 395 

179#### Persisting environment variables396Make it executable: `chmod +x scripts/install_pkgs.sh`

397 

398#### Persist environment variables

180 399 

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

401 

402#### Dependency management limitations

403 

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

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

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

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

182 408 

183## Network access and security409## Network access and security

184 410 


214 440 

215* api.anthropic.com441* api.anthropic.com

216* statsig.anthropic.com442* statsig.anthropic.com

443* platform.claude.com

444* code.claude.com

217* claude.ai445* claude.ai

218 446 

219#### Version Control447#### Version Control


221* github.com449* github.com

222* [www.github.com](http://www.github.com)450* [www.github.com](http://www.github.com)

223* api.github.com451* api.github.com

452* npm.pkg.github.com

224* raw\.githubusercontent.com453* raw\.githubusercontent.com

454* pkg-npm.githubusercontent.com

225* objects.githubusercontent.com455* objects.githubusercontent.com

226* codeload.github.com456* codeload.github.com

227* avatars.githubusercontent.com457* avatars.githubusercontent.com


243* [www.docker.com](http://www.docker.com)473* [www.docker.com](http://www.docker.com)

244* production.cloudflare.docker.com474* production.cloudflare.docker.com

245* download.docker.com475* download.docker.com

476* gcr.io

246* \*.gcr.io477* \*.gcr.io

247* ghcr.io478* ghcr.io

248* mcr.microsoft.com479* mcr.microsoft.com

249* \*.data.mcr.microsoft.com480* \*.data.mcr.microsoft.com

481* public.ecr.aws

250 482 

251#### Cloud Platforms483#### Cloud Platforms

252 484 


267* dot.net499* dot.net

268* visualstudio.com500* visualstudio.com

269* dev.azure.com501* dev.azure.com

502* \*.amazonaws.com

503* \*.api.aws

270* oracle.com504* oracle.com

271* [www.oracle.com](http://www.oracle.com)505* [www.oracle.com](http://www.oracle.com)

272* java.com506* java.com


316 550 

317* crates.io551* crates.io

318* [www.crates.io](http://www.crates.io)552* [www.crates.io](http://www.crates.io)

553* index.crates.io

319* static.crates.io554* static.crates.io

320* rustup.rs555* rustup.rs

321* static.rust-lang.org556* static.rust-lang.org


341* gradle.org576* gradle.org

342* [www.gradle.org](http://www.gradle.org)577* [www.gradle.org](http://www.gradle.org)

343* services.gradle.org578* services.gradle.org

579* plugins.gradle.org

580* kotlin.org

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

344* spring.io582* spring.io

345* repo.spring.io583* repo.spring.io

346 584 


414* statsig.com652* statsig.com

415* [www.statsig.com](http://www.statsig.com)653* [www.statsig.com](http://www.statsig.com)

416* api.statsig.com654* api.statsig.com

655* sentry.io

417* \*.sentry.io656* \*.sentry.io

657* http-intake.logs.datadoghq.com

658* \*.datadoghq.com

659* \*.datadoghq.eu

418 660 

419#### Content Delivery & Mirrors661#### Content Delivery & Mirrors

420 662 

663* sourceforge.net

421* \*.sourceforge.net664* \*.sourceforge.net

422* packagecloud.io665* packagecloud.io

423* \*.packagecloud.io666* \*.packagecloud.io


429* json.schemastore.org672* json.schemastore.org

430* [www.schemastore.org](http://www.schemastore.org)673* [www.schemastore.org](http://www.schemastore.org)

431 674 

675#### Model Context Protocol

676 

677* \*.modelcontextprotocol.io

678 

432<Note>679<Note>

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

434</Note>681</Note>


460## Limitations707## Limitations

461 708 

462* **Repository authentication**: You can only move sessions from web to local when you are authenticated to the same account709* **Repository authentication**: You can only move sessions from web to local when you are authenticated to the same account

463* **Platform restrictions**: Claude Code on the web only works with code hosted in GitHub. GitLab and other non-GitHub repositories cannot be used with cloud sessions710* **Platform restrictions**: Claude Code on the web only works with code hosted in GitHub. Self-hosted [GitHub Enterprise Server](/en/github-enterprise-server) instances are supported for Team and Enterprise plans. GitLab and other non-GitHub repositories cannot be used with cloud sessions

464 711 

465## Best practices712## Best practices

466 713 

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

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

469 716 

470## Related resources717## Related resources

471 718 

472* [Hooks configuration](/en/docs/claude-code/hooks)719* [Hooks configuration](/en/hooks)

473* [Settings reference](/en/docs/claude-code/settings)720* [Settings reference](/en/settings)

474* [Security](/en/docs/claude-code/security)721* [Security](/en/security)

475* [Data usage](/en/docs/claude-code/data-usage)722* [Data usage](/en/data-usage)

claude-directory.md +82 −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# Explore the .claude directory

6 

7> Where Claude Code reads CLAUDE.md, settings.json, hooks, skills, commands, subagents, rules, and auto memory. Explore the .claude directory in your project and ~/.claude in your home directory.

8 

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.

11 

12Most users only edit `CLAUDE.md` and `settings.json`. The rest of the directory is optional: add skills, rules, or subagents as you need them.

13 

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

15 

16<ClaudeExplorer />

17 

18## What's not shown

19 

20The explorer covers the files you'll interact with most. A few things live elsewhere:

21 

22| File | Location | Purpose |

23| ----------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------- |

24| `managed-settings.json` | System-level, varies by OS | Enterprise-enforced settings that you can't override. See [server-managed settings](/en/server-managed-settings). |

25| `CLAUDE.local.md` | Project root | Your private preferences for this project, loaded alongside CLAUDE.md. Create it manually and add it to `.gitignore`. |

26 

27## File reference

28 

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

30 

31<Note>

32 Several things can override what you put in these files:

33 

34 * [Managed settings](/en/server-managed-settings) deployed by your organization take precedence over everything

35 * CLI flags like `--permission-mode` or `--settings` override `settings.json` for that session

36 * Some environment variables take precedence over their equivalent setting, but this varies: check the [environment variables reference](/en/env-vars) for each one

37 

38 See [settings precedence](/en/settings#settings-precedence) for the full order.

39</Note>

40 

41Click a filename to open that node in the explorer above.

42 

43| File | Scope | Commit | What it does | Reference |

44| --------------------------------------------------- | ------------------ | ------ | ----------------------------------------------------- | -------------------------------------------------------------------- |

45| [`CLAUDE.md`](#ce-claude-md) | Project and global | ✓ | Instructions loaded every session | [Memory](/en/memory) |

46| [`rules/*.md`](#ce-rules) | Project and global | ✓ | Topic-scoped instructions, optionally path-gated | [Rules](/en/memory#organize-rules-with-claude/rules/) |

47| [`settings.json`](#ce-settings-json) | Project and global | ✓ | Permissions, hooks, env vars, model defaults | [Settings](/en/settings) |

48| [`settings.local.json`](#ce-settings-local-json) | Project only | | Your personal overrides, auto-gitignored | [Settings scopes](/en/settings#settings-files) |

49| [`.mcp.json`](#ce-mcp-json) | Project only | ✓ | Team-shared MCP servers | [MCP scopes](/en/mcp#mcp-installation-scopes) |

50| [`.worktreeinclude`](#ce-worktreeinclude) | Project only | ✓ | Gitignored files to copy into new worktrees | [Worktrees](/en/common-workflows#copy-gitignored-files-to-worktrees) |

51| [`skills/<name>/SKILL.md`](#ce-skills) | Project and global | ✓ | Reusable prompts invoked with `/name` or auto-invoked | [Skills](/en/skills) |

52| [`commands/*.md`](#ce-commands) | Project and global | ✓ | Single-file prompts; same mechanism as skills | [Skills](/en/skills) |

53| [`output-styles/*.md`](#ce-output-styles) | Project and global | ✓ | Custom system-prompt sections | [Output styles](/en/output-styles) |

54| [`agents/*.md`](#ce-agents) | Project and global | ✓ | Subagent definitions with their own prompt and tools | [Subagents](/en/sub-agents) |

55| [`agent-memory/<name>/`](#ce-agent-memory) | Project and global | ✓ | Persistent memory for subagents | [Persistent memory](/en/sub-agents#enable-persistent-memory) |

56| [`~/.claude.json`](#ce-claude-json) | Global only | | App state, OAuth, UI toggles, personal MCP servers | [Global config](/en/settings#global-config-settings) |

57| [`projects/<project>/memory/`](#ce-global-projects) | Global only | | Auto memory: Claude's notes to itself across sessions | [Auto memory](/en/memory#auto-memory) |

58| [`keybindings.json`](#ce-keybindings) | Global only | | Custom keyboard shortcuts | [Keybindings](/en/keybindings) |

59 

60## Check what loaded

61 

62The explorer shows what files can exist. To see what actually loaded in your current session, use these commands:

63 

64| Command | Shows |

65| -------------- | ------------------------------------------------------------------------------------- |

66| `/context` | Token usage by category: system prompt, memory files, skills, MCP tools, and messages |

67| `/memory` | Which CLAUDE.md and rules files loaded, plus auto-memory entries |

68| `/agents` | Configured subagents and their settings |

69| `/hooks` | Active hook configurations |

70| `/mcp` | Connected MCP servers and their status |

71| `/skills` | Available skills from project, user, and plugin sources |

72| `/permissions` | Current allow and deny rules |

73| `/doctor` | Installation and configuration diagnostics |

74 

75Run `/context` first for the overview, then the specific command for the area you want to investigate.

76 

77## Related resources

78 

79* [Manage Claude's memory](/en/memory): write and organize CLAUDE.md, rules, and auto memory

80* [Configure settings](/en/settings): set permissions, hooks, environment variables, and model defaults

81* [Create skills](/en/skills): build reusable prompts and workflows

82* [Configure subagents](/en/sub-agents): define specialized agents with their own context

cli-reference.md +100 −68

Details

1> ## Documentation Index

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

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

4 

1# CLI reference5# CLI reference

2 6 

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

4 8 

5## CLI commands9## CLI commands

6 10 

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

12 

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

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

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

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

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

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

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

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

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

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

17| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](/en/docs/claude-code/mcp). |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 logout` | Log out from your Anthropic account | `claude auth logout` |

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

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

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

18 31 

19## CLI flags32## CLI flags

20 33 

21Customize Claude Code's behavior with these command-line flags:34Customize 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.

22 35 

23| Flag | Description | Example |36| Flag | Description | Example |

24| :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |37| :---------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |

25| `--add-dir` | Add additional working directories for Claude to access (validates each path exists as a directory) | `claude --add-dir ../apps ../lib` |38| `--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` |

26| `--agents` | Define custom [subagents](/en/docs/claude-code/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |39| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |

27| `--allowedTools` | A list of tools that should be allowed without prompting the user for permission, in addition to [settings.json files](/en/docs/claude-code/settings) | `"Bash(git log:*)" "Bash(git diff:*)" "Read"` |40| `--agents` | Define custom subagents dynamically via JSON. Uses the same field names as subagent [frontmatter](/en/sub-agents#supported-frontmatter-fields), plus a `prompt` field for the agent's instructions | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |

28| `--disallowedTools` | A list of tools that should be disallowed without prompting the user for permission, in addition to [settings.json files](/en/docs/claude-code/settings) | `"Bash(git log:*)" "Bash(git diff:*)" "Edit"` |41| `--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` |

29| `--print`, `-p` | Print response without interactive mode (see [SDK documentation](/en/docs/claude-code/sdk) for programmatic usage details) | `claude -p "query"` |42| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"` |

30| `--append-system-prompt` | Append to system prompt (only with `--print`) | `claude --append-system-prompt "Custom instruction"` |43| `--append-system-prompt` | Append custom text to the end of the default system prompt | `claude --append-system-prompt "Always use TypeScript"` |

31| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |44| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt | `claude --append-system-prompt-file ./extra-rules.txt` |

45| `--bare` | Minimal mode: skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md so scripted calls start faster. Claude has access to Bash, file read, and file edit tools. Sets [`CLAUDE_CODE_SIMPLE`](/en/env-vars). See [bare mode](/en/headless#start-faster-with-bare-mode) | `claude --bare -p "query"` |

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

61| `--init` | Run initialization hooks and start interactive mode | `claude --init` |

62| `--init-only` | Run initialization hooks and exit (no interactive session) | `claude --init-only` |

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

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

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

33| `--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"` |66| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](https://platform.claude.com/docs/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |

34| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |67| `--maintenance` | Run maintenance hooks and start interactive mode | `claude --maintenance` |

35| `--max-turns` | Limit the number of agentic turns in non-interactive mode | `claude -p --max-turns 3 "query"` |68| `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` |

36| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name | `claude --model claude-sonnet-4-5-20250929` |69| `--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"` |

37| `--permission-mode` | Begin in a specified [permission mode](iam#permission-modes) | `claude --permission-mode plan` |70| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` |

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

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

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

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

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

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

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

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

39| `--resume` | Resume a specific session by ID, or by choosing in interactive mode | `claude --resume abc123 "query"` |79| `--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` |

40| `--continue` | Load the most recent conversation in the current directory | `claude --continue` |80| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |

41| `--dangerously-skip-permissions` | Skip permission prompts (use with caution) | `claude --dangerously-skip-permissions` |81| `--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"` |

42 82| `--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"` |

43<Tip>83| `--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` |

44 The `--output-format json` flag is particularly useful for scripting and84| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` |

45 automation, allowing you to parse Claude's responses programmatically.85| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |

46</Tip>86| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` |

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

48### Agents flag format88| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` |

49 89| `--system-prompt` | Replace the entire system prompt with custom text | `claude --system-prompt "You are a Python expert"` |

50The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields:90| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt | `claude --system-prompt-file ./custom-prompt.txt` |

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

52| Field | Required | Description |92| `--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` |

53| :------------ | :------- | :-------------------------------------------------------------------------------------------------------------- |93| `--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` |

54| `description` | Yes | Natural language description of when the subagent should be invoked |94| `--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"` |

55| `prompt` | Yes | The system prompt that guides the subagent's behavior |95| `--verbose` | Enable verbose logging, shows full turn-by-turn output | `claude --verbose` |

56| `tools` | No | Array of specific tools the subagent can use (e.g., `["Read", "Edit", "Bash"]`). If omitted, inherits all tools |96| `--version`, `-v` | Output the version number | `claude -v` |

57| `model` | No | Model alias to use: `sonnet`, `opus`, or `haiku`. If omitted, uses the default subagent model |97| `--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` |

58 98 

59Example:99### System prompt flags

60 100 

61```bash theme={null}101Claude Code provides four flags for customizing the system prompt. All four work in both interactive and non-interactive modes.

62claude --agents '{102 

63 "code-reviewer": {103| Flag | Behavior | Example |

64 "description": "Expert code reviewer. Use proactively after code changes.",104| :---------------------------- | :------------------------------------------ | :------------------------------------------------------ |

65 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",105| `--system-prompt` | Replaces the entire default prompt | `claude --system-prompt "You are a Python expert"` |

66 "tools": ["Read", "Grep", "Glob", "Bash"],106| `--system-prompt-file` | Replaces with file contents | `claude --system-prompt-file ./prompts/review.txt` |

67 "model": "sonnet"107| `--append-system-prompt` | Appends to the default prompt | `claude --append-system-prompt "Always use TypeScript"` |

68 },108| `--append-system-prompt-file` | Appends file contents to the default prompt | `claude --append-system-prompt-file ./style-rules.txt` |

69 "debugger": {109 

70 "description": "Debugging specialist for errors and test failures.",110`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be combined with either replacement flag.

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

72 }112For most use cases, use an append flag. Appending preserves Claude Code's built-in capabilities while adding your requirements. Use a replacement flag only when you need complete control over the system prompt.

73}'

74```

75 

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

77 

78For detailed information about print mode (`-p`) including output formats,

79streaming, verbose logging, and programmatic usage, see the

80[SDK documentation](/en/docs/claude-code/sdk).

81 113 

82## See also114## See also

83 115 

84* [Interactive mode](/en/docs/claude-code/interactive-mode) - Shortcuts, input modes, and interactive features116* [Chrome extension](/en/chrome) - Browser automation and web testing

85* [Slash commands](/en/docs/claude-code/slash-commands) - Interactive session commands117* [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features

86* [Quickstart guide](/en/docs/claude-code/quickstart) - Getting started with Claude Code118* [Quickstart guide](/en/quickstart) - Getting started with Claude Code

87* [Common workflows](/en/docs/claude-code/common-workflows) - Advanced workflows and patterns119* [Common workflows](/en/common-workflows) - Advanced workflows and patterns

88* [Settings](/en/docs/claude-code/settings) - Configuration options120* [Settings](/en/settings) - Configuration options

89* [SDK documentation](/en/docs/claude-code/sdk) - Programmatic usage and integrations121* [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) - Programmatic usage and integrations

code-review.md +238 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Code Review

6 

7> Set up automated PR reviews that catch logic errors, security vulnerabilities, and regressions using multi-agent analysis of your full codebase

8 

9<Note>

10 Code Review is in research preview, available for [Team and Enterprise](https://claude.ai/admin-settings/claude-code) subscriptions. It is not available for organizations with [Zero Data Retention](/en/zero-data-retention) enabled.

11</Note>

12 

13Code Review analyzes your GitHub pull requests and posts findings as inline comments on the lines of code where it found issues. A fleet of specialized agents examine the code changes in the context of your full codebase, looking for logic errors, security vulnerabilities, broken edge cases, and subtle regressions.

14 

15Findings are tagged by severity and don't approve or block your PR, so existing review workflows stay intact. You can tune what Claude flags by adding a `CLAUDE.md` or `REVIEW.md` file to your repository.

16 

17To run Claude in your own CI infrastructure instead of this managed service, see [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd). For repositories on a self-hosted GitHub instance, see [GitHub Enterprise Server](/en/github-enterprise-server).

18 

19This page covers:

20 

21* [How reviews work](#how-reviews-work)

22* [Setup](#set-up-code-review)

23* [Triggering reviews manually](#manually-trigger-reviews) with `@claude review` and `@claude review once`

24* [Customizing reviews](#customize-reviews) with `CLAUDE.md` and `REVIEW.md`

25* [Pricing](#pricing)

26* [Troubleshooting](#troubleshooting) failed runs and missing comments

27 

28## How reviews work

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.

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.

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

35 

36### Severity levels

37 

38Each finding is tagged with a severity level:

39 

40| Marker | Severity | Meaning |

41| :----- | :----------- | :------------------------------------------------------------------ |

42| 🔴 | Important | A bug that should be fixed before merging |

43| 🟡 | Nit | A minor issue, worth fixing but not blocking |

44| 🟣 | Pre-existing | A bug that exists in the codebase but was not introduced by this PR |

45 

46Findings include a collapsible extended reasoning section you can expand to understand why Claude flagged the issue and how it verified the problem.

47 

48### Check run output

49 

50Beyond the inline review comments, each review populates the **Claude Code Review** check run that appears alongside your CI checks. Expand its **Details** link to see a summary of every finding in one place, sorted by severity:

51 

52| Severity | File:Line | Issue |

53| ------------ | ------------------------- | -------------------------------------------------------------- |

54| 🔴 Important | `src/auth/session.ts:142` | Token refresh races with logout, leaving stale sessions active |

55| 🟡 Nit | `src/auth/session.ts:88` | `parseExpiry` silently returns 0 on malformed input |

56 

57Each finding also appears as an annotation in the **Files changed** tab, marked directly on the relevant diff lines. Important findings render with a red marker, nits with a yellow warning, and pre-existing bugs with a gray notice. Annotations and the severity table are written to the check run independently of inline review comments, so they remain available even if GitHub rejects an inline comment on a line that moved.

58 

59The check run always completes with a neutral conclusion so it never blocks merging through branch protection rules. If you want to gate merges on Code Review findings, read the severity breakdown from the check run output in your own CI. The last line of the Details text is a machine-readable comment your workflow can parse with `gh` and jq:

60 

61```bash theme={null}

62gh api repos/OWNER/REPO/check-runs/CHECK_RUN_ID \

63 --jq '.output.text | split("bughunter-severity: ")[1] | split(" -->")[0] | fromjson'

64```

65 

66This returns a JSON object with counts per severity, for example `{"normal": 2, "nit": 1, "pre_existing": 0}`. The `normal` key holds the count of Important findings; a non-zero value means Claude found at least one bug worth fixing before merge.

67 

68### What Code Review checks

69 

70By default, Code Review focuses on correctness: bugs that would break production, not formatting preferences or missing test coverage. You can expand what it checks by [adding guidance files](#customize-reviews) to your repository.

71 

72## Set up Code Review

73 

74An admin enables Code Review once for the organization and selects which repositories to include.

75 

76<Steps>

77 <Step title="Open Claude Code admin settings">

78 Go to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and find the Code Review section. You need admin access to your Claude organization and permission to install GitHub Apps in your GitHub organization.

79 </Step>

80 

81 <Step title="Start setup">

82 Click **Setup**. This begins the GitHub App installation flow.

83 </Step>

84 

85 <Step title="Install the Claude GitHub App">

86 Follow the prompts to install the Claude GitHub App to your GitHub organization. The app requests these repository permissions:

87 

88 * **Contents**: read and write

89 * **Issues**: read and write

90 * **Pull requests**: read and write

91 

92 Code Review uses read access to contents and write access to pull requests. The broader permission set also supports [GitHub Actions](/en/github-actions) if you enable that later.

93 </Step>

94 

95 <Step title="Select repositories">

96 Choose which repositories to enable for Code Review. If you don't see a repository, make sure you gave the Claude GitHub App access to it during installation. You can add more repositories later.

97 </Step>

98 

99 <Step title="Set review triggers per repo">

100 After setup completes, the Code Review section shows your repositories in a table. For each repository, use the **Review Behavior** dropdown to choose when reviews run:

101 

102 * **Once after PR creation**: review runs once when a PR is opened or marked ready for review

103 * **After every push**: review runs on every push to the PR branch, catching new issues as the PR evolves and auto-resolving threads when you fix flagged issues

104 * **Manual**: reviews start only when someone [comments `@claude review` or `@claude review once` on a PR](#manually-trigger-reviews); `@claude review` also subscribes the PR to reviews on subsequent pushes

105 

106 Reviewing on every push runs the most reviews and costs the most. Manual mode is useful for high-traffic repos where you want to opt specific PRs into review, or to only start reviewing your PRs once they're ready.

107 </Step>

108</Steps>

109 

110The repositories table also shows the average cost per review for each repo based on recent activity. Use the row actions menu to turn Code Review on or off per repository, or to remove a repository entirely.

111 

112To verify setup, open a test PR. If you chose an automatic trigger, a check run named **Claude Code Review** appears within a few minutes. If you chose Manual, comment `@claude review` on the PR to start the first review. If no check run appears, confirm the repository is listed in your admin settings and the Claude GitHub App has access to it.

113 

114## Manually trigger reviews

115 

116Two comment commands start a review on demand. Both work regardless of the repository's configured trigger, so you can use them to opt specific PRs into review in Manual mode or to get an immediate re-review in other modes.

117 

118| Command | What it does |

119| :-------------------- | :---------------------------------------------------------------------------- |

120| `@claude review` | Starts a review and subscribes the PR to push-triggered reviews going forward |

121| `@claude review once` | Starts a single review without subscribing the PR to future pushes |

122 

123Use `@claude review once` when you want feedback on the current state of a PR but don't want every subsequent push to incur a review. This is useful for long-running PRs with frequent pushes, or when you want a one-off second opinion without changing the PR's review behavior.

124 

125For either command to trigger a review:

126 

127* Post it as a top-level PR comment, not an inline comment on a diff line

128* Put the command at the start of the comment, with `once` on the same line if you're using the one-shot form

129* You must have owner, member, or collaborator access to the repository

130* The PR must be open

131 

132Unlike automatic triggers, manual triggers run on draft PRs, since an explicit request signals you want the review now regardless of draft status.

133 

134If a review is already running on that PR, the request is queued until the in-progress review completes. You can monitor progress via the check run on the PR.

135 

136## Customize reviews

137 

138Code Review reads two files from your repository to guide what it flags. Both are additive on top of the default correctness checks:

139 

140* **`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.

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

142 

143### CLAUDE.md

144 

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

146 

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

148 

149For review-specific guidance that you don't want applied to general Claude Code sessions, use [`REVIEW.md`](#review-md) instead.

150 

151### REVIEW\.md

152 

153Add a `REVIEW.md` file to your repository root for review-specific rules. Use it to encode:

154 

155* Company or team style guidelines: "prefer early returns over nested conditionals"

156* Language- or framework-specific conventions not covered by linters

157* Things Claude should always flag: "any new API route must have an integration test"

158* Things Claude should skip: "don't comment on formatting in generated code under `/gen/`"

159 

160Example `REVIEW.md`:

161 

162```markdown theme={null}

163# Code Review Guidelines

164 

165## Always check

166- New API endpoints have corresponding integration tests

167- Database migrations are backward-compatible

168- Error messages don't leak internal details to users

169 

170## Style

171- Prefer `match` statements over chained `isinstance` checks

172- Use structured logging, not f-string interpolation in log calls

173 

174## Skip

175- Generated files under `src/gen/`

176- Formatting-only changes in `*.lock` files

177```

178 

179Claude auto-discovers `REVIEW.md` at the repository root. No configuration needed.

180 

181## View usage

182 

183Go to [claude.ai/analytics/code-review](https://claude.ai/analytics/code-review) to see Code Review activity across your organization. The dashboard shows:

184 

185| Section | What it shows |

186| :------------------- | :--------------------------------------------------------------------------------------- |

187| PRs reviewed | Daily count of pull requests reviewed over the selected time range |

188| Cost weekly | Weekly spend on Code Review |

189| Feedback | Count of review comments that were auto-resolved because a developer addressed the issue |

190| Repository breakdown | Per-repo counts of PRs reviewed and comments resolved |

191 

192The repositories table in admin settings also shows average cost per review for each repo.

193 

194## Pricing

195 

196Code Review is billed based on token usage. Each review averages \$15-25 in cost, scaling with PR size, codebase complexity, and how many issues require verification. Code Review usage is billed separately through [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) and does not count against your plan's included usage.

197 

198The review trigger you choose affects total cost:

199 

200* **Once after PR creation**: runs once per PR

201* **After every push**: runs on each push, multiplying cost by the number of pushes

202* **Manual**: no reviews until someone comments `@claude review` on a PR

203 

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

205 

206Costs 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.

207 

208Monitor spend via the weekly cost chart in [analytics](#view-usage) or the per-repo average cost column in admin settings.

209 

210## Troubleshooting

211 

212Review runs are best-effort. A failed run never blocks your PR, but it also doesn't retry on its own. This section covers how to recover from a failed run and where to look when the check run reports issues you can't find.

213 

214### Retrigger a failed or timed-out review

215 

216When the review infrastructure hits an internal error or exceeds its time limit, the check run completes with a title of **Code review encountered an error** or **Code review timed out**. The conclusion is still neutral, so nothing blocks your merge, but no findings are posted.

217 

218To run the review again, comment `@claude review once` on the PR. This starts a fresh review without subscribing the PR to future pushes. If the PR is already subscribed to push-triggered reviews, pushing a new commit also starts a new review.

219 

220The **Re-run** button in GitHub's Checks tab does not retrigger Code Review. Use the comment command or a new push instead.

221 

222### Find issues that aren't showing as inline comments

223 

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

225 

226* **Check run Details**: click **Details** next to the Claude Code Review check in the Checks tab. The severity table lists every finding with its file, line, and summary regardless of whether the inline comment was accepted.

227* **Files changed annotations**: open the **Files changed** tab on the PR. Findings render as annotations attached directly to the diff lines, separate from review comments.

228* **Review body**: if you pushed to the PR while a review was running, some findings may reference lines that no longer exist in the current diff. Those appear under an **Additional findings** heading in the review body text rather than as inline comments.

229 

230## Related resources

231 

232Code Review is designed to work alongside the rest of Claude Code. If you want to run reviews locally before opening a PR, need a self-hosted setup, or want to go deeper on how `CLAUDE.md` shapes Claude's behavior across tools, these pages are good next stops:

233 

234* [Plugins](/en/discover-plugins): browse the plugin marketplace, including a `code-review` plugin for running on-demand reviews locally before pushing

235* [GitHub Actions](/en/github-actions): run Claude in your own GitHub Actions workflows for custom automation beyond code review

236* [GitLab CI/CD](/en/gitlab-ci-cd): self-hosted Claude integration for GitLab pipelines

237* [Memory](/en/memory): how `CLAUDE.md` files work across Claude Code

238* [Analytics](/en/analytics): track Claude Code usage beyond code review

commands.md +92 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Built-in commands

6 

7> Complete reference for built-in commands available in Claude Code.

8 

9Type `/` in Claude Code to see all available commands, or type `/` followed by any letters to filter. Not all commands are visible to every user. Some depend on your platform, plan, or environment. For example, `/desktop` only appears on macOS and Windows, `/upgrade` and `/privacy-settings` are only available on Pro and Max plans, and `/terminal-setup` is hidden when your terminal natively supports its keybindings.

10 

11Claude Code also includes [bundled skills](/en/skills#bundled-skills) like `/simplify`, `/batch`, `/debug`, and `/loop` that appear alongside built-in commands when you type `/`. To create your own commands, see [skills](/en/skills).

12 

13In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

14 

15| Command | Purpose |

16| :--------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

17| `/add-dir <path>` | Add a 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 |

18| `/agents` | Manage [agent](/en/sub-agents) configurations |

19| `/btw <question>` | Ask a quick [side question](/en/interactive-mode#side-questions-with-btw) without adding to the conversation |

20| `/chrome` | Configure [Claude in Chrome](/en/chrome) settings |

21| `/clear` | Clear conversation history and free up context. Aliases: `/reset`, `/new` |

22| `/color [color\|default]` | Set the prompt bar color for the current session. Available colors: `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, `cyan`. Use `default` to reset |

23| `/compact [instructions]` | Compact conversation with optional focus instructions |

24| `/config` | Open the [Settings](/en/settings) interface to adjust theme, model, [output style](/en/output-styles), and other preferences. Alias: `/settings` |

25| `/context` | Visualize current context usage as a colored grid. Shows optimization suggestions for context-heavy tools, memory bloat, and capacity warnings |

26| `/copy [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 |

27| `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details |

28| `/desktop` | Continue the current session in the Claude Code Desktop app. macOS and Windows only. Alias: `/app` |

29| `/diff` | Open an interactive diff viewer showing uncommitted changes and per-turn diffs. Use left/right arrows to switch between the current git diff and individual Claude turns, and up/down to browse files |

30| `/doctor` | Diagnose and verify your Claude Code installation and settings |

31| `/effort [low\|medium\|high\|max\|auto]` | Set the model [effort level](/en/model-config#adjust-effort-level). `low`, `medium`, and `high` persist across sessions. `max` applies to the current session only and requires Opus 4.6. `auto` resets to the model default. Without an argument, shows the current level. Takes effect immediately without waiting for the current response to finish |

32| `/exit` | Exit the CLI. Alias: `/quit` |

33| `/export [filename]` | Export the current conversation as plain text. With a filename, writes directly to that file. Without, opens a dialog to copy to clipboard or save to a file |

34| `/extra-usage` | Configure extra usage to keep working when rate limits are hit |

35| `/fast [on\|off]` | Toggle [fast mode](/en/fast-mode) on or off |

36| `/feedback [report]` | Submit feedback about Claude Code. Alias: `/bug` |

37| `/branch [name]` | Create a branch of the current conversation at this point. Alias: `/fork` |

38| `/help` | Show help and available commands |

39| `/hooks` | View [hook](/en/hooks) configurations for tool events |

40| `/ide` | Manage IDE integrations and show status |

41| `/init` | Initialize project with a `CLAUDE.md` guide. Set `CLAUDE_CODE_NEW_INIT=1` for an interactive flow that also walks through skills, hooks, and personal memory files |

42| `/insights` | Generate a report analyzing your Claude Code sessions, including project areas, interaction patterns, and friction points |

43| `/install-github-app` | Set up the [Claude GitHub Actions](/en/github-actions) app for a repository. Walks you through selecting a repo and configuring the integration |

44| `/install-slack-app` | Install the Claude Slack app. Opens a browser to complete the OAuth flow |

45| `/keybindings` | Open or create your keybindings configuration file |

46| `/login` | Sign in to your Anthropic account |

47| `/logout` | Sign out from your Anthropic account |

48| `/mcp` | Manage MCP server connections and OAuth authentication |

49| `/memory` | Edit `CLAUDE.md` memory files, enable or disable [auto-memory](/en/memory#auto-memory), and view auto-memory entries |

50| `/mobile` | Show QR code to download the Claude mobile app. Aliases: `/ios`, `/android` |

51| `/model [model]` | Select or change the AI model. For models that support it, use left/right arrows to [adjust effort level](/en/model-config#adjust-effort-level). The change takes effect immediately without waiting for the current response to finish |

52| `/passes` | Share a free week of Claude Code with friends. Only visible if your account is eligible |

53| `/permissions` | 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` |

54| `/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` |

55| `/plugin` | Manage Claude Code [plugins](/en/plugins) |

56| `/powerup` | Discover Claude Code features through quick interactive lessons with animated demos |

57| `/pr-comments [PR]` | Fetch and display comments from a GitHub pull request. Automatically detects the PR for the current branch, or pass a PR URL or number. Requires the `gh` CLI |

58| `/privacy-settings` | View and update your privacy settings. Only available for Pro and Max plan subscribers |

59| `/release-notes` | View the full changelog, with the most recent version closest to your prompt |

60| `/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 |

61| `/remote-control` | Make this session available for [remote control](/en/remote-control) from claude.ai. Alias: `/rc` |

62| `/remote-env` | Configure the default remote environment for [web sessions started with `--remote`](/en/claude-code-on-the-web#environment-configuration) |

63| `/rename [name]` | Rename the current session and show the name on the prompt bar. Without a name, auto-generates one from conversation history |

64| `/resume [session]` | Resume a conversation by ID or name, or open the session picker. Alias: `/continue` |

65| `/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` |

66| `/rewind` | Rewind the conversation and/or code to a previous point, or summarize from a selected message. See [checkpointing](/en/checkpointing). Alias: `/checkpoint` |

67| `/sandbox` | Toggle [sandbox mode](/en/sandboxing). Available on supported platforms only |

68| `/schedule [description]` | Create, update, list, or run [Cloud scheduled tasks](/en/web-scheduled-tasks). Claude walks you through the setup conversationally |

69| `/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 |

70| `/skills` | List available [skills](/en/skills) |

71| `/stats` | Visualize daily usage, session history, streaks, and model preferences |

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

73| `/statusline` | Configure Claude Code's [status line](/en/statusline). Describe what you want, or run without arguments to auto-configure from your shell prompt |

74| `/stickers` | Order Claude Code stickers |

75| `/tasks` | List and manage background tasks. Also available as `/bashes` |

76| `/terminal-setup` | Configure terminal keybindings for Shift+Enter and other shortcuts. Only visible in terminals that need it, like VS Code, Alacritty, or Warp |

77| `/theme` | Change the color theme. Includes light and dark variants, colorblind-accessible (daltonized) themes, and ANSI themes that use your terminal's color palette |

78| `/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 |

79| `/upgrade` | Open the upgrade page to switch to a higher plan tier |

80| `/usage` | Show plan usage limits and rate limit status |

81| `/vim` | Toggle between Vim and Normal editing modes |

82| `/voice` | Toggle push-to-talk [voice dictation](/en/voice-dictation). Requires a Claude.ai account |

83 

84## MCP prompts

85 

86MCP servers can expose prompts that appear as commands. These use the format `/mcp__<server>__<prompt>` and are dynamically discovered from connected servers. See [MCP prompts](/en/mcp#use-mcp-prompts-as-commands) for details.

87 

88## See also

89 

90* [Skills](/en/skills): create your own commands

91* [Interactive mode](/en/interactive-mode): keyboard shortcuts, Vim mode, and command history

92* [CLI reference](/en/cli-reference): launch-time flags

common-workflows.md +422 −363

Details

1> ## Documentation Index

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

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

4 

1# Common workflows5# Common workflows

2 6 

3> Learn about common workflows with Claude Code.7> Step-by-step guides for exploring codebases, fixing bugs, refactoring, testing, and other everyday tasks with Claude Code.

4 8 

5Each task in this document includes clear instructions, example commands, and best practices to help you get the most from Claude Code.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).

6 10 

7## Understand new codebases11## Understand new codebases

8 12 


24 </Step>28 </Step>

25 29 

26 <Step title="Ask for a high-level overview">30 <Step title="Ask for a high-level overview">

27 ```31 ```text theme={null}

28 > give me an overview of this codebase 32 give me an overview of this codebase

29 ```33 ```

30 </Step>34 </Step>

31 35 

32 <Step title="Dive deeper into specific components">36 <Step title="Dive deeper into specific components">

33 ```37 ```text theme={null}

34 > explain the main architecture patterns used here 38 explain the main architecture patterns used here

35 ```39 ```

36 40 

37 ```41 ```text theme={null}

38 > what are the key data models?42 what are the key data models?

39 ```43 ```

40 44 

41 ```45 ```text theme={null}

42 > how is authentication handled?46 how is authentication handled?

43 ```47 ```

44 </Step>48 </Step>

45</Steps>49</Steps>


58 62 

59<Steps>63<Steps>

60 <Step title="Ask Claude to find relevant files">64 <Step title="Ask Claude to find relevant files">

61 ```65 ```text theme={null}

62 > find the files that handle user authentication 66 find the files that handle user authentication

63 ```67 ```

64 </Step>68 </Step>

65 69 

66 <Step title="Get context on how components interact">70 <Step title="Get context on how components interact">

67 ```71 ```text theme={null}

68 > how do these authentication files work together? 72 how do these authentication files work together?

69 ```73 ```

70 </Step>74 </Step>

71 75 

72 <Step title="Understand the execution flow">76 <Step title="Understand the execution flow">

73 ```77 ```text theme={null}

74 > trace the login process from front-end to database 78 trace the login process from front-end to database

75 ```79 ```

76 </Step>80 </Step>

77</Steps>81</Steps>


81 85 

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

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

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

84</Tip>89</Tip>

85 90 

86***91***


91 96 

92<Steps>97<Steps>

93 <Step title="Share the error with Claude">98 <Step title="Share the error with Claude">

94 ```99 ```text theme={null}

95 > I'm seeing an error when I run npm test 100 I'm seeing an error when I run npm test

96 ```101 ```

97 </Step>102 </Step>

98 103 

99 <Step title="Ask for fix recommendations">104 <Step title="Ask for fix recommendations">

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

101 > suggest a few ways to fix the @ts-ignore in user.ts 106 suggest a few ways to fix the @ts-ignore in user.ts

102 ```107 ```

103 </Step>108 </Step>

104 109 

105 <Step title="Apply the fix">110 <Step title="Apply the fix">

106 ```111 ```text theme={null}

107 > update user.ts to add the null check you suggested 112 update user.ts to add the null check you suggested

108 ```113 ```

109 </Step>114 </Step>

110</Steps>115</Steps>


125 130 

126<Steps>131<Steps>

127 <Step title="Identify legacy code for refactoring">132 <Step title="Identify legacy code for refactoring">

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

129 > find deprecated API usage in our codebase 134 find deprecated API usage in our codebase

130 ```135 ```

131 </Step>136 </Step>

132 137 

133 <Step title="Get refactoring recommendations">138 <Step title="Get refactoring recommendations">

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

135 > suggest how to refactor utils.js to use modern JavaScript features 140 suggest how to refactor utils.js to use modern JavaScript features

136 ```141 ```

137 </Step>142 </Step>

138 143 

139 <Step title="Apply the changes safely">144 <Step title="Apply the changes safely">

140 ```145 ```text theme={null}

141 > refactor utils.js to use ES2024 features while maintaining the same behavior 146 refactor utils.js to use ES2024 features while maintaining the same behavior

142 ```147 ```

143 </Step>148 </Step>

144 149 

145 <Step title="Verify the refactoring">150 <Step title="Verify the refactoring">

146 ```151 ```text theme={null}

147 > run tests for the refactored code 152 run tests for the refactored code

148 ```153 ```

149 </Step>154 </Step>

150</Steps>155</Steps>


165 170 

166<Steps>171<Steps>

167 <Step title="View available subagents">172 <Step title="View available subagents">

168 ```173 ```text theme={null}

169 > /agents174 /agents

170 ```175 ```

171 176 

172 This shows all available subagents and lets you create new ones.177 This shows all available subagents and lets you create new ones.

173 </Step>178 </Step>

174 179 

175 <Step title="Use subagents automatically">180 <Step title="Use subagents automatically">

176 Claude Code will automatically delegate appropriate tasks to specialized subagents:181 Claude Code automatically delegates appropriate tasks to specialized subagents:

177 182 

178 ```183 ```text theme={null}

179 > review my recent code changes for security issues184 review my recent code changes for security issues

180 ```185 ```

181 186 

182 ```187 ```text theme={null}

183 > run all tests and fix any failures188 run all tests and fix any failures

184 ```189 ```

185 </Step>190 </Step>

186 191 

187 <Step title="Explicitly request specific subagents">192 <Step title="Explicitly request specific subagents">

188 ```193 ```text theme={null}

189 > use the code-reviewer subagent to check the auth module194 use the code-reviewer subagent to check the auth module

190 ```195 ```

191 196 

192 ```197 ```text theme={null}

193 > have the debugger subagent investigate why users can't log in198 have the debugger subagent investigate why users can't log in

194 ```199 ```

195 </Step>200 </Step>

196 201 

197 <Step title="Create custom subagents for your workflow">202 <Step title="Create custom subagents for your workflow">

198 ```203 ```text theme={null}

199 > /agents204 /agents

200 ```205 ```

201 206 

202 Then select "Create New subagent" and follow the prompts to define:207 Then select "Create New subagent" and follow the prompts to define:

203 208 

204 * Subagent type (e.g., `api-designer`, `performance-optimizer`)209 * A unique identifier that describes the subagent's purpose (for example, `code-reviewer`, `api-designer`).

205 * When to use it210 * When Claude should use this agent

206 * Which tools it can access211 * Which tools it can access

207 * Its specialized system prompt212 * A system prompt describing the agent's role and behavior

208 </Step>213 </Step>

209</Steps>214</Steps>

210 215 


214 * Create project-specific subagents in `.claude/agents/` for team sharing219 * Create project-specific subagents in `.claude/agents/` for team sharing

215 * Use descriptive `description` fields to enable automatic delegation220 * Use descriptive `description` fields to enable automatic delegation

216 * Limit tool access to what each subagent actually needs221 * Limit tool access to what each subagent actually needs

217 * Check the [subagents documentation](/en/docs/claude-code/sub-agents) for detailed examples222 * Check the [subagents documentation](/en/sub-agents) for detailed examples

218</Tip>223</Tip>

219 224 

220***225***

221 226 

222## Use Plan Mode for safe code analysis227## Use Plan Mode for safe code analysis

223 228 

224Plan 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.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.

225 230 

226### When to use Plan Mode231### When to use Plan Mode

227 232 


235 240 

236You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes.241You can switch into Plan Mode during a session using **Shift+Tab** to cycle through permission modes.

237 242 

238If you are in Normal Mode, **Shift+Tab** will first switch 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`.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`.

239 244 

240**Start a new session in Plan Mode**245**Start a new session in Plan Mode**

241 246 


247 252 

248**Run "headless" queries in Plan Mode**253**Run "headless" queries in Plan Mode**

249 254 

250You can also run a query in Plan Mode directly with `-p` (i.e., in ["headless mode"](/en/docs/claude-code/sdk/sdk-headless)):255You can also run a query in Plan Mode directly with `-p` (that is, in ["headless mode"](/en/headless)):

251 256 

252```bash theme={null}257```bash theme={null}

253claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"258claude --permission-mode plan -p "Analyze the authentication system and suggest improvements"


259claude --permission-mode plan264claude --permission-mode plan

260```265```

261 266 

262```267```text theme={null}

263> I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.268I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.

264```269```

265 270 

266Claude will analyze the current implementation and create a comprehensive plan. Refine with follow-ups:271Claude analyzes the current implementation and create a comprehensive plan. Refine with follow-ups:

267 272 

273```text theme={null}

274What about backward compatibility?

268```275```

269> What about backward compatibility?276 

270> How should we handle database migration?277```text theme={null}

278How should we handle database migration?

271```279```

272 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 

273### Configure Plan Mode as default285### Configure Plan Mode as default

274 286 

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


281}293}

282```294```

283 295 

284See [settings documentation](/en/docs/claude-code/settings#available-settings) for more configuration options.296See [settings documentation](/en/settings#available-settings) for more configuration options.

285 297 

286***298***

287 299 


291 303 

292<Steps>304<Steps>

293 <Step title="Identify untested code">305 <Step title="Identify untested code">

294 ```306 ```text theme={null}

295 > find functions in NotificationsService.swift that are not covered by tests 307 find functions in NotificationsService.swift that are not covered by tests

296 ```308 ```

297 </Step>309 </Step>

298 310 

299 <Step title="Generate test scaffolding">311 <Step title="Generate test scaffolding">

300 ```312 ```text theme={null}

301 > add tests for the notification service 313 add tests for the notification service

302 ```314 ```

303 </Step>315 </Step>

304 316 

305 <Step title="Add meaningful test cases">317 <Step title="Add meaningful test cases">

306 ```318 ```text theme={null}

307 > add test cases for edge conditions in the notification service 319 add test cases for edge conditions in the notification service

308 ```320 ```

309 </Step>321 </Step>

310 322 

311 <Step title="Run and verify tests">323 <Step title="Run and verify tests">

312 ```324 ```text theme={null}

313 > run the new tests and fix any failures 325 run the new tests and fix any failures

314 ```326 ```

315 </Step>327 </Step>

316</Steps>328</Steps>

317 329 

318<Tip>330Claude can generate tests that follow your project's existing patterns and conventions. When asking for tests, be specific about what behavior you want to verify. Claude examines your existing test files to match the style, frameworks, and assertion patterns already in use.

319 Tips:

320 331 

321 * Ask for tests that cover edge cases and error conditions332For comprehensive coverage, ask Claude to identify edge cases you might have missed. Claude can analyze your code paths and suggest tests for error conditions, boundary values, and unexpected inputs that are easy to overlook.

322 * Request both unit and integration tests when appropriate

323 * Have Claude explain the testing strategy

324</Tip>

325 333 

326***334***

327 335 

328## Create pull requests336## Create pull requests

329 337 

330Suppose you need to create a well-documented pull request for your changes.338You can create pull requests by asking Claude directly ("create a pr for my changes"), or guide Claude through it step-by-step:

331 339 

332<Steps>340<Steps>

333 <Step title="Summarize your changes">341 <Step title="Summarize your changes">

334 ```342 ```text theme={null}

335 > summarize the changes I've made to the authentication module 343 summarize the changes I've made to the authentication module

336 ```344 ```

337 </Step>345 </Step>

338 346 

339 <Step title="Generate a PR with Claude">347 <Step title="Generate a pull request">

340 ```348 ```text theme={null}

341 > create a pr 349 create a pr

342 ```350 ```

343 </Step>351 </Step>

344 352 

345 <Step title="Review and refine">353 <Step title="Review and refine">

346 ```354 ```text theme={null}

347 > enhance the PR description with more context about the security improvements 355 enhance the PR description with more context about the security improvements

348 ```

349 </Step>

350 

351 <Step title="Add testing details">

352 ```

353 > add information about how these changes were tested

354 ```356 ```

355 </Step>357 </Step>

356</Steps>358</Steps>

357 359 

358<Tip>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>`.

359 Tips:

360 361 

361 * Ask Claude directly to make a PR for you362<Tip>

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

363 * Ask Claude to highlight potential risks or considerations

364</Tip>364</Tip>

365 365 

366## Handle documentation366## Handle documentation


369 369 

370<Steps>370<Steps>

371 <Step title="Identify undocumented code">371 <Step title="Identify undocumented code">

372 ```372 ```text theme={null}

373 > find functions without proper JSDoc comments in the auth module 373 find functions without proper JSDoc comments in the auth module

374 ```374 ```

375 </Step>375 </Step>

376 376 

377 <Step title="Generate documentation">377 <Step title="Generate documentation">

378 ```378 ```text theme={null}

379 > add JSDoc comments to the undocumented functions in auth.js 379 add JSDoc comments to the undocumented functions in auth.js

380 ```380 ```

381 </Step>381 </Step>

382 382 

383 <Step title="Review and enhance">383 <Step title="Review and enhance">

384 ```384 ```text theme={null}

385 > improve the generated documentation with more context and examples 385 improve the generated documentation with more context and examples

386 ```386 ```

387 </Step>387 </Step>

388 388 

389 <Step title="Verify documentation">389 <Step title="Verify documentation">

390 ```390 ```text theme={null}

391 > check if the documentation follows our project standards 391 check if the documentation follows our project standards

392 ```392 ```

393 </Step>393 </Step>

394</Steps>394</Steps>


417 </Step>417 </Step>

418 418 

419 <Step title="Ask Claude to analyze the image">419 <Step title="Ask Claude to analyze the image">

420 ```420 ```text theme={null}

421 > What does this image show?421 What does this image show?

422 ```422 ```

423 423 

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

425 > Describe the UI elements in this screenshot425 Describe the UI elements in this screenshot

426 ```426 ```

427 427 

428 ```428 ```text theme={null}

429 > Are there any problematic elements in this diagram?429 Are there any problematic elements in this diagram?

430 ```430 ```

431 </Step>431 </Step>

432 432 

433 <Step title="Use images for context">433 <Step title="Use images for context">

434 ```434 ```text theme={null}

435 > Here's a screenshot of the error. What's causing it?435 Here's a screenshot of the error. What's causing it?

436 ```436 ```

437 437 

438 ```438 ```text theme={null}

439 > This is our current database schema. How should we modify it for the new feature?439 This is our current database schema. How should we modify it for the new feature?

440 ```440 ```

441 </Step>441 </Step>

442 442 

443 <Step title="Get code suggestions from visual content">443 <Step title="Get code suggestions from visual content">

444 ```444 ```text theme={null}

445 > Generate CSS to match this design mockup445 Generate CSS to match this design mockup

446 ```446 ```

447 447 

448 ```448 ```text theme={null}

449 > What HTML structure would recreate this component?449 What HTML structure would recreate this component?

450 ```450 ```

451 </Step>451 </Step>

452</Steps>452</Steps>


458 * Include screenshots of errors, UI designs, or diagrams for better context458 * Include screenshots of errors, UI designs, or diagrams for better context

459 * You can work with multiple images in a conversation459 * You can work with multiple images in a conversation

460 * Image analysis works with diagrams, screenshots, mockups, and more460 * Image analysis works with diagrams, screenshots, mockups, and more

461 * When Claude references images (for example, `[Image #1]`), `Cmd+Click` (Mac) or `Ctrl+Click` (Windows/Linux) the link to open the image in your default viewer

461</Tip>462</Tip>

462 463 

463***464***


468 469 

469<Steps>470<Steps>

470 <Step title="Reference a single file">471 <Step title="Reference a single file">

471 ```472 ```text theme={null}

472 > Explain the logic in @src/utils/auth.js473 Explain the logic in @src/utils/auth.js

473 ```474 ```

474 475 

475 This includes the full content of the file in the conversation.476 This includes the full content of the file in the conversation.

476 </Step>477 </Step>

477 478 

478 <Step title="Reference a directory">479 <Step title="Reference a directory">

479 ```480 ```text theme={null}

480 > What's the structure of @src/components?481 What's the structure of @src/components?

481 ```482 ```

482 483 

483 This provides a directory listing with file information.484 This provides a directory listing with file information.

484 </Step>485 </Step>

485 486 

486 <Step title="Reference MCP resources">487 <Step title="Reference MCP resources">

487 ```488 ```text theme={null}

488 > Show me the data from @github:repos/owner/repo/issues489 Show me the data from @github:repos/owner/repo/issues

489 ```490 ```

490 491 

491 This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/docs/claude-code/mcp#use-mcp-resources) for details.492 This fetches data from connected MCP servers using the format @server:resource. See [MCP resources](/en/mcp#use-mcp-resources) for details.

492 </Step>493 </Step>

493</Steps>494</Steps>

494 495 


496 Tips:497 Tips:

497 498 

498 * File paths can be relative or absolute499 * File paths can be relative or absolute

499 * @ file references add CLAUDE.md in the file's directory and parent directories to context500 * @ file references add `CLAUDE.md` in the file's directory and parent directories to context

500 * Directory references show file listings, not contents501 * Directory references show file listings, not contents

501 * You can reference multiple files in a single message (e.g., "@file1.js and @file2.js")502 * You can reference multiple files in a single message (for example, "@file1.js and @file2.js")

502</Tip>503</Tip>

503 504 

504***505***

505 506 

506## Use extended thinking507## Use extended thinking (thinking mode)

507 508 

508Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning.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`.

509 510 

510<Note>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.

511 [Extended thinking](/en/docs/build-with-claude/extended-thinking) is disabled by default in Claude Code. You can enable it on-demand by using `Tab` to toggle Thinking on, or by using prompts like "think" or "think hard". You can also enable it permanently by setting the [`MAX_THINKING_TOKENS` environment variable](/en/docs/claude-code/settings#environment-variables) in your settings.

512</Note>

513 512 

514<Steps>513Extended thinking is particularly valuable for complex architectural decisions, challenging bugs, multi-step implementation planning, and evaluating tradeoffs between different approaches.

515 <Step title="Provide context and ask Claude to think">

516 ```

517 > I need to implement a new authentication system using OAuth2 for our API. Think deeply about the best approach for implementing this in our codebase.

518 ```

519 514 

520 Claude will gather relevant information from your codebase and515<Note>

521 use extended thinking, which will be visible in the interface.516 Phrases like "think", "think hard", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.

522 </Step>517</Note>

523 518 

524 <Step title="Refine the thinking with follow-up prompts">519### Configure thinking mode

525 ```

526 > think about potential security vulnerabilities in this approach

527 ```

528 520 

529 ```521Thinking is enabled by default, but you can adjust or disable it.

530 > think hard about edge cases we should handle

531 ```

532 </Step>

533</Steps>

534 522 

535<Tip>523| Scope | How to configure | Details |

536 Tips to get the most value out of extended thinking: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` |

537 530 

538 [Extended thinking](/en/docs/build-with-claude/extended-thinking) is most valuable for complex tasks such as:531To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.

539 532 

540 * Planning complex architectural changes533### How extended thinking works

541 * Debugging intricate issues

542 * Creating implementation plans for new features

543 * Understanding complex codebases

544 * Evaluating tradeoffs between different approaches

545 534 

546 Use `Tab` to toggle Thinking on and off during a session.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.

547 536 

548 The way you prompt for thinking results in varying levels of thinking depth: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.

549 538 

550 * "think" triggers basic extended thinking539**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.

551 * intensifying phrases such as "keep hard", "think more", "think a lot", or "think longer" triggers deeper thinking

552 540 

553 For more extended thinking prompting tips, see [Extended thinking tips](/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips).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).

554</Tip>

555 542 

556<Note>543<Warning>

557 Claude will display its thinking process as italic gray text above the544 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.

558 response.545</Warning>

559</Note>

560 546 

561***547***

562 548 

563## Resume previous conversations549## Resume previous conversations

564 550 

565Suppose you've been working on a task with Claude Code and need to continue where you left off in a later session.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

566 556 

567Claude Code provides two options for resuming previous conversations:557From inside an active session, use `/resume` to switch to a different conversation.

568 558 

569* `--continue` to automatically continue the most recent conversation559Sessions are stored per project directory. The `/resume` picker shows interactive sessions from the same git repository, including worktrees. 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 directly to `claude --resume <session-id>`.

570* `--resume` to display a conversation picker560 

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.

571 564 

572<Steps>565<Steps>

573 <Step title="Continue the most recent conversation">566 <Step title="Name the session">

567 Name a session at startup with `-n`:

568 

574 ```bash theme={null}569 ```bash theme={null}

575 claude --continue570 claude -n auth-refactor

576 ```571 ```

577 572 

578 This immediately resumes your most recent conversation without any prompts.573 Or use `/rename` during a session, which also shows the name on the prompt bar:

579 </Step>

580 574 

581 <Step title="Continue in non-interactive mode">575 ```text theme={null}

582 ```bash theme={null}576 /rename auth-refactor

583 claude --continue --print "Continue with my task"

584 ```577 ```

585 578 

586 Use `--print` with `--continue` to resume the most recent conversation in non-interactive mode, perfect for scripts or automation.579 You can also rename any session from the picker: run `/resume`, navigate to a session, and press `R`.

587 </Step>580 </Step>

588 581 

589 <Step title="Show conversation picker">582 <Step title="Resume by name later">

583 From the command line:

584 

590 ```bash theme={null}585 ```bash theme={null}

591 claude --resume586 claude --resume auth-refactor

592 ```587 ```

593 588 

594 This displays an interactive conversation selector with a clean list view showing:589 Or from inside an active session:

595 590 

596 * Session summary (or initial prompt)591 ```text theme={null}

597 * Metadata: time elapsed, message count, and git branch592 /resume auth-refactor

598 593 ```

599 Use arrow keys to navigate and press Enter to select a conversation. Press Esc to exit.

600 </Step>594 </Step>

601</Steps>595</Steps>

602 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 

603<Tip>626<Tip>

604 Tips:627 Tips:

605 628 

606 * Conversation history is stored locally on your machine629 * **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

607 * Use `--continue` for quick access to your most recent conversation630 * Use `--continue` for quick access to your most recent conversation in the current directory

608 * Use `--resume` when you need to select a specific past conversation631 * Use `--resume session-name` when you know which session you need

609 * When resuming, you'll see the entire conversation history before continuing632 * 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

610 * The resumed conversation starts with the same model and configuration as the original635 * The resumed conversation starts with the same model and configuration as the original

611 636 

612 How it works:637 How it works:


615 2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context640 2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context

616 3. **Tool State**: Tool usage and results from the previous conversation are preserved641 3. **Tool State**: Tool usage and results from the previous conversation are preserved

617 4. **Context Restoration**: The conversation resumes with all previous context intact642 4. **Context Restoration**: The conversation resumes with all previous context intact

643</Tip>

618 644 

619 Examples:645***

620 646 

621 ```bash theme={null}647## Run parallel Claude Code sessions with Git worktrees

622 # Continue most recent conversation

623 claude --continue

624 648 

625 # Continue most recent conversation with a specific prompt649When 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.

626 claude --continue --print "Show me our progress"

627 650 

628 # Show conversation picker651Use 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:

629 claude --resume

630 652 

631 # Continue most recent conversation in non-interactive mode653```bash theme={null}

632 claude --continue --print "Run the tests again"654# Start Claude in a worktree named "feature-auth"

633 ```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 modifications to tracked files and no unpushed commits. Untracked files (new files never staged with `git add`) are not checked and do not prevent removal. 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.

634</Tip>700</Tip>

635 701 

636***702### Copy gitignored files to worktrees

637 703 

638## Run parallel Claude Code sessions with Git worktrees704Git 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.

639 705 

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

641 707 

642<Steps>708```text .worktreeinclude theme={null}

643 <Step title="Understand Git worktrees">709.env

644 Git worktrees allow you to check out multiple branches from the same710.env.local

645 repository into separate directories. Each worktree has its own working711config/secrets.json

646 directory with isolated files, while sharing the same Git history. Learn712```

647 more in the [official Git worktree

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

649 </Step>

650 713 

651 <Step title="Create a new worktree">714This applies to worktrees created with `--worktree`, subagent worktrees, and parallel sessions in the [desktop app](/en/desktop#work-in-parallel-with-sessions).

652 ```bash theme={null}

653 # Create a new worktree with a new branch

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

655 715 

656 # Or create a worktree with an existing branch716### Manage worktrees manually

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

658 ```

659 717 

660 This creates a new directory with a separate working copy of your repository.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.

661 </Step>

662 719 

663 <Step title="Run Claude Code in each worktree">720```bash theme={null}

664 ```bash theme={null}721# Create a worktree with a new branch

665 # Navigate to your worktree 722git worktree add ../project-feature-a -b feature-a

666 cd ../project-feature-a

667 723 

668 # Run Claude Code in this isolated environment724# Create a worktree with an existing branch

669 claude725git worktree add ../project-bugfix bugfix-123

670 ```

671 </Step>

672 726 

673 <Step title="Run Claude in another worktree">727# Start Claude in the worktree

674 ```bash theme={null}728cd ../project-feature-a && claude

675 cd ../project-bugfix729 

676 claude730# 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 }

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

678 </Step>820 </Step>

679 821 

680 <Step title="Manage your worktrees">822 <Step title="Optionally narrow the matcher">

681 ```bash theme={null}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:

682 # List all worktrees

683 git worktree list

684 824 

685 # Remove a worktree when done825 | Matcher | Fires when |

686 git worktree remove ../project-feature-a826 | :------------------- | :---------------------------------------------- |

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

688 </Step>831 </Step>

689</Steps>

690 832 

691<Tip>833 <Step title="Verify the hook">

692 Tips: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>

693 837 

694 * Each worktree has its own independent file state, making it perfect for parallel Claude Code sessions838For the complete event schema and notification types, see the [Notification reference](/en/hooks#notification).

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

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

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

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

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

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

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

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

703</Tip>

704 839 

705***840***

706 841 


746 881 

747 * Use pipes to integrate Claude into existing shell scripts882 * Use pipes to integrate Claude into existing shell scripts

748 * Combine with other Unix tools for powerful workflows883 * Combine with other Unix tools for powerful workflows

749 * Consider using --output-format for structured output884 * Consider using `--output-format` for structured output

750</Tip>885</Tip>

751 886 

752### Control output format887### Control output format


789 924 

790***925***

791 926 

792## Create custom slash commands927## Run Claude on a schedule

793 928 

794Claude Code supports custom slash commands that you can create to quickly execute specific prompts or tasks.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.

795 930 

796For more details, see the [Slash commands](/en/docs/claude-code/slash-commands) reference page.931Pick a scheduling option based on where you want the task to run:

797 932 

798### Create project-specific commands933| Option | Where it runs | Best for |

799 934| :----------------------------------------------------- | :-------------------------------- | :------------------------------------------------------------------------------------------------------------ |

800Suppose you want to create reusable slash commands for your project that all team members can use.935| [Cloud scheduled tasks](/en/web-scheduled-tasks) | Anthropic-managed infrastructure | Tasks that should run even when your computer is off. Configure at [claude.ai/code](https://claude.ai/code). |

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

802<Steps>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. |

803 <Step title="Create a commands directory in your project">938| [`/loop`](/en/scheduled-tasks) | The current CLI session | Quick polling while a session is open. Tasks are cancelled when you exit. |

804 ```bash theme={null}

805 mkdir -p .claude/commands

806 ```

807 </Step>

808 

809 <Step title="Create a Markdown file for each command">

810 ```bash theme={null}

811 echo "Analyze the performance of this code and suggest three specific optimizations:" > .claude/commands/optimize.md

812 ```

813 </Step>

814 

815 <Step title="Use your custom command in Claude Code">

816 ```

817 > /optimize

818 ```

819 </Step>

820</Steps>

821 

822<Tip>

823 Tips:

824 

825 * Command names are derived from the filename (e.g., `optimize.md` becomes `/optimize`)

826 * You can organize commands in subdirectories (e.g., `.claude/commands/frontend/component.md` creates `/component` with "(project:frontend)" shown in the description)

827 * Project commands are available to everyone who clones the repository

828 * The Markdown file content becomes the prompt sent to Claude when the command is invoked

829</Tip>

830 

831### Add command arguments with \$ARGUMENTS

832 

833Suppose you want to create flexible slash commands that can accept additional input from users.

834 

835<Steps>

836 <Step title="Create a command file with the $ARGUMENTS placeholder">

837 ```bash theme={null}

838 echo 'Find and fix issue #$ARGUMENTS. Follow these steps: 1.

839 Understand the issue described in the ticket 2. Locate the relevant code in

840 our codebase 3. Implement a solution that addresses the root cause 4. Add

841 appropriate tests 5. Prepare a concise PR description' >

842 .claude/commands/fix-issue.md

843 ```

844 </Step>

845 

846 <Step title="Use the command with an issue number">

847 In your Claude session, use the command with arguments.

848 

849 ```

850 > /fix-issue 123

851 ```

852 

853 This will replace \$ARGUMENTS with "123" in the prompt.

854 </Step>

855</Steps>

856 939 

857<Tip>940<Tip>

858 Tips: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."

859 

860 * The \$ARGUMENTS placeholder is replaced with any text that follows the command

861 * You can position \$ARGUMENTS anywhere in your command template

862 * Other useful applications: generating test cases for specific functions, creating documentation for components, reviewing code in particular files, or translating content to specified languages

863</Tip>

864 

865### Create personal slash commands

866 

867Suppose you want to create personal slash commands that work across all your projects.

868 

869<Steps>

870 <Step title="Create a commands directory in your home folder">

871 ```bash theme={null}

872 mkdir -p ~/.claude/commands

873 ```

874 </Step>

875 

876 <Step title="Create a Markdown file for each command">

877 ```bash theme={null}

878 echo "Review this code for security vulnerabilities, focusing on:" >

879 ~/.claude/commands/security-review.md

880 ```

881 </Step>

882 

883 <Step title="Use your personal custom command">

884 ```

885 > /security-review

886 ```

887 </Step>

888</Steps>

889 

890<Tip>

891 Tips:

892 

893 * Personal commands show "(user)" in their description when listed with `/help`

894 * Personal commands are only available to you and not shared with your team

895 * Personal commands work across all your projects

896 * You can use these for consistent workflows across different codebases

897</Tip>942</Tip>

898 943 

899***944***


904 949 

905### Example questions950### Example questions

906 951 

907```952```text theme={null}

908> can Claude Code create pull requests?953can Claude Code create pull requests?

909```954```

910 955 

911```956```text theme={null}

912> how does Claude Code handle permissions?957how does Claude Code handle permissions?

913```958```

914 959 

915```960```text theme={null}

916> what slash commands are available?961what skills are available?

917```962```

918 963 

919```964```text theme={null}

920> how do I use MCP with Claude Code?965how do I use MCP with Claude Code?

921```966```

922 967 

923```968```text theme={null}

924> how do I configure Claude Code for Amazon Bedrock?969how do I configure Claude Code for Amazon Bedrock?

925```970```

926 971 

927```972```text theme={null}

928> what are the limitations of Claude Code?973what are the limitations of Claude Code?

929```974```

930 975 

931<Note>976<Note>

932 Claude provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above.977 Claude provides documentation-based answers to these questions. For hands-on demonstrations, run `/powerup` for interactive lessons with animated demos, or refer to the specific workflow sections above.

933</Note>978</Note>

934 979 

935<Tip>980<Tip>


944 989 

945## Next steps990## Next steps

946 991 

947<Card title="Claude Code reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">992<CardGroup cols={2}>

948 Clone our development container reference implementation.993 <Card title="Best practices" icon="lightbulb" href="/en/best-practices">

949</Card>994 Patterns for getting the most out of Claude Code

995 </Card>

996 

997 <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">

998 Understand the agentic loop and context management

999 </Card>

1000 

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

1002 Add skills, hooks, MCP, subagents, and plugins

1003 </Card>

1004 

1005 <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">

1006 Clone the development container reference implementation

1007 </Card>

1008</CardGroup>

computer-use.md +208 −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# Let Claude use your computer from the CLI

6 

7> Enable computer use in the Claude Code CLI so Claude can open apps, click, type, and see your screen on macOS. Test native apps, debug visual issues, and automate GUI-only tools without leaving your terminal.

8 

9<Note>

10 {/* plan-availability: feature=computer-use plans=pro,max */}

11 

12 Computer use is a research preview on macOS that requires a Pro or Max plan. It is not available on Team or Enterprise plans. It requires Claude Code v2.1.85 or later and an interactive session, so it is not available in non-interactive mode with the `-p` flag.

13</Note>

14 

15Computer use lets Claude open apps, control your screen, and work on your machine the way you would. From the CLI, Claude can compile a Swift app, launch it, click through every button, and screenshot the result, all in the same conversation where it wrote the code.

16 

17This page covers how computer use works in the CLI. For the Desktop app on macOS or Windows, see [computer use in Desktop](/en/desktop#let-claude-use-your-computer).

18 

19## What you can do with computer use

20 

21Computer use handles tasks that require a GUI: anything you'd normally have to leave the terminal and do by hand.

22 

23* **Build and validate native apps**: ask Claude to build a macOS menu bar app. Claude writes the Swift, compiles it, launches it, and clicks through every control to verify it works before you ever open it.

24* **End-to-end UI testing**: point Claude at a local Electron app and say "test the onboarding flow." Claude opens the app, clicks through signup, and screenshots each step. No Playwright config, no test harness.

25* **Debug visual and layout issues**: tell Claude "the modal is clipping on small windows." Claude resizes the window, reproduces the bug, screenshots it, patches the CSS, and verifies the fix. Claude sees what you see.

26* **Drive GUI-only tools**: interact with design tools, hardware control panels, the iOS Simulator, or proprietary apps that have no CLI or API.

27 

28## When computer use applies

29 

30Claude has several ways to interact with an app or service. Computer use is the broadest and slowest, so Claude tries the most precise tool first:

31 

32* If you have an [MCP server](/en/mcp) for the service, Claude uses that.

33* If the task is a shell command, Claude uses Bash.

34* If the task is browser work and you have [Claude in Chrome](/en/chrome) set up, Claude uses that.

35* If none of those apply, Claude uses computer use.

36 

37Screen control is reserved for things nothing else can reach: native apps, simulators, and tools without an API.

38 

39## Enable computer use

40 

41Computer use is available as a built-in MCP server called `computer-use`. It's off by default until you enable it.

42 

43<Steps>

44 <Step title="Open the MCP menu">

45 In an interactive Claude Code session, run:

46 

47 ```text theme={null}

48 /mcp

49 ```

50 

51 Find `computer-use` in the server list. It shows as disabled.

52 </Step>

53 

54 <Step title="Enable the server">

55 Select `computer-use` and choose **Enable**. The setting persists per project, so you only do this once for each project where you want computer use.

56 </Step>

57 

58 <Step title="Grant macOS permissions">

59 The first time Claude tries to use your computer, you'll see a prompt to grant two macOS permissions:

60 

61 * **Accessibility**: lets Claude click, type, and scroll

62 * **Screen Recording**: lets Claude see what's on your screen

63 

64 The prompt includes links to open the relevant System Settings pane. Grant both, then select **Try again** in the prompt. macOS may require you to restart Claude Code after granting Screen Recording.

65 </Step>

66</Steps>

67 

68After setup, ask Claude to do something that needs the GUI:

69 

70```text theme={null}

71Build the app target, launch it, and click through each tab to make

72sure nothing crashes. Screenshot any error states you find.

73```

74 

75## Approve apps per session

76 

77Enabling the `computer-use` server doesn't grant Claude access to every app on your machine. The first time Claude needs a specific app in a session, a prompt appears in your terminal showing:

78 

79* Which apps Claude wants to control

80* Any extra permissions requested, such as clipboard access

81* How many other apps will be hidden while Claude works

82 

83Choose **Allow for this session** or **Deny**. Approvals last for the current session. You can approve multiple apps at once when Claude requests them together.

84 

85Apps with broad reach show an extra warning in the prompt so you know what approving them grants:

86 

87| Warning | Applies to |

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

89| Equivalent to shell access | Terminal, iTerm, VS Code, Warp, and other terminals and IDEs |

90| Can read or write any file | Finder |

91| Can change system settings | System Settings |

92 

93These apps aren't blocked. The warning lets you decide whether the task warrants that level of access.

94 

95Claude's level of control also varies by app category: browsers and trading platforms are view-only, terminals and IDEs are click-only, and everything else gets full control. See [app permissions in Desktop](/en/desktop#app-permissions) for the complete tier breakdown.

96 

97## How Claude works on your screen

98 

99Understanding the flow helps you anticipate what Claude will do and how to intervene.

100 

101### One session at a time

102 

103Computer use holds a machine-wide lock while active. If another Claude Code session is already using your computer, new attempts fail with a message telling you which session holds the lock. Finish or exit that session first.

104 

105### Apps are hidden while Claude works

106 

107When Claude starts controlling your screen, other visible apps are hidden so Claude interacts with only the approved apps. Your terminal window stays visible and is excluded from screenshots, so you can watch the session and Claude never sees its own output.

108 

109When Claude finishes the turn, hidden apps are restored automatically.

110 

111### Stop at any time

112 

113When Claude acquires the lock, a macOS notification appears: "Claude is using your computer · press Esc to stop." Press `Esc` anywhere to abort the current action immediately, or press `Ctrl+C` in the terminal. Either way, Claude releases the lock, unhides your apps, and returns control to you.

114 

115A second notification appears when Claude is done.

116 

117## Safety and the trust boundary

118 

119<Warning>

120 Unlike the [sandboxed Bash tool](/en/sandboxing), computer use runs on your actual desktop with access to the apps you approve. Claude checks each action and flags potential prompt injection from on-screen content, but the trust boundary is different. See the [computer use safety guide](https://support.claude.com/en/articles/14128542) for best practices.

121</Warning>

122 

123The built-in guardrails reduce risk without requiring configuration:

124 

125* **Per-app approval**: Claude can only control apps you've approved in the current session.

126* **Sentinel warnings**: apps that grant shell, filesystem, or system settings access are flagged before you approve.

127* **Terminal excluded from screenshots**: Claude never sees your terminal window, so on-screen prompts in your session can't feed back into the model.

128* **Global escape**: the `Esc` key aborts computer use from anywhere, and the key press is consumed so prompt injection can't use it to dismiss dialogs.

129* **Lock file**: only one session can control your machine at a time.

130 

131## Example workflows

132 

133These examples show common ways to combine computer use with coding tasks.

134 

135### Validate a native build

136 

137After making changes to a macOS or iOS app, have Claude compile and verify in one pass:

138 

139```text theme={null}

140Build the MenuBarStats target, launch it, open the preferences window,

141and verify the interval slider updates the label. Screenshot the

142preferences window when you're done.

143```

144 

145Claude runs `xcodebuild`, launches the app, interacts with the UI, and reports what it finds.

146 

147### Reproduce a layout bug

148 

149When a visual bug only appears at certain window sizes, let Claude find it:

150 

151```text theme={null}

152The settings modal clips its footer on narrow windows. Resize the app

153window down until you can reproduce it, screenshot the clipped state,

154then check the CSS for the modal container.

155```

156 

157Claude resizes the window, captures the broken state, and reads the relevant stylesheets.

158 

159### Test a simulator flow

160 

161Drive the iOS Simulator without writing XCTest:

162 

163```text theme={null}

164Open the iOS Simulator, launch the app, tap through the onboarding

165screens, and tell me if any screen takes more than a second to load.

166```

167 

168Claude controls the simulator the same way you would with a mouse.

169 

170## Differences from the Desktop app

171 

172The CLI and Desktop surfaces share the same computer use engine, with a few differences:

173 

174| Feature | Desktop | CLI |

175| :------------------- | :------------------------------------------------------- | :------------------------------ |

176| Platforms | macOS and Windows | macOS only |

177| Enable | Toggle in **Settings > General** (under **Desktop app**) | Enable `computer-use` in `/mcp` |

178| Denied apps list | Configurable in Settings | Not yet available |

179| Auto-unhide toggle | Optional | Always on |

180| Dispatch integration | Dispatch-spawned sessions can use computer use | Not applicable |

181 

182## Troubleshooting

183 

184### "Computer use is in use by another Claude session"

185 

186Another Claude Code session holds the lock. Finish the task in that session or exit it. If the other session crashed, the lock is released automatically when Claude detects the process is no longer running.

187 

188### macOS permissions prompt keeps reappearing

189 

190macOS sometimes requires a restart of the requesting process after you grant Screen Recording. Quit Claude Code completely and start a new session. If the prompt persists, open **System Settings > Privacy & Security > Screen Recording** and confirm your terminal app is listed and enabled.

191 

192### `computer-use` doesn't appear in `/mcp`

193 

194The server only appears on eligible setups. Check that:

195 

196* You're on macOS. Computer use in the CLI is not available on Linux or Windows. On Windows, use [computer use in Desktop](/en/desktop#let-claude-use-your-computer) instead.

197* You're running Claude Code v2.1.85 or later. Run `claude --version` to check.

198* You're on a Pro or Max plan. Run `/status` to confirm your subscription.

199* You're authenticated through claude.ai. Computer use is not available with third-party providers like Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry. If you access Claude exclusively through a third-party provider, you need a separate claude.ai account to use this feature.

200* You're in an interactive session. Computer use is not available in non-interactive mode with the `-p` flag.

201 

202## See also

203 

204* [Computer use in Desktop](/en/desktop#let-claude-use-your-computer): the same capability with a graphical settings page

205* [Claude in Chrome](/en/chrome): browser automation for web-based tasks

206* [MCP](/en/mcp): connect Claude to structured tools and APIs

207* [Sandboxing](/en/sandboxing): how Claude's Bash tool isolates filesystem and network access

208* [Computer use safety guide](https://support.claude.com/en/articles/14128542): best practices for safe computer use

context-window.md +35 −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# Explore the context window

6 

7> An interactive simulation of how Claude Code's context window fills during a session. See what loads automatically, what each file read costs, and when rules and hooks fire.

8 

9 

10Claude Code's context window holds everything Claude knows about your session: your instructions, the files it reads, its own responses, and content that never appears in your terminal. The timeline below walks through what loads and when. See [the written breakdown](#what-the-timeline-shows) for the same content as a list.

11 

12<ContextWindow />

13 

14## What the timeline shows

15 

16The session walks through a realistic flow with representative token counts:

17 

18* **Before you type anything**: CLAUDE.md, auto memory, MCP tool names, and skill descriptions all load into context. Your own setup may add more here, like an [output style](/en/output-styles) or text from [`--append-system-prompt`](/en/cli-reference), which both go into the system prompt the same way.

19* **As Claude works**: each file read adds to context, [path-scoped rules](/en/memory#path-specific-rules) load automatically alongside matching files, and a [PostToolUse hook](/en/hooks-guide) fires after each edit.

20* **The follow-up prompt**: a [subagent](/en/sub-agents) handles the research in its own separate context window, so the large file reads stay out of yours. Only the summary and a small metadata trailer come back.

21* **At the end**: `/compact` replaces the conversation with a structured summary. Most startup content reloads automatically. The [skill](/en/skills) listing is the one exception.

22 

23## Check your own session

24 

25The visualization uses representative numbers. To see your actual context usage at any point, run `/context` for a live breakdown by category with optimization suggestions. Run `/memory` to check which CLAUDE.md and auto memory files loaded at startup.

26 

27## Related resources

28 

29For deeper coverage of the features shown in the timeline, see these pages:

30 

31* [Extend Claude Code](/en/features-overview): when to use CLAUDE.md vs skills vs rules vs hooks vs MCP

32* [Store instructions and memories](/en/memory): CLAUDE.md hierarchy and auto memory

33* [Subagents](/en/sub-agents): delegate research to a separate context window

34* [Best practices](/en/best-practices): managing context as your primary constraint

35* [Reduce token usage](/en/costs#reduce-token-usage): strategies for keeping context usage low

costs.md +129 −59

Details

1> ## Documentation Index

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

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

4 

1# Manage costs effectively5# Manage costs effectively

2 6 

3> Learn how to track and optimize token usage and costs when using Claude Code.7> Track token usage, set team spend limits, and reduce Claude Code costs with context management, model selection, extended thinking settings, and preprocessing hooks.

8 

9Claude Code consumes tokens for each interaction. Costs vary based on codebase size, query complexity, and conversation length. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users.

4 10 

5Claude Code consumes tokens for each interaction. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users.11For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.6 though there is large variance depending on how many instances users are running and whether they're using it in automation.

6 12 

7For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.5 though there is large variance depending on how many instances users are running and whether they're using it in automation.13This page covers how to [track your costs](#track-your-costs), [manage costs for teams](#managing-costs-for-teams), and [reduce token usage](#reduce-token-usage).

8 14 

9## Track your costs15## Track your costs

10 16 

11### Using the `/cost` command17### Using the `/cost` command

12 18 

13<Note>19<Note>

14 The `/cost` command is not intended for Claude Max and Pro subscribers.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.

15</Note>21</Note>

16 22 

17The `/cost` command provides detailed token usage statistics for your current session:23The `/cost` command provides detailed token usage statistics for your current session:

18 24 

19```25```text theme={null}

20Total cost: $0.5526Total cost: $0.55

21Total duration (API): 6m 19.7s27Total duration (API): 6m 19.7s

22Total duration (wall): 6h 33m 10.2s28Total duration (wall): 6h 33m 10.2s

23Total code changes: 0 lines added, 0 lines removed29Total code changes: 0 lines added, 0 lines removed

24```30```

25 31 

26### Additional tracking options32## Managing costs for teams

27 33 

28Check [historical usage](https://support.claude.com/en/articles/9534590-cost-and-usage-reporting-in-console) in the Claude Console (requires Admin or Billing role) and set [workspace spend limits](https://support.claude.com/en/articles/9796807-creating-and-managing-workspaces) for the Claude Code workspace (requires Admin role).34When using Claude API, you can [set workspace spend limits](https://platform.claude.com/docs/en/build-with-claude/workspaces#workspace-limits) on the total Claude Code workspace spend. Admins can [view cost and usage reporting](https://platform.claude.com/docs/en/build-with-claude/workspaces#usage-and-cost-tracking) in the Console.

29 35 

30<Note>36<Note>

31 When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace - it is exclusively for Claude Code authentication and usage.37 When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization. You cannot create API keys for this workspace; it is exclusively for Claude Code authentication and usage.

32</Note>38</Note>

33 39 

34## Managing costs for teams40On Bedrock, Vertex, and Foundry, Claude Code does not send metrics from your cloud. To get cost metrics, several large enterprises reported using [LiteLLM](/en/llm-gateway#litellm-configuration), which is an open-source tool that helps companies [track spend by key](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend). This project is unaffiliated with Anthropic and has not been audited for security.

35 

36When using Claude API, you can limit the total Claude Code workspace spend. To configure, [follow these instructions](https://support.claude.com/en/articles/9796807-creating-and-managing-workspaces). Admins can view cost and usage reporting by [following these instructions](https://support.claude.com/en/articles/9534590-cost-and-usage-reporting-in-console).

37 

38On Bedrock and Vertex, Claude Code does not send metrics from your cloud. In order to get cost metrics, several large enterprises reported using [LiteLLM](/en/docs/claude-code/bedrock-vertex-proxies#litellm), which is an open-source tool that helps companies [track spend by key](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend). This project is unaffiliated with Anthropic and we have not audited its security.

39 41 

40### Rate limit recommendations42### Rate limit recommendations

41 43 


52 54 

53For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).55For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).

54 56 

55The TPM per user decreases as team size grows because we expect fewer users to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service.57The TPM per user decreases as team size grows because fewer users tend to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren't actively using the service.

56 58 

57<Note>59<Note>

58 If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user.60 If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user.

59</Note>61</Note>

60 62 

63### Agent team token costs

64 

65[Agent teams](/en/agent-teams) spawn multiple Claude Code instances, each with its own context window. Token usage scales with the number of active teammates and how long each one runs.

66 

67To keep agent team costs manageable:

68 

69* Use Sonnet for teammates. It balances capability and cost for coordination tasks.

70* Keep teams small. Each teammate runs its own context window, so token usage is roughly proportional to team size.

71* Keep spawn prompts focused. Teammates load CLAUDE.md, MCP servers, and skills automatically, but everything in the spawn prompt adds to their context from the start.

72* Clean up teams when work is done. Active teammates continue consuming tokens even if idle.

73* Agent teams are disabled by default. Set `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` in your [settings.json](/en/settings) or environment to enable them. See [enable agent teams](/en/agent-teams#enable-agent-teams).

74 

61## Reduce token usage75## Reduce token usage

62 76 

63* **Compact conversations:**77Token costs scale with context size: the more context Claude processes, the more tokens you use. Claude Code automatically optimizes costs through prompt caching (which reduces costs for repeated content like system prompts) and auto-compaction (which summarizes conversation history when approaching context limits).

64 78 

65 * Claude uses auto-compact by default when context exceeds 95% capacity79The following strategies help you keep context small and reduce per-message costs.

66 * Toggle auto-compact: Run `/config` and navigate to "Auto-compact enabled"

67 * Use `/compact` manually when context gets large

68 * Add custom instructions: `/compact Focus on code samples and API usage`

69 * Customize compaction by adding to CLAUDE.md:

70 80 

71 ```markdown theme={null}81### Manage context proactively

72 # Summary instructions

73 82 

74 When you are using compact, please focus on test output and code changes83Use `/cost` to check your current token usage, or [configure your status line](/en/statusline#context-window-usage) to display it continuously.

75 ```

76 84 

77* **Write specific queries:** Avoid vague requests that trigger unnecessary scanning85* **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.

86* **Add custom compaction instructions**: `/compact Focus on code samples and API usage` tells Claude what to preserve during summarization.

78 87 

79* **Break down complex tasks:** Split large tasks into focused interactions88You can also customize compaction behavior in your CLAUDE.md:

80 89 

81* **Clear history between tasks:** Use `/clear` to reset context90```markdown theme={null}

91# Compact instructions

82 92 

83Costs can vary significantly based on:93When you are using compact, please focus on test output and code changes

94```

84 95 

85* Size of codebase being analyzed96### Choose the right model

86* Complexity of queries

87* Number of files being searched or modified

88* Length of conversation history

89* Frequency of compacting conversations

90 97 

91## Background token usage98Sonnet handles most coding tasks well and costs less than Opus. Reserve Opus for complex architectural decisions or multi-step reasoning. Use `/model` to switch models mid-session, or set a default in `/config`. For simple subagent tasks, specify `model: haiku` in your [subagent configuration](/en/sub-agents#choose-a-model).

92 99 

93Claude Code uses tokens for some background functionality even when idle:100### Reduce MCP server overhead

94 101 

95* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature102MCP tool definitions are [deferred by default](/en/mcp#scale-with-mcp-tool-search), so only tool names enter context until Claude uses a specific tool. Run `/context` to see what's consuming space.

96* **Command processing**: Some commands like `/cost` may generate requests to check status

97 103 

98These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.104* **Prefer CLI tools when available**: Tools like `gh`, `aws`, `gcloud`, and `sentry-cli` are still more context-efficient than MCP servers because they don't add any per-tool listing. Claude can run CLI commands directly.

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

99 106 

100## Tracking version changes and updates107### Install code intelligence plugins for typed languages

101 108 

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

103 110 

104To check your current Claude Code version and installation details:111### Offload processing to hooks and skills

105 112 

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

107claude doctor

108```

109 114 

110This command shows your version, installation type, and system information.115A [skill](/en/skills) can give Claude domain knowledge so it doesn't have to explore. For example, a "codebase-overview" skill could describe your project's architecture, key directories, and naming conventions. When Claude invokes the skill, it gets this context immediately instead of spending tokens reading multiple files to understand the structure.

111 116 

112### Understanding changes in Claude Code behavior117For example, this PreToolUse hook filters test output to show only failures:

113 118 

114Claude Code regularly receives updates that may change how features work, including cost reporting:119<Tabs>

120 <Tab title="settings.json">

121 Add this to your [settings.json](/en/settings#settings-files) to run the hook before every Bash command:

115 122 

116* **Version tracking**: Use `claude doctor` to see your current version123 ```json theme={null}

117* **Behavior changes**: Features like `/cost` may display information differently across versions124 {

118* **Documentation access**: Claude always has access to the latest documentation, which can help explain current feature behavior125 "hooks": {

126 "PreToolUse": [

127 {

128 "matcher": "Bash",

129 "hooks": [

130 {

131 "type": "command",

132 "command": "~/.claude/hooks/filter-test-output.sh"

133 }

134 ]

135 }

136 ]

137 }

138 }

139 ```

140 </Tab>

141 

142 <Tab title="filter-test-output.sh">

143 The hook calls this script, which checks if the command is a test runner and modifies it to show only failures:

144 

145 ```bash theme={null}

146 #!/bin/bash

147 input=$(cat)

148 cmd=$(echo "$input" | jq -r '.tool_input.command')

149 

150 # If running tests, filter to show only failures

151 if [[ "$cmd" =~ ^(npm test|pytest|go test) ]]; then

152 filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"

153 echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"$filtered_cmd\"}}}"

154 else

155 echo "{}"

156 fi

157 ```

158 </Tab>

159</Tabs>

119 160 

120### When cost reporting changes161### Move instructions from CLAUDE.md to skills

121 162 

122If you notice changes in how costs are displayed (such as the `/cost` command showing different information):163Your [CLAUDE.md](/en/memory) file is loaded into context at session start. If it contains detailed instructions for specific workflows (like PR reviews or database migrations), those tokens are present even when you're doing unrelated work. [Skills](/en/skills) load on-demand only when invoked, so moving specialized instructions into skills keeps your base context smaller. Aim to keep CLAUDE.md under 200 lines by including only essentials.

123 164 

1241. **Verify your version**: Run `claude doctor` to confirm your current version165### Adjust extended thinking

1252. **Consult documentation**: Ask Claude directly about current feature behavior, as it has access to up-to-date documentation

1263. **Contact support**: For specific billing questions, contact Anthropic support through your Console account

127 166 

128<Note>167Extended thinking is enabled by default because it significantly improves performance on complex planning and reasoning tasks. Thinking tokens are billed as output tokens, and the default budget can be tens of thousands of tokens per request depending on the model. For simpler tasks where deep reasoning isn't needed, you can reduce costs by lowering the [effort level](/en/model-config#adjust-effort-level) with `/effort` or in `/model`, disabling thinking in `/config`, or lowering the budget with `MAX_THINKING_TOKENS=8000`.

129 For team deployments, we recommend starting with a small pilot group to168 

130 establish usage patterns before wider rollout.169### Delegate verbose operations to subagents

131</Note>170 

171Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](/en/sub-agents#isolate-high-volume-operations) so the verbose output stays in the subagent's context while only a summary returns to your main conversation.

172 

173### Manage agent team costs

174 

175Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode, because each teammate maintains its own context window and runs as a separate Claude instance. Keep team tasks small and self-contained to limit per-teammate token usage. See [agent teams](/en/agent-teams) for details.

176 

177### Write specific prompts

178 

179Vague requests like "improve this codebase" trigger broad scanning. Specific requests like "add input validation to the login function in auth.ts" let Claude work efficiently with minimal file reads.

180 

181### Work efficiently on complex tasks

182 

183For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path:

184 

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

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

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

188* **Test incrementally**: Write one file, test it, then continue. This catches issues early when they're cheap to fix.

189 

190## Background token usage

191 

192Claude Code uses tokens for some background functionality even when idle:

193 

194* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature

195* **Command processing**: Some commands like `/cost` may generate requests to check status

196 

197These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.

198 

199## Understanding changes in Claude Code behavior

200 

201Claude Code regularly receives updates that may change how features work, including cost reporting. Run `claude --version` to check your current version. For specific billing questions, contact Anthropic support through your [Console account](https://platform.claude.com/login). For team deployments, start with a small pilot group to establish usage patterns before wider rollout.

data-usage.md +39 −37

Details

1> ## Documentation Index

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

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

4 

1# Data usage5# Data usage

2 6 

3> Learn about Anthropic's data usage policies for Claude7> Learn about Anthropic's data usage policies for Claude


7### Data training policy11### Data training policy

8 12 

9**Consumer users (Free, Pro, and Max plans)**:13**Consumer users (Free, Pro, and Max plans)**:

10Starting August 28, 2025, we're giving you the choice to allow your data to be used to improve future Claude models.14We give you the choice to allow your data to be used to improve future Claude models. We will train new models using data from Free, Pro, and Max accounts when this setting is on (including when you use Claude Code from these accounts).

11 

12We will train new models using data from Free, Pro, and Max accounts when this setting is on (including when you use Claude Code from these accounts).

13 

14* If you're a current user, you can select your preference now and your selection will immediately go into effect.

15 This setting will only apply to new or resumed chats and coding sessions on Claude. Previous chats with no additional activity will not be used for model training.

16* You have until October 8, 2025 to make your selection.

17 If you're a new user, you can pick your setting for model training during the signup process.

18 You can change your selection at any time in your Privacy Settings.

19 15 

20**Commercial users**: (Team and Enterprise plans, API, 3rd-party platforms, and Claude Gov) maintain existing policies: Anthropic does not train generative models using code or prompts sent to Claude Code under commercial terms, unless the customer has chosen to provide their data to us for model improvement (e.g. [Developer Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program)).16**Commercial users**: (Team and Enterprise plans, API, 3rd-party platforms, and Claude Gov) maintain existing policies: Anthropic does not train generative models using code or prompts sent to Claude Code under commercial terms, unless the customer has chosen to provide their data to us for model improvement (for example, the [Developer Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program)).

21 17 

22### Development Partner Program18### Development Partner Program

23 19 

24If you explicitly opt in to methods to provide us with materials to train on, such as via the [Development Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program), we may use those materials provided to train our models. An organization admin can expressly opt-in to the Development Partner Program for their organization. Note that this program is available only for Anthropic first-party API, and not for Bedrock or Vertex users.20If you explicitly opt in to methods to provide us with materials to train on, such as via the [Development Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program), we may use those materials provided to train our models. An organization admin can expressly opt-in to the Development Partner Program for their organization. Note that this program is available only for Anthropic first-party API, and not for Bedrock or Vertex users.

25 21 

26### Feedback using the `/bug` command22### Feedback using the `/feedback` command

27 23 

28If you choose to send us feedback about Claude Code using the `/bug` command, we may use your feedback to improve our products and services. Transcripts shared via `/bug` are retained for 5 years.24If you choose to send us feedback about Claude Code using the `/feedback` command, we may use your feedback to improve our products and services. Transcripts shared via `/feedback` are retained for 5 years.

29 25 

30### Session quality surveys26### Session quality surveys

31 27 

32When you see the "How is Claude doing this session?" prompt in Claude Code, responding to this survey (including selecting "Dismiss"), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/bug` reports, this session quality survey is a simple product satisfaction metric. Your responses to this survey do not impact your data training preferences and cannot be used to train our AI models.28When you see the "How is Claude doing this session?" prompt in Claude Code, responding to this survey (including selecting "Dismiss"), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/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.

29 

30To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also disabled when `DISABLE_TELEMETRY` or `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set. To control frequency instead of disabling, set [`feedbackSurveyRate`](/en/settings#available-settings) in your settings file to a probability between `0` and `1`.

33 31 

34### Data retention32### Data retention

35 33 


39 37 

40* Users who allow data use for model improvement: 5-year retention period to support model development and safety improvements38* Users who allow data use for model improvement: 5-year retention period to support model development and safety improvements

41* Users who don't allow data use for model improvement: 30-day retention period39* Users who don't allow data use for model improvement: 30-day retention period

42* Privacy settings can be changed at any time at [claude.ai/settings/data-privacy-controls](claude.ai/settings/data-privacy-controls).40* Privacy settings can be changed at any time at [claude.ai/settings/data-privacy-controls](https://claude.ai/settings/data-privacy-controls).

43 41 

44**Commercial users (Team, Enterprise, and API)**:42**Commercial users (Team, Enterprise, and API)**:

45 43 

46* Standard: 30-day retention period44* Standard: 30-day retention period

47* Zero data retention: Available with appropriately configured API keys - Claude Code will not retain chat transcripts on servers45* [Zero data retention](/en/zero-data-retention): available for Claude Code on Claude for Enterprise. ZDR is enabled on a per-organization basis; each new organization must have ZDR enabled separately by your account team

48* Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable)46* Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable)

49 47 

48You can delete individual Claude Code on the web sessions at any time. Deleting a session permanently removes the session's event data. For instructions on how to delete sessions, see [Managing sessions](/en/claude-code-on-the-web#managing-sessions).

49 

50Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).50Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).

51 51 

52For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).52For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).

53 53 

54## Data flow and dependencies54## Data access

55 55 

56<img src="https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=4b30069d702719e7bfb974eaaafab21c" alt="Claude Code data flow diagram" data-og-width="1597" width="1597" data-og-height="1285" height="1285" data-path="images/claude-code-data-flow.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=280&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=067676caa12f89051cb193e6b3f7d0a0 280w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=560&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=5506197deff927f54f2fb5a349f358a8 560w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=840&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=bb4febe7974dde5b76b88744f89ab472 840w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=1100&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=b51af3074f87b33ccc342aaad655dcbf 1100w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=1650&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=8fd96f1dde615877d4e4bbe1874af12d 1650w, https://mintcdn.com/anthropic-claude-docs/LF5WV0SNF6oudpT5/images/claude-code-data-flow.png?w=2500&fit=max&auto=format&n=LF5WV0SNF6oudpT5&q=85&s=056deded541ec30e9b67a67d620f6aaf 2500w" />56For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). [Remote Control](/en/remote-control) sessions follow the local data flow since all execution happens on your machine. Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.

57 

58## Local Claude Code: Data flow and dependencies

59 

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.

61 

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

57 63 

58Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.64Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.

59 65 

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

61 67 

62### Cloud execution68### Cloud execution: Data flow and dependencies

63 

64<Note>

65 The above data flow diagram and description applies to Claude Code CLI running locally on your machine. For cloud-based sessions using Claude Code on the web, see the section below.

66</Note>

67 69 

68When using [Claude Code on the web](/en/docs/claude-code/claude-code-on-the-web), sessions run in Anthropic-managed virtual machines instead of locally. In cloud environments:70When using [Claude Code on the web](/en/claude-code-on-the-web), sessions run in Anthropic-managed virtual machines instead of locally. In cloud environments:

69 71 

70* **Code storage**: Your repository is cloned to an isolated VM and automatically deleted after session completion72* **Code and data storage:** Your repository is cloned to an isolated VM. Code and session data are subject to the retention and usage policies for your account type (see Data retention section above)

71* **Credentials**: GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox73* **Credentials:** GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox

72* **Network traffic**: All outbound traffic goes through a security proxy for audit logging and abuse prevention74* **Network traffic:** All outbound traffic goes through a security proxy for audit logging and abuse prevention

73* **Data retention**: Code and session data are subject to the retention and usage policies for your account type75* **Session data:** Prompts, code changes, and outputs follow the same data policies as local Claude Code usage

74* **Session data**: Prompts, code changes, and outputs follow the same data policies as local Claude Code usage

75 76 

76For security details about cloud execution, see [Security](/en/docs/claude-code/security#cloud-execution-security).77For security details about cloud execution, see [Security](/en/security#cloud-execution-security).

77 78 

78## Telemetry services79## Telemetry services

79 80 


81 82 

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

83 84 

84When users run the `/bug` 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 of bug reporting, set the `DISABLE_BUG_COMMAND` environment variable.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`.

85 86 

86## Default behaviors by API provider87## Default behaviors by API provider

87 88 

88By default, we disable all non-essential traffic (including error reporting, telemetry, and bug reporting functionality) when using Bedrock or Vertex. You can also opt out of all of these at once by setting the `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` environment variable. Here are the full default behaviors:89By default, error reporting, telemetry, and bug reporting are disabled when using Bedrock, Vertex, or Foundry. Session quality surveys are the exception and appear regardless of provider. You can opt out of all non-essential traffic, including surveys, at once by setting `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`. Here are the full default behaviors:

89 90 

90| Service | Claude API | Vertex API | Bedrock API |91| Service | Claude API | Vertex API | Bedrock API | Foundry API |

91| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |92| ------------------------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- |

92| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |93| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

93| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |94| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

94| **Claude API (`/bug` reports)** | Default on.<br />`DISABLE_BUG_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. |95| **Claude API (`/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. |

95 97 

96All environment variables can be checked into `settings.json` ([read more](/en/docs/claude-code/settings)).98All environment variables can be checked into `settings.json` ([read more](/en/settings)).

desktop.md +643 −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# Use Claude Code Desktop

6 

7> Get more out of Claude Code Desktop: computer use, Dispatch sessions from your phone, parallel sessions with Git isolation, visual diff review, app previews, PR monitoring, connectors, and enterprise configuration.

8 

9The Code tab within the Claude Desktop app lets you use Claude Code through a graphical interface instead of the terminal.

10 

11Desktop adds these capabilities on top of the standard Claude Code experience:

12 

13* [Visual diff review](#review-changes-with-diff-view) with inline comments

14* [Live app preview](#preview-your-app) with dev servers

15* [Computer use](#let-claude-use-your-computer) to open apps and control your screen on macOS and Windows

16* [GitHub PR monitoring](#monitor-pull-request-status) with auto-fix and auto-merge

17* [Parallel sessions](#work-in-parallel-with-sessions) with automatic Git worktree isolation

18* [Dispatch](#sessions-from-dispatch) integration: send a task from your phone, get a session here

19* [Scheduled tasks](/en/desktop-scheduled-tasks) that run Claude on a recurring schedule

20* [Connectors](#connect-external-tools) for GitHub, Slack, Linear, and more

21* Local, [SSH](#ssh-sessions), and [cloud](#run-long-running-tasks-remotely) environments

22 

23<Tip>

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

25</Tip>

26 

27This page covers [working with code](#work-with-code), [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).

28 

29## Start a session

30 

31Before you send your first message, configure four things in the prompt area:

32 

33* **Environment**: choose where Claude runs. Select **Local** for your machine, **Remote** for Anthropic-hosted cloud sessions, or an [**SSH connection**](#ssh-sessions) for a remote machine you manage. See [environment configuration](#environment-configuration).

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

35* **Model**: pick a [model](/en/model-config#available-models) from the dropdown next to the send button. The model is locked once the session starts.

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

37 

38Type your task and press **Enter** to start. Each session tracks its own context and changes independently.

39 

40## Work with code

41 

42Give Claude the right context, control how much it does on its own, and review what it changed.

43 

44### Use the prompt box

45 

46Type what you want Claude to do and press **Enter** to send. Claude reads your project files, makes changes, and runs commands based on your [permission mode](#choose-a-permission-mode). You can interrupt Claude at any point: click the stop button or type your correction and press **Enter**. Claude stops what it's doing and adjusts based on your input.

47 

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

49 

50### Add files and context to prompts

51 

52The prompt box supports two ways to bring in external context:

53 

54* **@mention files**: type `@` followed by a filename to add a file to the conversation context. Claude can then read and reference that file. @mention is not available in remote sessions.

55* **Attach files**: attach images, PDFs, and other files to your prompt using the attachment button, or drag and drop files directly into the prompt. This is useful for sharing screenshots of bugs, design mockups, or reference documents.

56 

57### Choose a permission mode

58 

59Permission 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.

60 

61| Mode | Settings key | Behavior |

62| ---------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

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

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

65| **Plan mode** | `plan` | Claude analyzes your code and creates a plan without modifying files or running commands. Good for complex tasks where you want to review the approach first. |

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

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

68 

69The `dontAsk` permission mode is available only in the [CLI](/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode).

70 

71<Tip title="Best practice">

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

73</Tip>

74 

75Remote sessions support Auto accept edits and Plan mode. Ask permissions is not available because remote sessions auto-accept file edits by default, and Bypass permissions is not available because the remote environment is already sandboxed.

76 

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

78 

79### Preview your app

80 

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

82 

83From the preview panel, you can:

84 

85* Interact with your running app directly in the embedded browser

86* Watch Claude verify its own changes automatically: it takes screenshots, inspects the DOM, clicks elements, fills forms, and fixes issues it finds

87* Start or stop servers from the **Preview** dropdown in the session toolbar

88* Persist cookies and local storage across server restarts by selecting **Persist sessions** in the dropdown, so you don't have to re-login during development

89* Edit the server configuration or stop all servers at once

90 

91Claude creates the initial server configuration based on your project. If your app uses a custom dev command, edit `.claude/launch.json` to match your setup. See [Configure preview servers](#configure-preview-servers) for the full reference.

92 

93To clear saved session data, toggle **Persist preview sessions** off in Settings → Claude Code. To disable preview entirely, toggle off **Preview** in Settings → Claude Code.

94 

95### Review changes with diff view

96 

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

98 

99When Claude changes files, a diff stats indicator appears showing the number of lines added and removed, such as `+12 -1`. Click this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.

100 

101To comment on specific lines, click any line in the diff to open a comment box. Type your feedback and press **Enter** to add the comment. After adding comments to multiple lines, submit all comments at once:

102 

103* **macOS**: press **Cmd+Enter**

104* **Windows**: press **Ctrl+Enter**

105 

106Claude reads your comments and makes the requested changes, which appear as a new diff you can review.

107 

108### Review your code

109 

110In the diff view, click **Review code** in the top-right toolbar to ask Claude to evaluate the changes before you commit. Claude examines the current diffs and leaves comments directly in the diff view. You can respond to any comment or ask Claude to revise.

111 

112The review focuses on high-signal issues: compile errors, definite logic errors, security vulnerabilities, and obvious bugs. It does not flag style, formatting, pre-existing issues, or anything a linter would catch.

113 

114### Monitor pull request status

115 

116After you open a pull request, a CI status bar appears in the session. Claude Code uses the GitHub CLI to poll check results and surface failures.

117 

118* **Auto-fix**: when enabled, Claude automatically attempts to fix failing CI checks by reading the failure output and iterating.

119* **Auto-merge**: when enabled, Claude merges the PR once all checks pass. The merge method is squash. Auto-merge must be [enabled in your GitHub repository settings](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-auto-merge-for-pull-requests-in-your-repository) for this to work.

120 

121Use the **Auto-fix** and **Auto-merge** toggles in the CI status bar to enable either option. Claude Code also sends a desktop notification when CI finishes.

122 

123<Note>

124 PR monitoring requires the [GitHub CLI (`gh`)](https://cli.github.com/) to be installed and authenticated on your machine. If `gh` is not installed, Desktop prompts you to install it the first time you try to create a PR.

125</Note>

126 

127## Let Claude use your computer

128 

129Computer use lets Claude open your apps, control your screen, and work directly on your machine the way you would. Ask Claude to test a native app in a mobile simulator, interact with a desktop tool that has no CLI, or automate something that only works through a GUI.

130 

131<Note>

132 Computer use is a research preview on macOS and Windows that requires a Pro or Max plan. It is not available on Team or Enterprise plans. The Claude Desktop app must be running.

133</Note>

134 

135Computer use is off by default. [Enable it in Settings](#enable-computer-use) before Claude can control your screen. On macOS, you also need to grant Accessibility and Screen Recording permissions.

136 

137<Warning>

138 Unlike the [sandboxed Bash tool](/en/sandboxing), computer use runs on your actual desktop with access to whatever you approve. Claude checks each action and flags potential prompt injection from on-screen content, but the trust boundary is different. See the [computer use safety guide](https://support.claude.com/en/articles/14128542) for best practices.

139</Warning>

140 

141### When computer use applies

142 

143Claude has several ways to interact with an app or service, and computer use is the broadest and slowest. It tries the most precise tool first:

144 

145* If you have a [connector](#connect-external-tools) for a service, Claude uses the connector.

146* If the task is a shell command, Claude uses Bash.

147* If the task is browser work and you have [Claude in Chrome](/en/chrome) set up, Claude uses that.

148* If none of those apply, Claude uses computer use.

149 

150The [per-app access tiers](#app-permissions) reinforce this: browsers are capped at view-only, and terminals and IDEs at click-only, steering Claude toward the dedicated tool even when computer use is active. Screen control is reserved for things nothing else can reach, like native apps, hardware control panels, mobile simulators, or proprietary tools without an API.

151 

152### Enable computer use

153 

154Computer use is off by default. If you ask Claude to do something that needs it while it's off, Claude tells you it could do the task if you enable computer use in Settings.

155 

156<Steps>

157 <Step title="Update the desktop app">

158 Make sure you have the latest version of Claude Desktop. Download or update at [claude.com/download](https://claude.com/download), then restart the app.

159 </Step>

160 

161 <Step title="Turn on the toggle">

162 In the desktop app, go to **Settings > General** (under **Desktop app**). Find the **Computer use** toggle and turn it on. On Windows, the toggle takes effect immediately and setup is complete. On macOS, continue to the next step.

163 

164 If you don't see the toggle, confirm you're on macOS or Windows with a Pro or Max plan, then update and restart the app.

165 </Step>

166 

167 <Step title="Grant macOS permissions">

168 On macOS, grant two system permissions before the toggle takes effect:

169 

170 * **Accessibility**: lets Claude click, type, and scroll

171 * **Screen Recording**: lets Claude see what's on your screen

172 

173 The Settings page shows the current status of each permission. If either is denied, click the badge to open the relevant System Settings pane.

174 </Step>

175</Steps>

176 

177### App permissions

178 

179The first time Claude needs to use an app, a prompt appears in your session. Click **Allow for this session** or **Deny**. Approvals last for the current session, or 30 minutes in [Dispatch-spawned sessions](#sessions-from-dispatch).

180 

181The prompt also shows what level of control Claude gets for that app. These tiers are fixed by app category and can't be changed:

182 

183| Tier | What Claude can do | Applies to |

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

185| View only | See the app in screenshots | Browsers, trading platforms |

186| Click only | Click and scroll, but not type or use keyboard shortcuts | Terminals, IDEs |

187| Full control | Click, type, drag, and use keyboard shortcuts | Everything else |

188 

189Apps with broad reach, like terminals, Finder or File Explorer, and System Settings or Settings, show an extra warning in the prompt so you know what approving them grants.

190 

191You can configure two settings in **Settings > General** (under **Desktop app**):

192 

193* **Denied apps**: add apps here to reject them without prompting. Claude may still affect a denied app indirectly through actions in an allowed app, but it can't interact with the denied app directly.

194* **Unhide apps when Claude finishes**: while Claude is working, your other windows are hidden so it interacts with only the approved app. When Claude finishes, hidden windows are restored unless you turn this setting off.

195 

196## Manage sessions

197 

198Each session is an independent conversation with its own context and changes. You can run multiple sessions in parallel, send work to the cloud, or let Dispatch start sessions for you from your phone.

199 

200### Work in parallel with sessions

201 

202Click **+ New session** in the sidebar to work on multiple tasks in parallel. For Git repositories, each session gets its own isolated copy of your project using [Git worktrees](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees), so changes in one session don't affect other sessions until you commit them.

203 

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

205 

206To include gitignored files like `.env` in new worktrees, create a [`.worktreeinclude` file](/en/common-workflows#copy-gitignored-files-to-worktrees) in your project root.

207 

208<Note>

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

210</Note>

211 

212Use the filter icon at the top of the sidebar to filter sessions by status (Active, Archived) and environment (Local, Cloud). To rename a session or check context usage, click the session title in the toolbar at the top of the active session. When context fills up, Claude automatically summarizes the conversation and continues working. You can also type `/compact` to trigger summarization earlier and free up context space. See [the context window](/en/how-claude-code-works#the-context-window) for details on how compaction works.

213 

214### Run long-running tasks remotely

215 

216For large refactors, test suites, migrations, or other long-running tasks, select **Remote** instead of **Local** when starting a session. Remote sessions run on Anthropic's cloud infrastructure and continue even if you close the app or shut down your computer. Check back anytime to see progress or steer Claude in a different direction. You can also monitor remote sessions from [claude.ai/code](https://claude.ai/code) or the Claude iOS app.

217 

218Remote sessions also support multiple repositories. After selecting a cloud environment, click the **+** button next to the repo pill to add additional repositories to the session. Each repo gets its own branch selector. This is useful for tasks that span multiple codebases, such as updating a shared library and its consumers.

219 

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

221 

222### Continue in another surface

223 

224The **Continue in** menu, accessible from the VS Code icon in the bottom right of the session toolbar, lets you move your session to another surface:

225 

226* **Claude Code on the Web**: sends your local session to continue running remotely. Desktop pushes your branch, generates a summary of the conversation, and creates a new remote session with the full context. You can then choose to archive the local session or keep it. This requires a clean working tree, and is not available for SSH sessions.

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

228 

229### Sessions from Dispatch

230 

231[Dispatch](https://support.claude.com/en/articles/13947068) is a persistent conversation with Claude that lives in the [Cowork](https://claude.com/product/cowork#dispatch-and-computer-use) tab. You message Dispatch a task, and it decides how to handle it.

232 

233A task can end up as a Code session in two ways: you ask for one directly, such as "open a Claude Code session and fix the login bug", or Dispatch decides the task is development work and spawns one on its own. Tasks that typically route to Code include fixing bugs, updating dependencies, running tests, or opening pull requests. Research, document editing, and spreadsheet work stay in Cowork.

234 

235Either way, the Code session appears in the Code tab's sidebar with a **Dispatch** badge. You get a push notification on your phone when it finishes or needs your approval.

236 

237If you have [computer use](#let-claude-use-your-computer) enabled, Dispatch-spawned Code sessions can use it too. App approvals in those sessions expire after 30 minutes and re-prompt, rather than lasting the full session like regular Code sessions.

238 

239For setup, pairing, and Dispatch settings, see the [Dispatch help article](https://support.claude.com/en/articles/13947068). Dispatch requires a Pro or Max plan and is not available on Team or Enterprise plans.

240 

241Dispatch is one of several ways to work with Claude when you're away from your terminal. See [Platforms and integrations](/en/platforms#work-when-you-are-away-from-your-terminal) to compare it with Remote Control, Channels, Slack, and scheduled tasks.

242 

243## Extend Claude Code

244 

245Connect external services, add reusable workflows, customize Claude's behavior, and configure preview servers.

246 

247### Connect external tools

248 

249For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Connectors** to add integrations like Google Calendar, Slack, GitHub, Linear, Notion, and more. You can add connectors before or during a session. The **+** button is not available in remote sessions, but [scheduled tasks](/en/web-scheduled-tasks) configure connectors at task creation time.

250 

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

252 

253Once connected, Claude can read your calendar, send messages, create issues, and interact with your tools directly. You can ask Claude what connectors are configured in your session.

254 

255Connectors are [MCP servers](/en/mcp) with a graphical setup flow. Use them for quick integration with supported services. For integrations not listed in Connectors, add MCP servers manually via [settings files](/en/mcp#installing-mcp-servers). You can also [create custom connectors](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp).

256 

257### Use skills

258 

259[Skills](/en/skills) extend what Claude can do. Claude loads them automatically when relevant, or you can invoke one directly: type `/` in the prompt box or click the **+** button and select **Slash commands** to browse what's available. This includes [built-in commands](/en/commands), your [custom skills](/en/skills#create-your-first-skill), project skills from your codebase, and skills from any [installed plugins](/en/plugins). Select one and it appears highlighted in the input field. Type your task after it and send as usual.

260 

261### Install plugins

262 

263[Plugins](/en/plugins) are reusable packages that add skills, agents, hooks, MCP servers, and LSP configurations to Claude Code. You can install plugins from the desktop app without using the terminal.

264 

265For local and [SSH](#ssh-sessions) sessions, click the **+** button next to the prompt box and select **Plugins** to see your installed plugins and their commands. To add a plugin, select **Add plugin** from the submenu to open the plugin browser, which shows available plugins from your configured [marketplaces](/en/plugin-marketplaces) including the official Anthropic marketplace. Select **Manage plugins** to enable, disable, or uninstall plugins.

266 

267Plugins can be scoped to your user account, a specific project, or local-only. Plugins are not available for remote sessions. For the full plugin reference including creating your own plugins, see [plugins](/en/plugins).

268 

269### Configure preview servers

270 

271Claude automatically detects your dev server setup and stores the configuration in `.claude/launch.json` at the root of the folder you selected when starting the session. Preview uses this folder as its working directory, so if you selected a parent folder, subfolders with their own dev servers won't be detected automatically. To work with a subfolder's server, either start a session in that folder directly or add a configuration manually.

272 

273To customize how your server starts, for example to use `yarn dev` instead of `npm run dev` or to change the port, edit the file manually or click **Edit configuration** in the Preview dropdown to open it in your code editor. The file supports JSON with comments.

274 

275```json theme={null}

276{

277 "version": "0.0.1",

278 "configurations": [

279 {

280 "name": "my-app",

281 "runtimeExecutable": "npm",

282 "runtimeArgs": ["run", "dev"],

283 "port": 3000

284 }

285 ]

286}

287```

288 

289You can define multiple configurations to run different servers from the same project, such as a frontend and an API. See the [examples](#examples) below.

290 

291#### Auto-verify changes

292 

293When `autoVerify` is enabled, Claude automatically verifies code changes after editing files. It takes screenshots, checks for errors, and confirms changes work before completing its response.

294 

295Auto-verify is on by default. Disable it per-project by adding `"autoVerify": false` to `.claude/launch.json`, or toggle it from the **Preview** dropdown menu.

296 

297```json theme={null}

298{

299 "version": "0.0.1",

300 "autoVerify": false,

301 "configurations": [...]

302}

303```

304 

305When disabled, preview tools are still available and you can ask Claude to verify at any time. Auto-verify makes it automatic after every edit.

306 

307#### Configuration fields

308 

309Each entry in the `configurations` array accepts the following fields:

310 

311| Field | Type | Description |

312| ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

313| `name` | string | A unique identifier for this server |

314| `runtimeExecutable` | string | The command to run, such as `npm`, `yarn`, or `node` |

315| `runtimeArgs` | string\[] | Arguments passed to `runtimeExecutable`, such as `["run", "dev"]` |

316| `port` | number | The port your server listens on. Defaults to 3000 |

317| `cwd` | string | Working directory relative to your project root. Defaults to the project root. Use `${workspaceFolder}` to reference the project root explicitly |

318| `env` | object | Additional environment variables as key-value pairs, such as `{ "NODE_ENV": "development" }`. Don't put secrets here since this file is committed to your repo. Secrets set in your shell profile are inherited automatically. |

319| `autoPort` | boolean | How to handle port conflicts. See below |

320| `program` | string | A script to run with `node`. See [when to use `program` vs `runtimeExecutable`](#when-to-use-program-vs-runtimeexecutable) |

321| `args` | string\[] | Arguments passed to `program`. Only used when `program` is set |

322 

323##### When to use `program` vs `runtimeExecutable`

324 

325Use `runtimeExecutable` with `runtimeArgs` to start a dev server through a package manager. For example, `"runtimeExecutable": "npm"` with `"runtimeArgs": ["run", "dev"]` runs `npm run dev`.

326 

327Use `program` when you have a standalone script you want to run with `node` directly. For example, `"program": "server.js"` runs `node server.js`. Pass additional flags with `args`.

328 

329#### Port conflicts

330 

331The `autoPort` field controls what happens when your preferred port is already in use:

332 

333* **`true`**: Claude finds and uses a free port automatically. Suitable for most dev servers.

334* **`false`**: Claude fails with an error. Use this when your server must use a specific port, such as for OAuth callbacks or CORS allowlists.

335* **Not set (default)**: Claude asks whether the server needs that exact port, then saves your answer.

336 

337When Claude picks a different port, it passes the assigned port to your server via the `PORT` environment variable.

338 

339#### Examples

340 

341These configurations show common setups for different project types:

342 

343<Tabs>

344 <Tab title="Next.js">

345 This configuration runs a Next.js app using Yarn on port 3000:

346 

347 ```json theme={null}

348 {

349 "version": "0.0.1",

350 "configurations": [

351 {

352 "name": "web",

353 "runtimeExecutable": "yarn",

354 "runtimeArgs": ["dev"],

355 "port": 3000

356 }

357 ]

358 }

359 ```

360 </Tab>

361 

362 <Tab title="Multiple servers">

363 For a monorepo with a frontend and an API server, define multiple configurations. The frontend uses `autoPort: true` so it picks a free port if 3000 is taken, while the API server requires port 8080 exactly:

364 

365 ```json theme={null}

366 {

367 "version": "0.0.1",

368 "configurations": [

369 {

370 "name": "frontend",

371 "runtimeExecutable": "npm",

372 "runtimeArgs": ["run", "dev"],

373 "cwd": "apps/web",

374 "port": 3000,

375 "autoPort": true

376 },

377 {

378 "name": "api",

379 "runtimeExecutable": "npm",

380 "runtimeArgs": ["run", "start"],

381 "cwd": "server",

382 "port": 8080,

383 "env": { "NODE_ENV": "development" },

384 "autoPort": false

385 }

386 ]

387 }

388 ```

389 </Tab>

390 

391 <Tab title="Node.js script">

392 To run a Node.js script directly instead of using a package manager command, use the `program` field:

393 

394 ```json theme={null}

395 {

396 "version": "0.0.1",

397 "configurations": [

398 {

399 "name": "server",

400 "program": "server.js",

401 "args": ["--verbose"],

402 "port": 4000

403 }

404 ]

405 }

406 ```

407 </Tab>

408</Tabs>

409 

410## Environment configuration

411 

412The environment you pick when [starting a session](#start-a-session) determines where Claude executes and how you connect:

413 

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

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

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

417 

418### Local sessions

419 

420Local sessions inherit environment variables from your shell. If you need additional variables, set them in your shell profile, such as `~/.zshrc` or `~/.bashrc`, and restart the desktop app. See [environment variables](/en/env-vars) for the full list of supported variables.

421 

422[Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) is enabled by default, which improves performance on complex reasoning tasks but uses additional tokens. To disable thinking entirely, set `MAX_THINKING_TOKENS=0` in your shell profile. On Opus, `MAX_THINKING_TOKENS` is ignored except for `0` because adaptive reasoning controls thinking depth instead.

423 

424### Remote sessions

425 

426Remote sessions continue in the background even if you close the app. Usage counts toward your [subscription plan limits](/en/costs) with no separate compute charges.

427 

428You can create custom cloud environments with different network access levels and environment variables. Select the environment dropdown when starting a remote session and choose **Add environment**. See [cloud environments](/en/claude-code-on-the-web#cloud-environment) for details on configuring network access and environment variables.

429 

430### SSH sessions

431 

432SSH sessions let you run Claude Code on a remote machine while using the desktop app as your interface. This is useful for working with codebases that live on cloud VMs, dev containers, or servers with specific hardware or dependencies.

433 

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

435 

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

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

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

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

440 

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

442 

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

444 

445## Enterprise configuration

446 

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

448 

449### Admin console controls

450 

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

452 

453* **Code in the desktop**: control whether users in your organization can access Claude Code in the desktop app

454* **Code in the web**: enable or disable [web sessions](/en/claude-code-on-the-web) for your organization

455* **Remote Control**: enable or disable [Remote Control](/en/remote-control) for your organization

456* **Disable Bypass permissions mode**: prevent users in your organization from enabling bypass permissions mode

457 

458### Managed settings

459 

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

461 

462| Key | Description |

463| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

464| `permissions.disableBypassPermissionsMode` | set to `"disable"` to prevent users from enabling Bypass permissions mode. |

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

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

467 

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

469 

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

471 

472### Device management policies

473 

474IT teams can manage the desktop app through MDM on macOS or group policy on Windows. Available policies include enabling or disabling the Claude Code feature, controlling auto-updates, and setting a custom deployment URL.

475 

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

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

478 

479### Authentication and SSO

480 

481Enterprise organizations can require SSO for all users. See [authentication](/en/authentication) for plan-level details and [Setting up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso) for SAML and OIDC configuration.

482 

483### Data handling

484 

485Claude Code processes your code locally in local sessions or on Anthropic's cloud infrastructure in remote sessions. Conversations and code context are sent to Anthropic's API for processing. See [data handling](/en/data-usage) for details on data retention, privacy, and compliance.

486 

487### Deployment

488 

489Desktop can be distributed through enterprise deployment tools:

490 

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

492* **Windows**: deploy via MSIX package or `.exe` installer. See [Deploy Claude Desktop for Windows](https://support.claude.com/en/articles/12622703-deploy-claude-desktop-for-windows) for enterprise deployment options including silent installation

493 

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

495 

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

497 

498## Coming from the CLI?

499 

500If you already use the Claude Code CLI, Desktop runs the same underlying engine with a graphical interface. You can run both simultaneously on the same machine, even on the same project. Each maintains separate session history, but they share configuration and project memory via CLAUDE.md files.

501 

502To move a CLI session into Desktop, run `/desktop` in the terminal. Claude saves your session and opens it in the desktop app, then exits the CLI. This command is available on macOS and Windows only.

503 

504<Tip>

505 When to use Desktop vs CLI: use Desktop when you want visual diff review, file attachments, or session management in a sidebar. Use the CLI when you need scripting, automation, third-party providers, or prefer a terminal workflow.

506</Tip>

507 

508### CLI flag equivalents

509 

510This table shows the desktop app equivalent for common CLI flags. Flags not listed have no desktop equivalent because they are designed for scripting or automation.

511 

512| CLI | Desktop equivalent |

513| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |

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

515| `--resume`, `--continue` | Click a session in the sidebar |

516| `--permission-mode` | Mode selector next to the send button |

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

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

519| `--allowedTools`, `--disallowedTools` | Not available in Desktop |

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

521| `--print`, `--output-format` | Not available. Desktop is interactive only. |

522| `ANTHROPIC_MODEL` env var | Model dropdown next to the send button |

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

524 

525### Shared configuration

526 

527Desktop and CLI read the same configuration files, so your setup carries over:

528 

529* **[CLAUDE.md](/en/memory)** and `CLAUDE.local.md` files in your project are used by both

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

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

532* **[Settings](/en/settings)** in `~/.claude.json` and `~/.claude/settings.json` are shared. Permission rules, allowed tools, and other settings in `settings.json` apply to Desktop sessions.

533* **Models**: Sonnet, Opus, and Haiku are available in both. In Desktop, select the model from the dropdown next to the send button before starting a session. You cannot change the model during an active session.

534 

535<Note>

536 **MCP servers: desktop chat app vs Claude Code**: MCP servers configured for the Claude Desktop chat app in `claude_desktop_config.json` are separate from Claude Code and will not appear in the Code tab. To use MCP servers in Claude Code, configure them in `~/.claude.json` or your project's `.mcp.json` file. See [MCP configuration](/en/mcp#installing-mcp-servers) for details.

537</Note>

538 

539### Feature comparison

540 

541This table compares core capabilities between the CLI and Desktop. For a full list of CLI flags, see the [CLI reference](/en/cli-reference).

542 

543| Feature | CLI | Desktop |

544| ----------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------- |

545| Permission modes | All modes including `dontAsk` | Ask permissions, Auto accept edits, Plan mode, Auto, and Bypass permissions via Settings |

546| `--dangerously-skip-permissions` | CLI flag | Bypass permissions mode. Enable in Settings → Claude Code → "Allow bypass permissions mode" |

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

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

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

550| @mention files | Text-based | With autocomplete; local and SSH sessions only |

551| File attachments | Not available | Images, PDFs |

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

553| Multiple sessions | Separate terminals | Sidebar tabs |

554| Recurring tasks | Cron jobs, CI pipelines | [Scheduled tasks](/en/desktop-scheduled-tasks) |

555| Computer use | [Enable via `/mcp`](/en/computer-use) on macOS | [App and screen control](#let-claude-use-your-computer) on macOS and Windows |

556| Dispatch integration | Not available | [Dispatch sessions](#sessions-from-dispatch) in the sidebar |

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

558 

559### What's not available in Desktop

560 

561The following features are only available in the CLI or VS Code extension:

562 

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

564* **Linux**: the desktop app is available on macOS and Windows only.

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

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

567 

568## Troubleshooting

569 

570### Check your version

571 

572To see which version of the desktop app you're running:

573 

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

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

576 

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

578 

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

580 

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

582 

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

5842. Verify you have an active paid subscription: Pro, Max, Team, or Enterprise.

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

5864. Check your internet connection and proxy settings.

587 

588### Blank or stuck screen on launch

589 

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

591 

5921. Restart the app.

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

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

595 

596### "Failed to load session"

597 

598If you see `Failed to load session`, the selected folder may no longer exist, a Git repository may require Git LFS that isn't installed, or file permissions may prevent access. Try selecting a different folder or restarting the app.

599 

600### Session not finding installed tools

601 

602If Claude can't find tools like `npm`, `node`, or other CLI commands, verify the tools work in your regular terminal, check that your shell profile properly sets up PATH, and restart the desktop app to reload environment variables.

603 

604### Git and Git LFS errors

605 

606On Windows, Git is required for the Code tab to start local sessions. If you see "Git is required," install [Git for Windows](https://git-scm.com/downloads/win) and restart the app.

607 

608If you see "Git LFS is required by this repository but is not installed," install Git LFS from [git-lfs.com](https://git-lfs.com/), run `git lfs install`, and restart the app.

609 

610### MCP servers not working on Windows

611 

612If MCP server toggles don't respond or servers fail to connect on Windows, check that the server is properly configured in your settings, restart the app, verify the server process is running in Task Manager, and review server logs for connection errors.

613 

614### App won't quit

615 

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

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

618 

619### Windows-specific issues

620 

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

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

623* **ARM64**: Windows ARM64 devices are fully supported.

624 

625### Cowork tab unavailable on Intel Macs

626 

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

628 

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

630 

631Remote sessions can create branches that don't exist on your local machine. Click the branch name in the session toolbar to copy it, then fetch it locally:

632 

633```bash theme={null}

634git fetch origin <branch-name>

635git checkout <branch-name>

636```

637 

638### Still stuck?

639 

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

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

642 

643When filing a bug, include your desktop app version, your operating system, the exact error message, and relevant logs. On macOS, check Console.app. On Windows, check Event Viewer → Windows Logs → Application.

desktop-quickstart.md +135 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Get started with the desktop app

6 

7> Install Claude Code on desktop and start your first coding session

8 

9The desktop app gives you Claude Code with a graphical interface: visual diff review, live app preview, GitHub PR monitoring with auto-merge, parallel sessions with Git worktree isolation, scheduled tasks, and the ability to run tasks remotely. No terminal required.

10 

11Download Claude for your platform:

12 

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

15 Universal build for Intel and Apple Silicon

16 </Card>

17 

18 <Card title="Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code&utm_medium=docs">

19 For x64 processors

20 </Card>

21</CardGroup>

22 

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.

24 

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

27</Note>

28 

29This page walks through installing the app and starting your first session. If you're already set up, see [Use Claude Code Desktop](/en/desktop) for the full reference.

30 

31The desktop app has three tabs:

32 

33* **Chat**: General conversation with no file access, similar to claude.ai.

34* **Cowork**: An autonomous background agent that works on tasks in a cloud VM with its own environment. It can run independently while you do other work.

35* **Code**: An interactive coding assistant with direct access to your local files. You review and approve each change in real time.

36 

37Chat and Cowork are covered in the [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop). This page focuses on the **Code** tab.

38 

39## Install

40 

41<Steps>

42 <Step title="Install and sign in">

43 Download Claude for your platform and run the installer:

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>

51 

52 <Step title="Open the Code tab">

53 Click the **Code** tab at the top center. If clicking Code prompts you to upgrade, you need to [subscribe to a paid plan](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=desktop_quickstart_upgrade) first. If it prompts you to sign in online, complete the sign-in and restart the app. If you see a 403 error, see [authentication troubleshooting](/en/desktop#403-or-authentication-errors-in-the-code-tab).

54 </Step>

55</Steps>

56 

57The desktop app includes Claude Code. You don't need to install Node.js or the CLI separately. To use `claude` from the terminal, install the CLI separately. See [Get started with the CLI](/en/quickstart).

58 

59## Start your first session

60 

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

62 

63<Steps>

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

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

66 

67 <Tip>

68 Start with a small project you know well. It's the fastest way to see what Claude Code can do. On Windows, [Git](https://git-scm.com/downloads/win) must be installed for local sessions to work. Most Macs include Git by default.

69 </Tip>

70 

71 You can also select:

72 

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

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.

75 </Step>

76 

77 <Step title="Choose a model">

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

79 </Step>

80 

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

82 Type what you want Claude to do:

83 

84 * `Find a TODO comment and fix it`

85 * `Add tests for the main function`

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

87 

88 A [session](/en/desktop#work-in-parallel-with-sessions) is a conversation with Claude about your code. Each session tracks its own context and changes, so you can work on multiple tasks without them interfering with each other.

89 </Step>

90 

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

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

93 

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

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

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

97 

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

99 </Step>

100</Steps>

101 

102## Now what?

103 

104You've made your first edit. For the full reference on everything Desktop can do, see [Use Claude Code Desktop](/en/desktop). Here are some things to try next.

105 

106**Interrupt and steer.** You can interrupt Claude at any point. If it's going down the wrong path, click the stop button or type your correction and press **Enter**. Claude stops what it's doing and adjusts based on your input. You don't have to wait for it to finish or start over.

107 

108**Give Claude more context.** Type `@filename` in the prompt box to pull a specific file into the conversation, attach images and PDFs using the attachment button, or drag and drop files directly into the prompt. The more context Claude has, the better the results. See [Add files and context](/en/desktop#add-files-and-context-to-prompts).

109 

110**Use skills for repeatable tasks.** Type `/` or click **+** → **Slash commands** to browse [built-in commands](/en/commands), [custom skills](/en/skills), and plugin skills. Skills are reusable prompts you can invoke whenever you need them, like code review checklists or deployment steps.

111 

112**Review changes before committing.** After Claude edits files, a `+12 -1` indicator appears. Click it to open the [diff view](/en/desktop#review-changes-with-diff-view), review modifications file by file, and comment on specific lines. Claude reads your comments and revises. Click **Review code** to have Claude evaluate the diffs itself and leave inline suggestions.

113 

114**Adjust how much control you have.** Your [permission mode](/en/desktop#choose-a-permission-mode) controls the balance. Ask permissions (default) requires approval before every edit. Auto accept edits auto-accepts file edits for faster iteration. Plan mode lets Claude map out an approach without touching any files, which is useful before a large refactor.

115 

116**Add plugins for more capabilities.** Click the **+** button next to the prompt box and select **Plugins** to browse and install [plugins](/en/desktop#install-plugins) that add skills, agents, MCP servers, and more.

117 

118**Preview your app.** Click the **Preview** dropdown to run your dev server directly in the desktop. Claude can view the running app, test endpoints, inspect logs, and iterate on what it sees. See [Preview your app](/en/desktop#preview-your-app).

119 

120**Track your pull request.** After opening a PR, Claude Code monitors CI check results and can automatically fix failures or merge the PR once all checks pass. See [Monitor pull request status](/en/desktop#monitor-pull-request-status).

121 

122**Put Claude on a schedule.** Set up [scheduled tasks](/en/desktop-scheduled-tasks) to run Claude automatically on a recurring basis: a daily code review every morning, a weekly dependency audit, or a briefing that pulls from your connected tools.

123 

124**Scale up when you're ready.** Open [parallel sessions](/en/desktop#work-in-parallel-with-sessions) from the sidebar to work on multiple tasks at once, each in its own Git worktree. Send [long-running work to the cloud](/en/desktop#run-long-running-tasks-remotely) so it continues even if you close the app, or [continue a session on the web or in your IDE](/en/desktop#continue-in-another-surface) if a task takes longer than expected. [Connect external tools](/en/desktop#extend-claude-code) like GitHub, Slack, and Linear to bring your workflow together.

125 

126## Coming from the CLI?

127 

128Desktop runs the same engine as the CLI with a graphical interface. You can run both simultaneously on the same project, and they share configuration (CLAUDE.md files, MCP servers, hooks, skills, and settings). For a full comparison of features, flag equivalents, and what's not available in Desktop, see [CLI comparison](/en/desktop#coming-from-the-cli).

129 

130## What's next

131 

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

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

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

135* [Common workflows](/en/common-workflows): tutorials for debugging, refactoring, testing, and more

desktop-scheduled-tasks.md +109 −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# Schedule recurring tasks in Claude Code Desktop

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.

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.

10 

11## Compare scheduling options

12 

13Claude Code offers three ways to schedule recurring work:

14 

15| | [Cloud](/en/web-scheduled-tasks) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |

16| :------------------------- | :------------------------------- | :------------------------------------- | :----------------------------- |

17| Runs on | Anthropic cloud | Your machine | Your machine |

18| Requires machine on | No | Yes | Yes |

19| Requires open session | No | No | Yes |

20| Persistent across restarts | Yes | Yes | No (session-scoped) |

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

23| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |

24| Customizable schedule | Via `/schedule` in the CLI | Yes | Yes |

25| Minimum interval | 1 hour | 1 minute | 1 minute |

26 

27<Tip>

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.

29</Tip>

30 

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 [Cloud scheduled tasks](/en/web-scheduled-tasks).

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>

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.

42</Note>

43 

44## Create a scheduled task

45 

46To create a local scheduled task, click **Schedule** in the sidebar, click **New task**, and choose **New local task**. Configure these fields:

47 

48| Field | Description |

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

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

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

53| Frequency | How often the task runs. See [frequency options](#frequency-options) below. |

54 

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

56 

57## Frequency options

58 

59Pick a preset from the frequency dropdown, or ask Claude for anything the picker doesn't cover:

60 

61* **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 traffic

63* **Daily**: shows a time picker, defaults to 9:00 AM local time

64* **Weekdays**: same as Daily but skips Saturday and Sunday

65* **Weekly**: shows a time picker and a day picker

66 

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

68 

69## How scheduled tasks run

70 

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.

72 

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.

74 

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, use a [remote task](/en/web-scheduled-tasks) instead.

76 

77## Missed runs

78 

79When the app starts or your computer wakes, Desktop checks whether each task missed any runs in the last seven days. If it did, Desktop starts exactly one catch-up run for the most recently missed time and discards anything older. A daily task that missed six days runs once on wake. Desktop shows a notification when a catch-up run starts.

80 

81Keep this in mind when writing prompts. A task scheduled for 9am might run at 11pm if your computer was asleep all day. If timing matters, add guardrails to the prompt itself, for example: "Only review today's commits. If it's after 5pm, skip the review and just post a summary of what was missed."

82 

83## Permissions for scheduled tasks

84 

85Each task has its own permission mode, which you set when creating or editing the task. Allow rules from `~/.claude/settings.json` also apply to scheduled task sessions. If a task runs in Ask mode and needs to run a tool it doesn't have permission for, the run stalls until you approve it. The session stays open in the sidebar so you can answer later.

86 

87To avoid stalls, click **Run now** after creating a task, watch for permission prompts, and select "always allow" for each one. Future runs of that task auto-approve the same tools without prompting. You can review and revoke these approvals from the task's detail page.

88 

89## Manage scheduled tasks

90 

91Click a task in the **Schedule** list to open its detail page. From here you can:

92 

93* **Run now**: start the task immediately without waiting for the next scheduled time

94* **Toggle repeats**: pause or resume scheduled runs without deleting the task

95* **Edit**: change the prompt, frequency, folder, or other settings

96* **Review history**: see every past run, including ones that were skipped because your computer was asleep

97* **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 created

99 

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

101 

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.

103 

104## Related resources

105 

106* [Cloud scheduled tasks](/en/web-scheduled-tasks): schedule tasks that run on Anthropic-managed infrastructure even when your computer is off

107* [Run prompts on a schedule](/en/scheduled-tasks): session-scoped scheduling with `/loop` in the CLI

108* [Claude Code GitHub Actions](/en/github-actions): run Claude on a schedule in CI instead of on your machine

109* [Use Claude Code Desktop](/en/desktop): the full Desktop app guide

devcontainer.md +9 −5

Details

1> ## Documentation Index

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

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

4 

1# Development containers5# Development containers

2 6 

3> Learn about the Claude Code development container for teams that need consistent, secure environments.7> Learn about the Claude Code development container for teams that need consistent, secure environments.


8 12 

9<Warning>13<Warning>

10 While the devcontainer provides substantial protections, no system is completely immune to all attacks.14 While the devcontainer provides substantial protections, no system is completely immune to all attacks.

11 When executed with `--dangerously-skip-permissions`, devcontainers do not prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials.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.

12 We recommend only using devcontainers when developing with trusted repositories.16 We recommend only using devcontainers when developing with trusted repositories.

13 Always maintain good security practices and monitor Claude's activities.17 Always maintain good security practices and monitor Claude's activities.

14</Warning>18</Warning>


24 28 

25## Getting started in 4 steps29## Getting started in 4 steps

26 30 

271. Install VS Code and the Remote - Containers extension311. Install VS Code and the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers)

282. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository322. Clone the [Claude Code reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer) repository

293. Open the repository in VS Code333. Open the repository in VS Code

304. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Remote-Containers: Reopen in Container")344. When prompted, click "Reopen in Container" (or use Command Palette: Cmd+Shift+P → "Dev Containers: Reopen in Container")

31 35 

32## Configuration breakdown36## Configuration breakdown

33 37 


73## Related resources77## Related resources

74 78 

75* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)79* [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)

76* [Claude Code security best practices](/en/docs/claude-code/security)80* [Claude Code security best practices](/en/security)

77* [Enterprise network configuration](/en/docs/claude-code/network-config)81* [Enterprise network configuration](/en/network-config)

discover-plugins.md +427 −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# Discover and install prebuilt plugins through marketplaces

6 

7> Find and install plugins from marketplaces to extend Claude Code with new commands, agents, and capabilities.

8 

9Plugins extend Claude Code with skills, agents, hooks, and MCP servers. Plugin marketplaces are catalogs that help you discover and install these extensions without building them yourself.

10 

11Looking to create and distribute your own marketplace? See [Create and distribute a plugin marketplace](/en/plugin-marketplaces).

12 

13## How marketplaces work

14 

15A marketplace is a catalog of plugins that someone else has created and shared. Using a marketplace is a two-step process:

16 

17<Steps>

18 <Step title="Add the marketplace">

19 This registers the catalog with Claude Code so you can browse what's available. No plugins are installed yet.

20 </Step>

21 

22 <Step title="Install individual plugins">

23 Browse the catalog and install the plugins you want.

24 </Step>

25</Steps>

26 

27Think of it like adding an app store: adding the store gives you access to browse its collection, but you still choose which apps to download individually.

28 

29## Official Anthropic marketplace

30 

31The official Anthropic marketplace (`claude-plugins-official`) is automatically available when you start Claude Code. Run `/plugin` and go to the **Discover** tab to browse what's available, or view the catalog at [claude.com/plugins](https://claude.com/plugins).

32 

33To install a plugin from the official marketplace, use `/plugin install <name>@claude-plugins-official`. For example, to install the GitHub integration:

34 

35```shell theme={null}

36/plugin install github@claude-plugins-official

37```

38 

39<Note>

40 The official marketplace is maintained by Anthropic. To submit a plugin to the official marketplace, use one of the in-app submission forms:

41 

42 * **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

43 * **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

44 

45 To distribute plugins independently, [create your own marketplace](/en/plugin-marketplaces) and share it with users.

46</Note>

47 

48The official marketplace includes several categories of plugins:

49 

50### Code intelligence

51 

52Code intelligence plugins enable Claude Code's built-in LSP tool, giving Claude the ability to jump to definitions, find references, and see type errors immediately after edits. These plugins configure [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) connections, the same technology that powers VS Code's code intelligence.

53 

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

55 

56| Language | Plugin | Binary required |

57| :--------- | :------------------ | :--------------------------- |

58| C/C++ | `clangd-lsp` | `clangd` |

59| C# | `csharp-lsp` | `csharp-ls` |

60| Go | `gopls-lsp` | `gopls` |

61| Java | `jdtls-lsp` | `jdtls` |

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

63| Lua | `lua-lsp` | `lua-language-server` |

64| PHP | `php-lsp` | `intelephense` |

65| Python | `pyright-lsp` | `pyright-langserver` |

66| Rust | `rust-analyzer-lsp` | `rust-analyzer` |

67| Swift | `swift-lsp` | `sourcekit-lsp` |

68| TypeScript | `typescript-lsp` | `typescript-language-server` |

69 

70You can also [create your own LSP plugin](/en/plugins-reference#lsp-servers) for other languages.

71 

72<Note>

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

74</Note>

75 

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

77 

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

79 

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

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

82 

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

84 

85### External integrations

86 

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

88 

89* **Source control**: `github`, `gitlab`

90* **Project management**: `atlassian` (Jira/Confluence), `asana`, `linear`, `notion`

91* **Design**: `figma`

92* **Infrastructure**: `vercel`, `firebase`, `supabase`

93* **Communication**: `slack`

94* **Monitoring**: `sentry`

95 

96### Development workflows

97 

98Plugins that add commands and agents for common development tasks:

99 

100* **commit-commands**: Git commit workflows including commit, push, and PR creation

101* **pr-review-toolkit**: Specialized agents for reviewing pull requests

102* **agent-sdk-dev**: Tools for building with the Claude Agent SDK

103* **plugin-dev**: Toolkit for creating your own plugins

104 

105### Output styles

106 

107Customize how Claude responds:

108 

109* **explanatory-output-style**: Educational insights about implementation choices

110* **learning-output-style**: Interactive learning mode for skill building

111 

112## Try it: add the demo marketplace

113 

114Anthropic also maintains a [demo plugins marketplace](https://github.com/anthropics/claude-code/tree/main/plugins) (`claude-code-plugins`) with example plugins that show what's possible with the plugin system. Unlike the official marketplace, you need to add this one manually.

115 

116<Steps>

117 <Step title="Add the marketplace">

118 From within Claude Code, run the `plugin marketplace add` command for the `anthropics/claude-code` marketplace:

119 

120 ```shell theme={null}

121 /plugin marketplace add anthropics/claude-code

122 ```

123 

124 This downloads the marketplace catalog and makes its plugins available to you.

125 </Step>

126 

127 <Step title="Browse available plugins">

128 Run `/plugin` to open the plugin manager. This opens a tabbed interface with four tabs you can cycle through using **Tab** (or **Shift+Tab** to go backward):

129 

130 * **Discover**: browse available plugins from all your marketplaces

131 * **Installed**: view and manage your installed plugins

132 * **Marketplaces**: add, remove, or update your added marketplaces

133 * **Errors**: view any plugin loading errors

134 

135 Go to the **Discover** tab to see plugins from the marketplace you just added.

136 </Step>

137 

138 <Step title="Install a plugin">

139 Select a plugin to view its details, then choose an installation scope:

140 

141 * **User scope**: install for yourself across all projects

142 * **Project scope**: install for all collaborators on this repository

143 * **Local scope**: install for yourself in this repository only

144 

145 For example, select **commit-commands** (a plugin that adds git workflow commands) and install it to your user scope.

146 

147 You can also install directly from the command line:

148 

149 ```shell theme={null}

150 /plugin install commit-commands@anthropics-claude-code

151 ```

152 

153 See [Configuration scopes](/en/settings#configuration-scopes) to learn more about scopes.

154 </Step>

155 

156 <Step title="Use your new plugin">

157 After installing, run `/reload-plugins` to activate the plugin. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`.

158 

159 Try it out by making a change to a file and running:

160 

161 ```shell theme={null}

162 /commit-commands:commit

163 ```

164 

165 This stages your changes, generates a commit message, and creates the commit.

166 

167 Each plugin works differently. Check the plugin's description in the **Discover** tab or its homepage to learn what commands and capabilities it provides.

168 </Step>

169</Steps>

170 

171The rest of this guide covers all the ways you can add marketplaces, install plugins, and manage your configuration.

172 

173## Add marketplaces

174 

175Use the `/plugin marketplace add` command to add marketplaces from different sources.

176 

177<Tip>

178 **Shortcuts**: You can use `/plugin market` instead of `/plugin marketplace`, and `rm` instead of `remove`.

179</Tip>

180 

181* **GitHub repositories**: `owner/repo` format (for example, `anthropics/claude-code`)

182* **Git URLs**: any git repository URL (GitLab, Bitbucket, self-hosted)

183* **Local paths**: directories or direct paths to `marketplace.json` files

184* **Remote URLs**: direct URLs to hosted `marketplace.json` files

185 

186### Add from GitHub

187 

188Add a GitHub repository that contains a `.claude-plugin/marketplace.json` file using the `owner/repo` format—where `owner` is the GitHub username or organization and `repo` is the repository name.

189 

190For example, `anthropics/claude-code` refers to the `claude-code` repository owned by `anthropics`:

191 

192```shell theme={null}

193/plugin marketplace add anthropics/claude-code

194```

195 

196### Add from other Git hosts

197 

198Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers:

199 

200Using HTTPS:

201 

202```shell theme={null}

203/plugin marketplace add https://gitlab.com/company/plugins.git

204```

205 

206Using SSH:

207 

208```shell theme={null}

209/plugin marketplace add git@gitlab.com:company/plugins.git

210```

211 

212To add a specific branch or tag, append `#` followed by the ref:

213 

214```shell theme={null}

215/plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0

216```

217 

218### Add from local paths

219 

220Add a local directory that contains a `.claude-plugin/marketplace.json` file:

221 

222```shell theme={null}

223/plugin marketplace add ./my-marketplace

224```

225 

226You can also add a direct path to a `marketplace.json` file:

227 

228```shell theme={null}

229/plugin marketplace add ./path/to/marketplace.json

230```

231 

232### Add from remote URLs

233 

234Add a remote `marketplace.json` file via URL:

235 

236```shell theme={null}

237/plugin marketplace add https://example.com/marketplace.json

238```

239 

240<Note>

241 URL-based marketplaces have some limitations compared to Git-based marketplaces. If you encounter "path not found" errors when installing plugins, see [Troubleshooting](/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces).

242</Note>

243 

244## Install plugins

245 

246Once you've added marketplaces, you can install plugins directly (installs to user scope by default):

247 

248```shell theme={null}

249/plugin install plugin-name@marketplace-name

250```

251 

252To choose a different [installation scope](/en/settings#configuration-scopes), use the interactive UI: run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin. You'll see options for:

253 

254* **User scope** (default): install for yourself across all projects

255* **Project scope**: install for all collaborators on this repository (adds to `.claude/settings.json`)

256* **Local scope**: install for yourself in this repository only (not shared with collaborators)

257 

258You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/en/settings#settings-files) and cannot be modified.

259 

260Run `/plugin` and go to the **Installed** tab to see your plugins grouped by scope.

261 

262<Warning>

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.

264</Warning>

265 

266## Manage installed plugins

267 

268Run `/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.

269 

270You can also manage plugins with direct commands.

271 

272Disable a plugin without uninstalling:

273 

274```shell theme={null}

275/plugin disable plugin-name@marketplace-name

276```

277 

278Re-enable a disabled plugin:

279 

280```shell theme={null}

281/plugin enable plugin-name@marketplace-name

282```

283 

284Completely remove a plugin:

285 

286```shell theme={null}

287/plugin uninstall plugin-name@marketplace-name

288```

289 

290The `--scope` option lets you target a specific scope with CLI commands:

291 

292```shell theme={null}

293claude plugin install formatter@your-org --scope project

294claude plugin uninstall formatter@your-org --scope project

295```

296 

297### Apply plugin changes without restarting

298 

299When you install, enable, or disable plugins during a session, run `/reload-plugins` to pick up all changes without restarting:

300 

301```shell theme={null}

302/reload-plugins

303```

304 

305Claude Code reloads all active plugins and shows counts for plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers.

306 

307## Manage marketplaces

308 

309You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.

310 

311### Use the interactive interface

312 

313Run `/plugin` and go to the **Marketplaces** tab to:

314 

315* View all your added marketplaces with their sources and status

316* Add new marketplaces

317* Update marketplace listings to fetch the latest plugins

318* Remove marketplaces you no longer need

319 

320### Use CLI commands

321 

322You can also manage marketplaces with direct commands.

323 

324List all configured marketplaces:

325 

326```shell theme={null}

327/plugin marketplace list

328```

329 

330Refresh plugin listings from a marketplace:

331 

332```shell theme={null}

333/plugin marketplace update marketplace-name

334```

335 

336Remove a marketplace:

337 

338```shell theme={null}

339/plugin marketplace remove marketplace-name

340```

341 

342<Warning>

343 Removing a marketplace will uninstall any plugins you installed from it.

344</Warning>

345 

346### Configure auto-updates

347 

348Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you'll see a notification prompting you to run `/reload-plugins`.

349 

350Toggle auto-update for individual marketplaces through the UI:

351 

3521. Run `/plugin` to open the plugin manager

3532. Select **Marketplaces**

3543. Choose a marketplace from the list

3554. Select **Enable auto-update** or **Disable auto-update**

356 

357Official Anthropic marketplaces have auto-update enabled by default. Third-party and local development marketplaces have auto-update disabled by default.

358 

359To disable all automatic updates entirely for both Claude Code and all plugins, set the `DISABLE_AUTOUPDATER` environment variable. See [Auto updates](/en/setup#auto-updates) for details.

360 

361To keep plugin auto-updates enabled while disabling Claude Code auto-updates, set `FORCE_AUTOUPDATE_PLUGINS=1` along with `DISABLE_AUTOUPDATER`:

362 

363```bash theme={null}

364export DISABLE_AUTOUPDATER=1

365export FORCE_AUTOUPDATE_PLUGINS=1

366```

367 

368This is useful when you want to manage Claude Code updates manually but still receive automatic plugin updates.

369 

370## Configure team marketplaces

371 

372Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins.

373 

374Add `extraKnownMarketplaces` to your project's `.claude/settings.json`:

375 

376```json theme={null}

377{

378 "extraKnownMarketplaces": {

379 "my-team-tools": {

380 "source": {

381 "source": "github",

382 "repo": "your-org/claude-plugins"

383 }

384 }

385 }

386}

387```

388 

389For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/en/settings#plugin-settings).

390 

391## Security

392 

393Plugins and marketplaces are highly trusted components that can execute arbitrary code on your machine with your user privileges. Only install plugins and add marketplaces from sources you trust. Organizations can restrict which marketplaces users are allowed to add using [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).

394 

395## Troubleshooting

396 

397### /plugin command not recognized

398 

399If you see "unknown command" or the `/plugin` command doesn't appear:

400 

4011. **Check your version**: Run `claude --version` to see what's installed.

4022. **Update Claude Code**:

403 * **Homebrew**: `brew upgrade claude-code`

404 * **npm**: `npm update -g @anthropic-ai/claude-code`

405 * **Native installer**: Re-run the install command from [Setup](/en/setup)

4063. **Restart Claude Code**: After updating, restart your terminal and run `claude` again.

407 

408### Common issues

409 

410* **Marketplace not loading**: Verify the URL is accessible and that `.claude-plugin/marketplace.json` exists at the path

411* **Plugin installation failures**: Check that plugin source URLs are accessible and repositories are public (or you have access)

412* **Files not found after installation**: Plugins are copied to a cache, so paths referencing files outside the plugin directory won't work

413* **Plugin skills not appearing**: Clear the cache with `rm -rf ~/.claude/plugins/cache`, restart Claude Code, and reinstall the plugin.

414 

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

416 

417### Code intelligence issues

418 

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

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

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

422 

423## Next steps

424 

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

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

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

env-vars.md +202 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Environment variables

6 

7> Complete reference for environment variables that control Claude Code behavior.

8 

9Claude Code supports the following environment variables to control its behavior. Set them in your shell before launching `claude`, or configure them in [`settings.json`](/en/settings#available-settings) under the `env` key to apply them to every session or roll them out across your team.

10 

11| Variable | Purpose |

12| :------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

13| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header. When set, this key is used instead of your Claude Pro, Max, Team, or Enterprise subscription even if you are logged in. In non-interactive mode (`-p`), the key is always used when present. In interactive mode, you are prompted to approve the key once before it overrides your subscription. To use your subscription instead, run `unset ANTHROPIC_API_KEY` |

14| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) |

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

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

18| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) |

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

20| `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` | Display description for the custom model entry in the `/model` picker. Defaults to `Custom model (<model-id>)` when not set |

21| `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` | Display name for the custom model entry in the `/model` picker. Defaults to the model ID when not set |

22| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

23| `ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

24| `ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

25| `ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

26| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

27| `ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

28| `ANTHROPIC_DEFAULT_OPUS_MODEL_NAME` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

29| `ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

30| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/model-config#environment-variables) |

31| `ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

32| `ANTHROPIC_DEFAULT_SONNET_MODEL_NAME` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

33| `ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES` | See [Model configuration](/en/model-config#customize-pinned-model-display-and-capabilities) |

34| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry authentication (see [Microsoft Foundry](/en/microsoft-foundry)) |

35| `ANTHROPIC_FOUNDRY_BASE_URL` | Full base URL for the Foundry resource (for example, `https://my-resource.services.ai.azure.com/anthropic`). Alternative to `ANTHROPIC_FOUNDRY_RESOURCE` (see [Microsoft Foundry](/en/microsoft-foundry)) |

36| `ANTHROPIC_FOUNDRY_RESOURCE` | Foundry resource name (for example, `my-resource`). Required if `ANTHROPIC_FOUNDRY_BASE_URL` is not set (see [Microsoft Foundry](/en/microsoft-foundry)) |

37| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) |

38| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |

39| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |

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

41| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI. Required when using [Google Vertex AI](/en/google-vertex-ai) |

42| `API_TIMEOUT_MS` | Timeout for API requests in milliseconds (default: 600000, or 10 minutes). Increase this when requests time out on slow networks or when routing through a proxy |

43| `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/)) |

44| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |

45| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |

46| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |

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

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

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

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

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

52| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |

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

54| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load CLAUDE.md files from directories specified with `--add-dir`. By default, additional directories do not load memory files |

55| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using [`apiKeyHelper`](/en/settings#available-settings)) |

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

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

58| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |

59| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |

60| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |

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

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

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

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

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

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

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

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

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

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

71| `CLAUDE_CODE_DISABLE_FAST_MODE` | Set to `1` to disable [fast mode](/en/fast-mode) |

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

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

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

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

76| `CLAUDE_CODE_DISABLE_MOUSE` | Set to `1` to disable mouse tracking in [fullscreen rendering](/en/fullscreen). Keyboard scrolling with `PgUp` and `PgDn` still works. Use this to keep your terminal's native copy-on-select behavior |

77| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_FEEDBACK_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |

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

79| `CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL` | Set to `1` to skip automatic addition of the official plugin marketplace on first run |

80| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |

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

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

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

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

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

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

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

88| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Set to `1` to enable [agent teams](/en/agent-teams). Agent teams are experimental and disabled by default |

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

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

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

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

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

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

95| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions. Equivalent to setting [`autoInstallIdeExtension`](/en/settings#global-config-settings) to `false` |

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

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

98| `CLAUDE_CODE_MAX_RETRIES` | Override the number of times to retry failed API requests (default: 10) |

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

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

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

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

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

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

105| `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS` | Timeout in milliseconds for flushing pending OpenTelemetry spans (default: 5000). See [Monitoring](/en/monitoring-usage) |

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

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

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

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

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

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

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

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

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

115| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Maximum time in milliseconds for [SessionEnd](/en/hooks#sessionend) hooks to complete (default: `1500`). Applies to session exit, `/clear`, and switching sessions via interactive `/resume`. Per-hook `timeout` values are also capped by this budget |

116| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |

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

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

119| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |

120| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |

121| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) |

122| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) |

123| `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. `claude-code-action` sets this automatically when `allowed_non_write_users` is configured |

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

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

126| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | Set to `false` to disable syntax highlighting in diff output. Useful when colors interfere with your terminal setup |

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

128| `CLAUDE_CODE_TEAM_NAME` | Name of the agent team this teammate belongs to. Set automatically on [agent team](/en/agent-teams) members |

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

130| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |

131| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) |

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

133| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |

134| `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'` |

135| `CLAUDE_ENABLE_STREAM_WATCHDOG` | Set to `1` to abort API response streams that stall with no data for 90 seconds. Useful in automated environments where a hung session would go unnoticed, or behind proxies that drop connections silently. Without this, a stalled stream can hang the session indefinitely since the request timeout only covers the initial connection. Configure the timeout with `CLAUDE_STREAM_IDLE_TIMEOUT_MS` |

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

137| `CLAUDE_STREAM_IDLE_TIMEOUT_MS` | Timeout in milliseconds before the streaming idle watchdog closes a stalled connection. Default: `90000` (90 seconds). Requires `CLAUDE_ENABLE_STREAM_WATCHDOG=1`. Increase this value if long-running tools or slow networks cause premature timeout errors |

138| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates |

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

140| `DISABLE_COMPACT` | Set to `1` to disable all compaction: both automatic compaction and the manual `/compact` command |

141| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |

142| `DISABLE_DOCTOR_COMMAND` | Set to `1` to hide the `/doctor` command. Useful for managed deployments where users should not run installation diagnostics |

143| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |

144| `DISABLE_EXTRA_USAGE_COMMAND` | Set to `1` to hide the `/extra-usage` command that lets users purchase additional usage beyond rate limits |

145| `DISABLE_FEEDBACK_COMMAND` | Set to `1` to disable the `/feedback` command. The older name `DISABLE_BUG_COMMAND` is also accepted |

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

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

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

149| `DISABLE_LOGIN_COMMAND` | Set to `1` to hide the `/login` command. Useful when authentication is handled externally via API keys or `apiKeyHelper` |

150| `DISABLE_LOGOUT_COMMAND` | Set to `1` to hide the `/logout` command |

151| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |

152| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

153| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

154| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

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

156| `DISABLE_UPGRADE_COMMAND` | Set to `1` to hide the `/upgrade` command |

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

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

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

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

161| `FORCE_AUTOUPDATE_PLUGINS` | Set to `1` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |

162| `HTTP_PROXY` | Specify HTTP proxy server for network connections |

163| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |

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

165| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000) |

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

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

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

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

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

171| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of remote MCP servers (HTTP/SSE) to connect in parallel during startup (default: 20) |

172| `MCP_SERVER_CONNECTION_BATCH_SIZE` | Maximum number of local MCP servers (stdio) to connect in parallel during startup (default: 3) |

173| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |

174| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |

175| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |

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

177| `OTEL_LOG_TOOL_DETAILS` | Set to `1` to include MCP server names and tool details in telemetry. Disabled by default to protect PII. See [Monitoring](/en/monitoring-usage) |

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

179| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Set to `false` to exclude account UUID from metrics attributes (default: included). See [Monitoring](/en/monitoring-usage) |

180| `OTEL_METRICS_INCLUDE_SESSION_ID` | Set to `false` to exclude session ID from metrics attributes (default: included). See [Monitoring](/en/monitoring-usage) |

181| `OTEL_METRICS_INCLUDE_VERSION` | Set to `true` to include Claude Code version in metrics attributes (default: excluded). See [Monitoring](/en/monitoring-usage) |

182| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Override the character budget for skill metadata shown to the [Skill tool](/en/skills#control-who-invokes-a-skill). The budget scales dynamically at 1% of the context window, with a fallback of 8,000 characters. Legacy name kept for backwards compatibility |

183| `TASK_MAX_OUTPUT_LENGTH` | Maximum number of characters in [subagent](/en/sub-agents) output before truncation (default: 32000, maximum: 160000). When truncated, the full output is saved to disk and the path is included in the truncated response |

184| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code |

185| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |

186| `VERTEX_REGION_CLAUDE_3_5_SONNET` | Override region for Claude 3.5 Sonnet when using Vertex AI |

187| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |

188| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |

189| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |

190| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |

191| `VERTEX_REGION_CLAUDE_4_5_SONNET` | Override region for Claude Sonnet 4.5 when using Vertex AI |

192| `VERTEX_REGION_CLAUDE_4_6_SONNET` | Override region for Claude Sonnet 4.6 when using Vertex AI |

193| `VERTEX_REGION_CLAUDE_HAIKU_4_5` | Override region for Claude Haiku 4.5 when using Vertex AI |

194 

195Standard 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.

196 

197## See also

198 

199* [Settings](/en/settings): configure environment variables in `settings.json` so they apply to every session

200* [CLI reference](/en/cli-reference): launch-time flags

201* [Network configuration](/en/network-config): proxy and TLS setup

202* [Monitoring](/en/monitoring-usage): OpenTelemetry configuration

fast-mode.md +150 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Speed up responses with fast mode

6 

7> Get faster Opus 4.6 responses in Claude Code by toggling fast mode.

8 

9<Note>

10 Fast mode is in [research preview](#research-preview). The feature, pricing, and availability may change based on feedback.

11</Note>

12 

13Fast mode is a high-speed configuration for Claude Opus 4.6, making the model 2.5x faster at a higher cost per token. Toggle it on with `/fast` when you need speed for interactive work like rapid iteration or live debugging, and toggle it off when cost matters more than latency.

14 

15Fast mode is not a different model. It uses the same Opus 4.6 with a different API configuration that prioritizes speed over cost efficiency. You get identical quality and capabilities, just faster responses.

16 

17<Note>

18 Fast mode requires Claude Code v2.1.36 or later. Check your version with `claude --version`.

19</Note>

20 

21What to know:

22 

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

24* Fast mode for Opus 4.6 pricing is \$30/150 MTok.

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

26* For Claude Code users on subscription plans (Pro/Max/Team/Enterprise), fast mode is available via extra usage only and not included in the subscription rate limits.

27 

28This page covers how to [toggle fast mode](#toggle-fast-mode), its [cost tradeoff](#understand-the-cost-tradeoff), [when to use it](#decide-when-to-use-fast-mode), [requirements](#requirements), [per-session opt-in](#require-per-session-opt-in), and [rate limit behavior](#handle-rate-limits).

29 

30## Toggle fast mode

31 

32Toggle fast mode in either of these ways:

33 

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

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

36 

37By default, fast mode persists across sessions. Administrators can configure fast mode to reset each session. See [require per-session opt-in](#require-per-session-opt-in) for details.

38 

39For the best cost efficiency, enable fast mode at the start of a session rather than switching mid-conversation. See [understand the cost tradeoff](#understand-the-cost-tradeoff) for details.

40 

41When you enable fast mode:

42 

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

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

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

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

47 

48When you disable fast mode with `/fast` again, you remain on Opus 4.6. The model does not revert to your previous model. To switch to a different model, use `/model`.

49 

50## Understand the cost tradeoff

51 

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

53 

54| Mode | Input (MTok) | Output (MTok) |

55| --------------------- | ------------ | ------------- |

56| Fast mode on Opus 4.6 | \$30 | \$150 |

57 

58Fast mode pricing is flat across the full 1M token context window.

59 

60When you switch into fast mode mid-conversation, you pay the full fast mode uncached input token price for the entire conversation context. This costs more than if you had enabled fast mode from the start.

61 

62## Decide when to use fast mode

63 

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

65 

66* Rapid iteration on code changes

67* Live debugging sessions

68* Time-sensitive work with tight deadlines

69 

70Standard mode is better for:

71 

72* Long autonomous tasks where speed matters less

73* Batch processing or CI/CD pipelines

74* Cost-sensitive workloads

75 

76### Fast mode vs effort level

77 

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

79 

80| Setting | Effect |

81| ---------------------- | -------------------------------------------------------------------------------- |

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

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

84 

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

86 

87## Requirements

88 

89Fast mode requires all of the following:

90 

91* **Not available on third-party cloud providers**: fast mode is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Azure Foundry. Fast mode is available through the Anthropic Console API and for Claude subscription plans using extra usage.

92* **Extra usage enabled**: your account must have extra usage enabled, which allows billing beyond your plan's included usage. For individual accounts, enable this in your [Console billing settings](https://platform.claude.com/settings/organization/billing). For Team and Enterprise, an admin must enable extra usage for the organization.

93 

94<Note>

95 Fast mode usage is billed directly to extra usage, even if you have remaining usage on your plan. This means fast mode tokens do not count against your plan's included usage and are charged at the fast mode rate from the first token.

96</Note>

97 

98* **Admin enablement for Team and Enterprise**: fast mode is disabled by default for Team and Enterprise organizations. An admin must explicitly [enable fast mode](#enable-fast-mode-for-your-organization) before users can access it.

99 

100<Note>

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

102</Note>

103 

104### Enable fast mode for your organization

105 

106Admins can enable fast mode in:

107 

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

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

110 

111Another option to disable fast mode entirely is to set `CLAUDE_CODE_DISABLE_FAST_MODE=1`. See [Environment variables](/en/env-vars).

112 

113### Require per-session opt-in

114 

115By default, fast mode persists across sessions: if a user enables fast mode, it stays on in future sessions. Administrators on [Team](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_teams#team-&-enterprise) or [Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=fast_mode_enterprise) plans can prevent this by setting `fastModePerSessionOptIn` to `true` in [managed settings](/en/settings#settings-files) or [server-managed settings](/en/server-managed-settings). This causes each session to start with fast mode off, requiring users to explicitly enable it with `/fast`.

116 

117```json theme={null}

118{

119 "fastModePerSessionOptIn": true

120}

121```

122 

123This is useful for controlling costs in organizations where users run multiple concurrent sessions. Users can still enable fast mode with `/fast` when they need speed, but it resets at the start of each new session. The user's fast mode preference is still saved, so removing this setting restores the default persistent behavior.

124 

125## Handle rate limits

126 

127Fast mode has separate rate limits from standard Opus 4.6. When you hit the fast mode rate limit or run out of extra usage credits:

128 

1291. Fast mode automatically falls back to standard Opus 4.6

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

1313. You continue working at standard speed and pricing

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

133 

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

135 

136## Research preview

137 

138Fast mode is a research preview feature. This means:

139 

140* The feature may change based on feedback

141* Availability and pricing are subject to change

142* The underlying API configuration may evolve

143 

144Report issues or feedback through your usual Anthropic support channels.

145 

146## See also

147 

148* [Model configuration](/en/model-config): switch models and adjust effort levels

149* [Manage costs effectively](/en/costs): track token usage and reduce costs

150* [Status line configuration](/en/statusline): display model and context information

features-overview.md +294 −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# Extend Claude Code

6 

7> Understand when to use CLAUDE.md, Skills, subagents, hooks, MCP, and plugins.

8 

9Claude Code combines a model that reasons about your code with [built-in tools](/en/how-claude-code-works#tools) for file operations, search, execution, and web access. The built-in tools cover most coding tasks. This guide covers the extension layer: features you add to customize what Claude knows, connect it to external services, and automate workflows.

10 

11<Note>

12 For how the core agentic loop works, see [How Claude Code works](/en/how-claude-code-works).

13</Note>

14 

15**New to Claude Code?** Start with [CLAUDE.md](/en/memory) for project conventions. Add other extensions as you need them.

16 

17## Overview

18 

19Extensions plug into different parts of the agentic loop:

20 

21* **[CLAUDE.md](/en/memory)** adds persistent context Claude sees every session

22* **[Skills](/en/skills)** add reusable knowledge and invocable workflows

23* **[MCP](/en/mcp)** connects Claude to external services and tools

24* **[Subagents](/en/sub-agents)** run their own loops in isolated context, returning summaries

25* **[Agent teams](/en/agent-teams)** coordinate multiple independent sessions with shared tasks and peer-to-peer messaging

26* **[Hooks](/en/hooks)** run outside the loop entirely as deterministic scripts

27* **[Plugins](/en/plugins)** and **[marketplaces](/en/plugin-marketplaces)** package and distribute these features

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.

30 

31## Match features to your goal

32 

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 

35| Feature | What it does | When to use it | Example |

36| ---------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |

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 |

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 |

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 |

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)**.

45 

46### Compare similar features

47 

48Some features can seem similar. Here's how to tell them apart.

49 

50<Tabs>

51 <Tab title="Skill vs Subagent">

52 Skills and subagents solve different problems:

53 

54 * **Skills** are reusable content you can load into any context

55 * **Subagents** are isolated workers that run separately from your main conversation

56 

57 | Aspect | Skill | Subagent |

58 | --------------- | ---------------------------------------------- | ---------------------------------------------------------------- |

59 | **What it is** | Reusable instructions, knowledge, or workflows | Isolated worker with its own context |

60 | **Key benefit** | Share content across contexts | Context isolation. Work happens separately, only summary returns |

61 | **Best for** | Reference material, invocable workflows | Tasks that read many files, parallel work, specialized workers |

62 

63 **Skills can be reference or action.** Reference skills provide knowledge Claude uses throughout your session (like your API style guide). Action skills tell Claude to do something specific (like `/deploy` that runs your deployment workflow).

64 

65 **Use a subagent** when you need context isolation or when your context window is getting full. The subagent might read dozens of files or run extensive searches, but your main conversation only receives a summary. Since subagent work doesn't consume your main context, this is also useful when you don't need the intermediate work to remain visible. Custom subagents can have their own instructions and can preload skills.

66 

67 **They can combine.** A subagent can preload specific skills (`skills:` field). A skill can run in isolated context using `context: fork`. See [Skills](/en/skills) for details.

68 </Tab>

69 

70 <Tab title="CLAUDE.md vs Skill">

71 Both store instructions, but they load differently and serve different purposes.

72 

73 | Aspect | CLAUDE.md | Skill |

74 | ------------------------- | ---------------------------- | --------------------------------------- |

75 | **Loads** | Every session, automatically | On demand |

76 | **Can include files** | Yes, with `@path` imports | Yes, with `@path` imports |

77 | **Can trigger workflows** | No | Yes, with `/<name>` |

78 | **Best for** | "Always do X" rules | Reference material, invocable workflows |

79 

80 **Put it in CLAUDE.md** if Claude should always know it: coding conventions, build commands, project structure, "never do X" rules.

81 

82 **Put it in a skill** if it's reference material Claude needs sometimes (API docs, style guides) or a workflow you trigger with `/<name>` (deploy, review, release).

83 

84 **Rule of thumb:** Keep CLAUDE.md under 200 lines. If it's growing, move reference content to skills or split into [`.claude/rules/`](/en/memory#organize-rules-with-claude/rules/) files.

85 </Tab>

86 

87 <Tab title="CLAUDE.md vs Rules vs Skills">

88 All three store instructions, but they load differently:

89 

90 | Aspect | CLAUDE.md | `.claude/rules/` | Skill |

91 | ------------ | ----------------------------------- | -------------------------------------------------- | ---------------------------------------- |

92 | **Loads** | Every session | Every session, or when matching files are opened | On demand, when invoked or relevant |

93 | **Scope** | Whole project | Can be scoped to file paths | Task-specific |

94 | **Best for** | Core conventions and build commands | Language-specific or directory-specific guidelines | Reference material, repeatable workflows |

95 

96 **Use CLAUDE.md** for instructions every session needs: build commands, test conventions, project architecture.

97 

98 **Use rules** to keep CLAUDE.md focused. Rules with [`paths` frontmatter](/en/memory#path-specific-rules) only load when Claude works with matching files, saving context.

99 

100 **Use skills** for content Claude only needs sometimes, like API documentation or a deployment checklist you trigger with `/<name>`.

101 </Tab>

102 

103 <Tab title="Subagent vs Agent team">

104 Both parallelize work, but they're architecturally different:

105 

106 * **Subagents** run inside your session and report results back to your main context

107 * **Agent teams** are independent Claude Code sessions that communicate with each other

108 

109 | Aspect | Subagent | Agent team |

110 | ----------------- | ------------------------------------------------ | --------------------------------------------------- |

111 | **Context** | Own context window; results return to the caller | Own context window; fully independent |

112 | **Communication** | Reports results back to the main agent only | Teammates message each other directly |

113 | **Coordination** | Main agent manages all work | Shared task list with self-coordination |

114 | **Best for** | Focused tasks where only the result matters | Complex work requiring discussion and collaboration |

115 | **Token cost** | Lower: results summarized back to main context | Higher: each teammate is a separate Claude instance |

116 

117 **Use a subagent** when you need a quick, focused worker: research a question, verify a claim, review a file. The subagent does the work and returns a summary. Your main conversation stays clean.

118 

119 **Use an agent team** when teammates need to share findings, challenge each other, and coordinate independently. Agent teams are best for research with competing hypotheses, parallel code review, and new feature development where each teammate owns a separate piece.

120 

121 **Transition point:** If you're running parallel subagents but hitting context limits, or if your subagents need to communicate with each other, agent teams are the natural next step.

122 

123 <Note>

124 Agent teams are experimental and disabled by default. See [agent teams](/en/agent-teams) for setup and current limitations.

125 </Note>

126 </Tab>

127 

128 <Tab title="MCP vs Skill">

129 MCP connects Claude to external services. Skills extend what Claude knows, including how to use those services effectively.

130 

131 | Aspect | MCP | Skill |

132 | -------------- | ---------------------------------------------------- | ------------------------------------------------------- |

133 | **What it is** | Protocol for connecting to external services | Knowledge, workflows, and reference material |

134 | **Provides** | Tools and data access | Knowledge, workflows, reference material |

135 | **Examples** | Slack integration, database queries, browser control | Code review checklist, deploy workflow, API style guide |

136 

137 These solve different problems and work well together:

138 

139 **MCP** gives Claude the ability to interact with external systems. Without MCP, Claude can't query your database or post to Slack.

140 

141 **Skills** give Claude knowledge about how to use those tools effectively, plus workflows you can trigger with `/<name>`. A skill might include your team's database schema and query patterns, or a `/post-to-slack` workflow with your team's message formatting rules.

142 

143 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.

144 </Tab>

145</Tabs>

146 

147### Understand how features layer

148 

149Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here's how they layer:

150 

151* **CLAUDE.md files** are additive: all levels contribute content to Claude's context simultaneously. Files from your working directory and above load at launch; subdirectories load as you work in them. When instructions conflict, Claude uses judgment to reconcile them, with more specific instructions typically taking precedence. See [how CLAUDE.md files load](/en/memory#how-claude-md-files-load).

152* **Skills and subagents** override by name: when the same name exists at multiple levels, one definition wins based on priority (managed > user > project for skills; managed > CLI flag > project > user > plugin for subagents). Plugin skills are [namespaced](/en/plugins#add-skills-to-your-plugin) to avoid conflicts. See [skill discovery](/en/skills#where-skills-live) and [subagent scope](/en/sub-agents#choose-the-subagent-scope).

153* **MCP servers** override by name: local > project > user. See [MCP scope](/en/mcp#scope-hierarchy-and-precedence).

154* **Hooks** merge: all registered hooks fire for their matching events regardless of source. See [hooks](/en/hooks).

155 

156### Combine features

157 

158Each extension solves a different problem: CLAUDE.md handles always-on context, skills handle on-demand knowledge and workflows, MCP handles external connections, subagents handle isolation, and hooks handle automation. Real setups combine them based on your workflow.

159 

160For example, you might use CLAUDE.md for project conventions, a skill for your deployment workflow, MCP to connect to your database, and a hook to run linting after every edit. Each feature handles what it's best at.

161 

162| Pattern | How it works | Example |

163| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |

164| **Skill + MCP** | MCP provides the connection; a skill teaches Claude how to use it well | MCP connects to your database, a skill documents your schema and query patterns |

165| **Skill + Subagent** | A skill spawns subagents for parallel work | `/audit` skill kicks off security, performance, and style subagents that work in isolated context |

166| **CLAUDE.md + Skills** | CLAUDE.md holds always-on rules; skills hold reference material loaded on demand | CLAUDE.md says "follow our API conventions," a skill contains the full API style guide |

167| **Hook + MCP** | A hook triggers external actions through MCP | Post-edit hook sends a Slack notification when Claude modifies critical files |

168 

169## Understand context costs

170 

171Every feature you add consumes some of Claude's context. Too much can fill up your context window, but it can also add noise that makes Claude less effective; skills may not trigger correctly, or Claude may lose track of your conventions. Understanding these trade-offs helps you build an effective setup. For an interactive view of how these features combine in a running session, see [Explore the context window](/en/context-window).

172 

173### Context cost by feature

174 

175Each feature has a different loading strategy and context cost:

176 

177| Feature | When it loads | What loads | Context cost |

178| --------------- | ------------------------- | --------------------------------------------- | -------------------------------------------- |

179| **CLAUDE.md** | Session start | Full content | Every request |

180| **Skills** | Session start + when used | Descriptions at start, full content when used | Low (descriptions every request)\* |

181| **MCP servers** | Session start | Tool names; full schemas on demand | Low until a tool is used |

182| **Subagents** | When spawned | Fresh context with specified skills | Isolated from main session |

183| **Hooks** | On trigger | Nothing (runs externally) | Zero, unless hook returns additional context |

184 

185\*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.

186 

187### Understand how features load

188 

189Each feature loads at different points in your session. The tabs below explain when each one loads and what goes into context.

190 

191<img src="https://mintcdn.com/claude-code/6yTCYq1p37ZB8-CQ/images/context-loading.svg?fit=max&auto=format&n=6yTCYq1p37ZB8-CQ&q=85&s=5a58ce953a35a2412892015e2ad6cb67" alt="Context loading: CLAUDE.md loads at session start and stays in every request. MCP tool names load at start with full schemas deferred until use. Skills load descriptions at start, full content on invocation. Subagents get isolated context. Hooks run externally." width="720" height="410" data-path="images/context-loading.svg" />

192 

193<Tabs>

194 <Tab title="CLAUDE.md">

195 **When:** Session start

196 

197 **What loads:** Full content of all CLAUDE.md files (managed, user, and project levels).

198 

199 **Inheritance:** Claude reads CLAUDE.md files from your working directory up to the root, and discovers nested ones in subdirectories as it accesses those files. See [How CLAUDE.md files load](/en/memory#how-claude-md-files-load) for details.

200 

201 <Tip>Keep CLAUDE.md under 200 lines. Move reference material to skills, which load on-demand.</Tip>

202 </Tab>

203 

204 <Tab title="Skills">

205 Skills are extra capabilities in Claude's toolkit. They can be reference material (like an API style guide) or invocable workflows you trigger with `/<name>` (like `/deploy`). Claude Code ships with [bundled skills](/en/skills#bundled-skills) like `/simplify`, `/batch`, and `/debug` that work out of the box. You can also create your own. Claude uses skills when appropriate, or you can invoke one directly.

206 

207 **When:** Depends on the skill's configuration. By default, descriptions load at session start and full content loads when used. For user-only skills (`disable-model-invocation: true`), nothing loads until you invoke them.

208 

209 **What loads:** For model-invocable skills, Claude sees names and descriptions in every request. When you invoke a skill with `/<name>` or Claude loads it automatically, the full content loads into your conversation.

210 

211 **How Claude chooses skills:** Claude matches your task against skill descriptions to decide which are relevant. If descriptions are vague or overlap, Claude may load the wrong skill or miss one that would help. To tell Claude to use a specific skill, invoke it with `/<name>`. Skills with `disable-model-invocation: true` are invisible to Claude until you invoke them.

212 

213 **Context cost:** Low until used. User-only skills have zero cost until invoked.

214 

215 **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.

216 

217 <Tip>Use `disable-model-invocation: true` for skills with side effects. This saves context and ensures only you trigger them.</Tip>

218 </Tab>

219 

220 <Tab title="MCP servers">

221 **When:** Session start.

222 

223 **What loads:** Tool names from connected servers. Full JSON schemas stay deferred until Claude needs a specific tool.

224 

225 **Context cost:** [Tool search](/en/mcp#scale-with-mcp-tool-search) is on by default, so idle MCP tools consume minimal context.

226 

227 **Reliability note:** MCP connections can fail silently mid-session. If a server disconnects, its tools disappear without warning. Claude may try to use a tool that no longer exists. If you notice Claude failing to use an MCP tool it previously could access, check the connection with `/mcp`.

228 

229 <Tip>Run `/mcp` to see token costs per server. Disconnect servers you're not actively using.</Tip>

230 </Tab>

231 

232 <Tab title="Subagents">

233 **When:** On demand, when you or Claude spawns one for a task.

234 

235 **What loads:** Fresh, isolated context containing:

236 

237 * The system prompt (shared with parent for cache efficiency)

238 * Full content of skills listed in the agent's `skills:` field

239 * CLAUDE.md and git status (inherited from parent)

240 * Whatever context the lead agent passes in the prompt

241 

242 **Context cost:** Isolated from main session. Subagents don't inherit your conversation history or invoked skills.

243 

244 <Tip>Use subagents for work that doesn't need your full conversation context. Their isolation prevents bloating your main session.</Tip>

245 </Tab>

246 

247 <Tab title="Hooks">

248 **When:** On trigger. Hooks fire at specific lifecycle events like tool execution, session boundaries, prompt submission, permission requests, and compaction. See [Hooks](/en/hooks) for the full list.

249 

250 **What loads:** Nothing by default. Hooks run as external scripts.

251 

252 **Context cost:** Zero, unless the hook returns output that gets added as messages to your conversation.

253 

254 <Tip>Hooks are ideal for side effects (linting, logging) that don't need to affect Claude's context.</Tip>

255 </Tab>

256</Tabs>

257 

258## Learn more

259 

260Each feature has its own guide with setup instructions, examples, and configuration options.

261 

262<CardGroup cols={2}>

263 <Card title="CLAUDE.md" icon="file-lines" href="/en/memory">

264 Store project context, conventions, and instructions

265 </Card>

266 

267 <Card title="Skills" icon="brain" href="/en/skills">

268 Give Claude domain expertise and reusable workflows

269 </Card>

270 

271 <Card title="Subagents" icon="users" href="/en/sub-agents">

272 Offload work to isolated context

273 </Card>

274 

275 <Card title="Agent teams" icon="network" href="/en/agent-teams">

276 Coordinate multiple sessions working in parallel

277 </Card>

278 

279 <Card title="MCP" icon="plug" href="/en/mcp">

280 Connect Claude to external services

281 </Card>

282 

283 <Card title="Hooks" icon="bolt" href="/en/hooks-guide">

284 Automate workflows with hooks

285 </Card>

286 

287 <Card title="Plugins" icon="puzzle-piece" href="/en/plugins">

288 Bundle and share feature sets

289 </Card>

290 

291 <Card title="Marketplaces" icon="store" href="/en/plugin-marketplaces">

292 Host and distribute plugin collections

293 </Card>

294</CardGroup>

fullscreen.md +145 −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# Fullscreen rendering

6 

7> Enable a smoother, flicker-free rendering mode with mouse support and stable memory usage in long conversations.

8 

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.

11</Note>

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.

14 

15The difference is most noticeable in terminal emulators where rendering throughput is the bottleneck, such as the VS Code integrated terminal, tmux, and iTerm2. If your terminal scroll position jumps to the top while Claude is working, or the screen flashes as tool output streams in, this mode addresses those.

16 

17<Note>

18 The term fullscreen describes how Claude Code takes over the terminal's drawing surface, the way `vim` does. It has nothing to do with maximizing your terminal window, and works at any window size.

19</Note>

20 

21## Enable fullscreen rendering

22 

23Set the `CLAUDE_CODE_NO_FLICKER` environment variable when starting Claude Code:

24 

25```bash theme={null}

26CLAUDE_CODE_NO_FLICKER=1 claude

27```

28 

29To enable it for every session, export the variable in your shell profile such as `~/.zshrc` or `~/.bashrc`:

30 

31```bash theme={null}

32export CLAUDE_CODE_NO_FLICKER=1

33```

34 

35## What changes

36 

37Fullscreen rendering changes how the CLI draws to your terminal. The input box stays fixed at the bottom of the screen instead of moving as output streams in. If the input stays put while Claude is working, fullscreen rendering is active. Only visible messages are kept in the render tree, so memory stays constant regardless of conversation length.

38 

39Because the conversation lives in the alternate screen buffer instead of your terminal's scrollback, a few things work differently:

40 

41| Before | Now | Details |

42| :-------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |

43| `Cmd+f` or tmux search to find text | `Ctrl+o` then `/` to search, or `Ctrl+o` then `[` to write the conversation to native scrollback so `Cmd+f` works again | [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) |

45| `Cmd`-click to open a URL | Click the URL | [Use the mouse](#use-the-mouse) |

46 

47If mouse capture interferes with your workflow, you can [turn it off](#keep-native-text-selection) while keeping the flicker-free rendering.

48 

49## Use the mouse

50 

51Fullscreen rendering captures mouse events and handles them inside Claude Code:

52 

53* **Click in the prompt input** to position your cursor anywhere in the text you're typing.

54* **Click a collapsed tool result** to expand it and see the full output. Click again to collapse. The tool call and its result expand together. Only messages that have more to show are clickable.

55* **Click a URL or file path** to open it. File paths in tool output, like the ones printed after an Edit or Write, open in your default application. Plain `http://` and `https://` URLs open in your browser. In most terminals this replaces native `Cmd`-click or `Ctrl`-click, which mouse capture intercepts. In the VS Code integrated terminal and similar xterm.js-based terminals, keep using `Cmd`-click. Claude Code defers to the terminal's own link handler there to avoid opening links twice.

56* **Click and drag** to select text anywhere in the conversation. Double-click selects a word, matching iTerm2's word boundaries so a file path selects as one unit. Triple-click selects the line.

57* **Scroll with the mouse wheel** to move through the conversation.

58 

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.

60 

61## Scroll the conversation

62 

63Fullscreen rendering handles scrolling inside the app. Use these shortcuts to navigate:

64 

65| Shortcut | Action |

66| :-------------- | :--------------------------------------------------- |

67| `PgUp` / `PgDn` | Scroll up or down by half a screen |

68| `Ctrl+Home` | Jump to the start of the conversation |

69| `Ctrl+End` | Jump to the latest message and re-enable auto-follow |

70| Mouse wheel | Scroll a few lines at a time |

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.

73 

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.

75 

76Mouse 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.

77 

78### Adjust wheel scroll speed

79 

80If 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.

81 

82Set `CLAUDE_CODE_SCROLL_SPEED` to multiply the base scroll distance:

83 

84```bash theme={null}

85export CLAUDE_CODE_SCROLL_SPEED=3

86```

87 

88A value of `3` matches the default in `vim` and similar applications. The setting accepts values from 1 to 20.

89 

90## Search and review the conversation

91 

92Press `Ctrl+o` to enter transcript mode. With fullscreen rendering active, transcript mode gains `less`-style navigation and search:

93 

94| Key | Action |

95| :----------------------------------- | :----------------------------------------------------------------------------------------------------- |

96| `/` | Open search. Type to find matches, `Enter` to accept, `Esc` to cancel and restore your scroll position |

97| `n` / `N` | Jump to next or previous match. Works after you've closed the search bar |

98| `j` / `k` or `↑` / `↓` | Scroll one line |

99| `g` / `G` or `Home` / `End` | Jump to top or bottom |

100| `Ctrl+u` / `Ctrl+d` | Scroll half a page |

101| `Ctrl+b` / `Ctrl+f` or `Space` / `b` | Scroll a full page |

102| `Esc`, `q`, or `Ctrl+o` | Exit transcript mode |

103 

104Your 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:

105 

106* **`[`**: writes the full conversation into your terminal's native scrollback buffer, with all tool output expanded. The conversation is now ordinary text in your terminal, so `Cmd+f`, tmux copy mode, and any other native tool can search or select it. Long sessions may pause for a moment while this happens. This lasts until you exit transcript mode with `Esc` or `q`, which returns you to fullscreen rendering. The next `Ctrl+o` starts fresh.

107* **`v`**: writes the conversation to a temporary file and opens it in `$VISUAL` or `$EDITOR`.

108 

109Press `Esc`, `q`, or `Ctrl+o` to return to the prompt.

110 

111## Use with tmux

112 

113Fullscreen rendering works inside tmux, with two caveats.

114 

115Mouse wheel scrolling requires tmux's mouse mode. If your `~/.tmux.conf` does not already enable it, add this line and reload your config:

116 

117```bash theme={null}

118set -g mouse on

119```

120 

121Without mouse mode, wheel events go to tmux instead of Claude Code. Keyboard scrolling with `PgUp` and `PgDn` works either way. Claude Code prints a one-time hint at startup if it detects tmux with mouse mode off.

122 

123Fullscreen 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.

124 

125## Keep native text selection

126 

127Mouse 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.

128 

129Claude 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.

130 

131If 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:

132 

133```bash theme={null}

134CLAUDE_CODE_NO_FLICKER=1 CLAUDE_CODE_DISABLE_MOUSE=1 claude

135```

136 

137With mouse capture disabled, keyboard scrolling with `PgUp`, `PgDn`, `Ctrl+Home`, and `Ctrl+End` still works, and your terminal handles selection natively. You lose click-to-position-cursor, click-to-expand tool output, URL clicking, and wheel scrolling inside Claude Code.

138 

139## Research preview

140 

141Fullscreen rendering is a research preview feature. It has been tested on common terminal emulators, but you may encounter rendering issues on less common terminals or unusual configurations.

142 

143If 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.

144 

145To turn fullscreen rendering off, unset the environment variable or set `CLAUDE_CODE_NO_FLICKER=0`.

github-actions.md +34 −30

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code GitHub Actions5# Claude Code GitHub Actions

2 6 

3> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions7> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions

4 8 

5Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards.9Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards. For automatic reviews posted on every PR without a trigger, see [GitHub Code Review](/en/code-review).

6 10 

7<Note>11<Note>

8 Claude Code GitHub Actions is built on top of the [Claude Code12 Claude Code GitHub Actions is built on top of the [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), which enables programmatic integration of Claude Code into your applications. You can use the SDK to build custom automation workflows beyond GitHub Actions.

9 SDK](/en/docs/claude-code/sdk), which enables programmatic integration of

10 Claude Code into your applications. You can use the SDK to build custom

11 automation workflows beyond GitHub Actions.

12</Note>13</Note>

13 14 

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`.

17</Info>

18 

14## Why use Claude Code GitHub Actions?19## Why use Claude Code GitHub Actions?

15 20 

16* **Instant PR creation**: Describe what you need, and Claude creates a complete PR with all necessary changes21* **Instant PR creation**: Describe what you need, and Claude creates a complete PR with all necessary changes


633. **Copy the workflow file** from [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) into your repository's `.github/workflows/`683. **Copy the workflow file** from [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) into your repository's `.github/workflows/`

64 69 

65<Tip>70<Tip>

66 After completing either the quickstart or manual setup, test the action by71 After completing either the quickstart or manual setup, test the action by tagging `@claude` in an issue or PR comment.

67 tagging `@claude` in an issue or PR comment!

68</Tip>72</Tip>

69 73 

70## Upgrading from Beta74## Upgrading from Beta


87### Breaking Changes Reference91### Breaking Changes Reference

88 92 

89| Old Beta Input | New v1.0 Input |93| Old Beta Input | New v1.0 Input |

90| --------------------- | -------------------------------- |94| --------------------- | ------------------------------------- |

91| `mode` | *(Removed - auto-detected)* |95| `mode` | *(Removed - auto-detected)* |

92| `direct_prompt` | `prompt` |96| `direct_prompt` | `prompt` |

93| `override_prompt` | `prompt` with GitHub variables |97| `override_prompt` | `prompt` with GitHub variables |

94| `custom_instructions` | `claude_args: --system-prompt` |98| `custom_instructions` | `claude_args: --append-system-prompt` |

95| `max_turns` | `claude_args: --max-turns` |99| `max_turns` | `claude_args: --max-turns` |

96| `model` | `claude_args: --model` |100| `model` | `claude_args: --model` |

97| `allowed_tools` | `claude_args: --allowedTools` |101| `allowed_tools` | `claude_args: --allowedTools` |


110 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}114 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

111 custom_instructions: "Follow our coding standards"115 custom_instructions: "Follow our coding standards"

112 max_turns: "10"116 max_turns: "10"

113 model: "claude-sonnet-4-5-20250929"117 model: "claude-sonnet-4-6"

114```118```

115 119 

116**GA version (v1.0):**120**GA version (v1.0):**


121 prompt: "Review this PR for security issues"125 prompt: "Review this PR for security issues"

122 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}126 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

123 claude_args: |127 claude_args: |

124 --system-prompt "Follow our coding standards"128 --append-system-prompt "Follow our coding standards"

125 --max-turns 10129 --max-turns 10

126 --model claude-sonnet-4-5-20250929130 --model claude-sonnet-4-6

127```131```

128 132 

129<Tip>133<Tip>


153 # Responds to @claude mentions in comments157 # Responds to @claude mentions in comments

154```158```

155 159 

156### Using slash commands160### Using skills

157 161 

158```yaml theme={null}162```yaml theme={null}

159name: Code Review163name: Code Review


167 - uses: anthropics/claude-code-action@v1171 - uses: anthropics/claude-code-action@v1

168 with:172 with:

169 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}173 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

170 prompt: "/review"174 prompt: "Review this pull request for code quality, correctness, and security. Analyze the diff, then post your findings as review comments."

171 claude_args: "--max-turns 5"175 claude_args: "--max-turns 5"

172```176```

173 177 


186 with:190 with:

187 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}191 anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

188 prompt: "Generate a summary of yesterday's commits and open issues"192 prompt: "Generate a summary of yesterday's commits and open issues"

189 claude_args: "--model claude-opus-4-1-20250805"193 claude_args: "--model opus"

190```194```

191 195 

192### Common use cases196### Common use cases

193 197 

194In issue or PR comments:198In issue or PR comments:

195 199 

196```200```text theme={null}

197@claude implement this feature based on the issue description201@claude implement this feature based on the issue description

198@claude how should I implement user authentication for this endpoint?202@claude how should I implement user authentication for this endpoint?

199@claude fix the TypeError in the user dashboard component203@claude fix the TypeError in the user dashboard component


209 213 

210### Security considerations214### Security considerations

211 215 

212<Warning>Never commit API keys directly to your repository!</Warning>216<Warning>Never commit API keys directly to your repository.</Warning>

213 217 

214For comprehensive security guidance including permissions, authentication, and best practices, see the [Claude Code Action security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).218For comprehensive security guidance including permissions, authentication, and best practices, see the [Claude Code Action security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).

215 219 


220* Limit action permissions to only what's necessary224* Limit action permissions to only what's necessary

221* Review Claude's suggestions before merging225* Review Claude's suggestions before merging

222 226 

223Always use GitHub Secrets (e.g., `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.227Always use GitHub Secrets (for example, `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.

224 228 

225### Optimizing performance229### Optimizing performance

226 230 


263Key features:267Key features:

264 268 

265* **Unified prompt interface** - Use `prompt` for all instructions269* **Unified prompt interface** - Use `prompt` for all instructions

266* **Slash commands** - Pre-built prompts like `/review` or `/fix`270* **Skills** - Invoke installed [skills](/en/skills) directly from the prompt

267* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`271* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`

268* **Flexible triggers** - Works with any GitHub event272* **Flexible triggers** - Works with any GitHub event

269 273 


514 with:518 with:

515 github_token: ${{ steps.app-token.outputs.token }}519 github_token: ${{ steps.app-token.outputs.token }}

516 use_bedrock: "true"520 use_bedrock: "true"

517 claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0 --max-turns 10'521 claude_args: '--model us.anthropic.claude-sonnet-4-6 --max-turns 10'

518 ```522 ```

519 523 

520 <Tip>524 <Tip>

521 The model ID format for Bedrock includes the region prefix (e.g., `us.anthropic.claude...`) and version suffix.525 The model ID format for Bedrock includes a region prefix (for example, `us.anthropic.claude-sonnet-4-6`).

522 </Tip>526 </Tip>

523 </Accordion>527 </Accordion>

524 528 


585 github_token: ${{ steps.app-token.outputs.token }}589 github_token: ${{ steps.app-token.outputs.token }}

586 trigger_phrase: "@claude"590 trigger_phrase: "@claude"

587 use_vertex: "true"591 use_vertex: "true"

588 claude_args: '--model claude-sonnet-4@20250514 --max-turns 10'592 claude_args: '--model claude-sonnet-4-5@20250929 --max-turns 10'

589 env:593 env:

590 ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}594 ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}

591 CLOUD_ML_REGION: us-east5595 CLOUD_ML_REGION: us-east5

592 VERTEX_REGION_CLAUDE_3_7_SONNET: us-east5596 VERTEX_REGION_CLAUDE_4_5_SONNET: us-east5

593 ```597 ```

594 598 

595 <Tip>599 <Tip>


621The Claude Code Action v1 uses a simplified configuration:625The Claude Code Action v1 uses a simplified configuration:

622 626 

623| Parameter | Description | Required |627| Parameter | Description | Required |

624| ------------------- | ----------------------------------------------- | -------- |628| ------------------- | ------------------------------------------------------------------ | -------- |

625| `prompt` | Instructions for Claude (text or slash command) | No\* |629| `prompt` | Instructions for Claude (plain text or a [skill](/en/skills) name) | No\* |

626| `claude_args` | CLI arguments passed to Claude Code | No |630| `claude_args` | CLI arguments passed to Claude Code | No |

627| `anthropic_api_key` | Claude API key | Yes\*\* |631| `anthropic_api_key` | Claude API key | Yes\*\* |

628| `github_token` | GitHub token for API access | No |632| `github_token` | GitHub token for API access | No |


633\*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\

634\*\*Required for direct Claude API, not for Bedrock/Vertex638\*\*Required for direct Claude API, not for Bedrock/Vertex

635 639 

636#### Using claude\_args640#### Pass CLI arguments

637 641 

638The `claude_args` parameter accepts any Claude Code CLI arguments:642The `claude_args` parameter accepts any Claude Code CLI arguments:

639 643 

640```yaml theme={null}644```yaml theme={null}

641claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json"645claude_args: "--max-turns 5 --model claude-sonnet-4-6 --mcp-config /path/to/config.json"

642```646```

643 647 

644Common arguments:648Common arguments:

645 649 

646* `--max-turns`: Maximum conversation turns (default: 10)650* `--max-turns`: Maximum conversation turns (default: 10)

647* `--model`: Model to use (e.g., `claude-sonnet-4-5-20250929`)651* `--model`: Model to use (for example, `claude-sonnet-4-6`)

648* `--mcp-config`: Path to MCP configuration652* `--mcp-config`: Path to MCP configuration

649* `--allowed-tools`: Comma-separated list of allowed tools653* `--allowedTools`: Comma-separated list of allowed tools. The `--allowed-tools` alias also works.

650* `--debug`: Enable debug output654* `--debug`: Enable debug output

651 655 

652### Alternative integration methods656### Alternative integration methods


663 667 

664You can configure Claude's behavior in two ways:668You can configure Claude's behavior in two ways:

665 669 

6661. **CLAUDE.md**: Define coding standards, review criteria, and project-specific rules in a `CLAUDE.md` file at the root of your repository. Claude will follow these guidelines when creating PRs and responding to requests. Check out our [Memory documentation](/en/docs/claude-code/memory) for more details.6701. **CLAUDE.md**: Define coding standards, review criteria, and project-specific rules in a `CLAUDE.md` file at the root of your repository. Claude will follow these guidelines when creating PRs and responding to requests. Check out our [Memory documentation](/en/memory) for more details.

6672. **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude's behavior for different workflows or tasks.6712. **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude's behavior for different workflows or tasks.

668 672 

669Claude will follow these guidelines when creating PRs and responding to requests.673Claude will follow these guidelines when creating PRs and responding to requests.

github-enterprise-server.md +188 −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# Claude Code with GitHub Enterprise Server

6 

7> Connect Claude Code to your self-hosted GitHub Enterprise Server instance for web sessions, code review, and plugin marketplaces.

8 

9<Note>

10 GitHub Enterprise Server support is available for Team and Enterprise plans.

11</Note>

12 

13GitHub Enterprise Server (GHES) support lets your organization use Claude Code with repositories hosted on your self-managed GitHub instance instead of github.com. Once an admin connects your GHES instance, developers can run web sessions, get automated code reviews, and install plugins from internal marketplaces without any per-repository configuration.

14 

15For repositories on github.com, see [Claude Code on the web](/en/claude-code-on-the-web) and [Code Review](/en/code-review). To run Claude in your own CI infrastructure, see [GitHub Actions](/en/github-actions).

16 

17## What works with GitHub Enterprise Server

18 

19The table below shows which Claude Code features support GHES and any differences from github.com behavior.

20 

21| Feature | GHES support | Notes |

22| :--------------------- | :-------------- | :--------------------------------------------------------------------------------------------------------------------------- |

23| Claude Code on the web | ✅ Supported | Admin connects the GHES instance once; developers use `claude --remote` or [claude.ai/code](https://claude.ai/code) as usual |

24| Code Review | ✅ Supported | Same automated PR reviews as github.com |

25| Teleport sessions | ✅ Supported | Move sessions between web and terminal with `/teleport` |

26| Plugin marketplaces | ✅ Supported | Use full git URLs instead of `owner/repo` shorthand |

27| Contribution metrics | ✅ Supported | Delivered via webhooks to the [analytics dashboard](/en/analytics) |

28| GitHub Actions | ✅ Supported | Requires manual workflow setup; `/install-github-app` is github.com only |

29| GitHub MCP server | ❌ Not supported | The GitHub MCP server does not work with GHES instances |

30 

31## Admin setup

32 

33An admin connects your GHES instance to Claude Code once. After that, developers in your organization can use GHES repositories without any additional configuration. You need admin access to your Claude organization and permission to create GitHub Apps on your GHES instance.

34 

35The guided setup generates a GitHub App manifest and redirects you to your GHES instance to create the app in one click. If your environment blocks the redirect flow, an [alternative manual setup](#manual-setup) is available.

36 

37<Steps>

38 <Step title="Open Claude Code admin settings">

39 Go to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and find the GitHub Enterprise Server section.

40 </Step>

41 

42 <Step title="Start the guided setup">

43 Click **Connect**. Enter a display name for the connection and your GHES hostname, for example `github.example.com`. If your GHES instance uses a self-signed or private certificate authority, paste the CA certificate in the optional field.

44 </Step>

45 

46 <Step title="Create the GitHub App">

47 Click **Continue to GitHub Enterprise**. Your browser redirects to your GHES instance with a pre-filled app manifest. Review the configuration and click **Create GitHub App**. GHES redirects you back to Claude with the app credentials stored automatically.

48 </Step>

49 

50 <Step title="Install the app on your repositories">

51 From the GitHub App page on your GHES instance, install the app on the repositories or organizations you want Claude to access. You can start with a subset and add more later.

52 </Step>

53 

54 <Step title="Enable features">

55 Return to [claude.ai/admin-settings/claude-code](https://claude.ai/admin-settings/claude-code) and enable [Code Review](/en/code-review#set-up-code-review) and [contribution metrics](/en/analytics#enable-contribution-metrics) for your GHES repositories using the same configuration as github.com.

56 </Step>

57</Steps>

58 

59### GitHub App permissions

60 

61The manifest configures the GitHub App with the permissions and webhook events Claude needs across web sessions, Code Review, and contribution metrics:

62 

63| Permission | Access | Used for |

64| :--------------- | :------------- | :------------------------------------------ |

65| Contents | Read and write | Cloning repositories and pushing branches |

66| Pull requests | Read and write | Creating PRs and posting review comments |

67| Issues | Read and write | Responding to issue mentions |

68| Checks | Read and write | Posting Code Review check runs |

69| Actions | Read | Reading CI status for auto-fix |

70| Repository hooks | Read and write | Receiving webhooks for contribution metrics |

71| Metadata | Read | Required by GitHub for all apps |

72 

73The app subscribes to `pull_request`, `issue_comment`, `pull_request_review_comment`, `pull_request_review`, and `check_run` events.

74 

75### Manual setup

76 

77If the guided redirect flow is blocked by your network configuration, click **Add manually** instead of Connect. Create a GitHub App on your GHES instance with the [permissions and events above](#github-app-permissions), then enter the app credentials in the form: hostname, OAuth client ID and secret, GitHub App ID, client ID, client secret, webhook secret, and private key.

78 

79### Network requirements

80 

81Your GHES instance must be reachable from Anthropic infrastructure so Claude can clone repositories and post review comments. If your GHES instance is behind a firewall, allowlist the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).

82 

83## Developer workflow

84 

85Once your admin has connected the GHES instance, no developer-side configuration is needed. Claude Code detects your GHES hostname automatically from the git remote in your working directory.

86 

87Clone a repository from your GHES instance as you normally would:

88 

89```bash theme={null}

90git clone git@github.example.com:platform/api-service.git

91cd api-service

92```

93 

94Then start a web session. Claude detects the GHES host from your git remote and routes the session through your organization's configured instance:

95 

96```bash theme={null}

97claude --remote "Add retry logic to the payment webhook handler"

98```

99 

100The session runs on Anthropic infrastructure, clones your repository from GHES, and pushes changes back to a branch. Monitor progress with `/tasks` or at [claude.ai/code](https://claude.ai/code). See [Claude Code on the web](/en/claude-code-on-the-web) for the full remote session workflow including diff review, auto-fix, and scheduled tasks.

101 

102### Teleport sessions to your terminal

103 

104Pull a web session into your local terminal with `/teleport` or `claude --teleport`. Teleport verifies you're in a checkout of the same GHES repository before fetching the branch and loading the session history. See [teleport requirements](/en/claude-code-on-the-web#requirements-for-teleporting) for details.

105 

106## Plugin marketplaces on GHES

107 

108Host plugin marketplaces on your GHES instance to distribute internal tooling across your organization. The marketplace structure is identical to github.com-hosted marketplaces; the only difference is how you reference them.

109 

110### Add a GHES marketplace

111 

112The `owner/repo` shorthand always resolves to github.com. For GHES-hosted marketplaces, use the full git URL:

113 

114```bash theme={null}

115/plugin marketplace add git@github.example.com:platform/claude-plugins.git

116```

117 

118HTTPS URLs work as well:

119 

120```bash theme={null}

121/plugin marketplace add https://github.example.com/platform/claude-plugins.git

122```

123 

124See [Create and distribute a plugin marketplace](/en/plugin-marketplaces) for the full guide to building marketplaces.

125 

126### Allowlist GHES marketplaces in managed settings

127 

128If your organization uses [managed settings](/en/settings) to restrict which marketplaces developers can add, use the `hostPattern` source type to allow all marketplaces from your GHES instance without enumerating each repository:

129 

130```json theme={null}

131{

132 "strictKnownMarketplaces": [

133 {

134 "source": "hostPattern",

135 "hostPattern": "^github\\.example\\.com$"

136 }

137 ]

138}

139```

140 

141You can also pre-register marketplaces for developers so they appear without manual setup. This example makes an internal tools marketplace available organization-wide:

142 

143```json theme={null}

144{

145 "extraKnownMarketplaces": {

146 "internal-tools": {

147 "source": {

148 "source": "git",

149 "url": "git@github.example.com:platform/claude-plugins.git"

150 }

151 }

152 }

153}

154```

155 

156See the [strictKnownMarketplaces](/en/settings#strictknownmarketplaces) and [extraKnownMarketplaces](/en/settings#extraknownmarketplaces) settings reference for the complete schema.

157 

158## Limitations

159 

160A few features behave differently on GHES than on github.com. The [feature table](#what-works-with-github-enterprise-server) summarizes support; this section covers the workarounds.

161 

162* **`/install-github-app` command**: follow the [admin setup](#admin-setup) flow on claude.ai instead. If you also want GitHub Actions workflows on GHES, adapt the [example workflow](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) manually.

163* **GitHub MCP server**: use the `gh` CLI configured for your GHES host instead. Run `gh auth login --hostname github.example.com` to authenticate, then Claude can use `gh` commands in sessions.

164 

165## Troubleshooting

166 

167### Web session fails to clone repository

168 

169If `claude --remote` fails with a clone error, verify that your admin has completed setup for your GHES instance and that the GitHub App is installed on the repository you're working in. Check with your admin that the instance hostname registered in Claude settings matches the hostname in your git remote.

170 

171### Marketplace add fails with a policy error

172 

173If `/plugin marketplace add` is blocked for your GHES URL, your organization has restricted marketplace sources. Ask your admin to add a `hostPattern` entry for your GHES hostname in [managed settings](#allowlist-ghes-marketplaces-in-managed-settings).

174 

175### GHES instance not reachable

176 

177If reviews or web sessions time out, your GHES instance may not be reachable from Anthropic infrastructure. Confirm your firewall allows inbound connections from the [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).

178 

179## Related resources

180 

181These pages cover the features referenced throughout this guide in more depth:

182 

183* [Claude Code on the web](/en/claude-code-on-the-web): run Claude Code sessions on cloud infrastructure

184* [Code Review](/en/code-review): automated PR reviews

185* [Plugin marketplaces](/en/plugin-marketplaces): build and distribute plugin catalogs

186* [Analytics](/en/analytics): track usage and contribution metrics

187* [Managed settings](/en/settings): organization-wide policy configuration

188* [Network configuration](/en/network-config): firewall and IP allowlist requirements

gitlab-ci-cd.md +20 −16

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code GitLab CI/CD5# Claude Code GitLab CI/CD

2 6 

3> Learn about integrating Claude Code into your development workflow with GitLab CI/CD7> Learn about integrating Claude Code into your development workflow with GitLab CI/CD


9</Info>13</Info>

10 14 

11<Note>15<Note>

12 This integration is built on top of the [Claude Code CLI and SDK](/en/docs/claude-code/sdk), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.16 This integration is built on top of the [Claude Code CLI and Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.

13</Note>17</Note>

14 18 

15## Why use Claude Code with GitLab?19## Why use Claude Code with GitLab?


77 before_script:81 before_script:

78 - apk update82 - apk update

79 - apk add --no-cache git curl bash83 - apk add --no-cache git curl bash

80 - npm install -g @anthropic-ai/claude-code84 - curl -fsSL https://claude.ai/install.sh | bash

81 script:85 script:

82 # Optional: start a GitLab MCP server if your setup provides one86 # Optional: start a GitLab MCP server if your setup provides one

83 - /bin/gitlab-mcp-server || true87 - /bin/gitlab-mcp-server || true


87 claude91 claude

88 -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"92 -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"

89 --permission-mode acceptEdits93 --permission-mode acceptEdits

90 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"94 --allowedTools "Bash Read Edit Write mcp__gitlab"

91 --debug95 --debug

92```96```

93 97 


122 126 

123In an issue comment:127In an issue comment:

124 128 

125```129```text theme={null}

126@claude implement this feature based on the issue description130@claude implement this feature based on the issue description

127```131```

128 132 


132 136 

133In an MR discussion:137In an MR discussion:

134 138 

135```139```text theme={null}

136@claude suggest a concrete approach to cache the results of this API call140@claude suggest a concrete approach to cache the results of this API call

137```141```

138 142 


142 146 

143In an issue or MR comment:147In an issue or MR comment:

144 148 

145```149```text theme={null}

146@claude fix the TypeError in the user dashboard component150@claude fix the TypeError in the user dashboard component

147```151```

148 152 


255 before_script:259 before_script:

256 - apk update260 - apk update

257 - apk add --no-cache git curl bash261 - apk add --no-cache git curl bash

258 - npm install -g @anthropic-ai/claude-code262 - curl -fsSL https://claude.ai/install.sh | bash

259 script:263 script:

260 - /bin/gitlab-mcp-server || true264 - /bin/gitlab-mcp-server || true

261 - >265 - >

262 claude266 claude

263 -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"267 -p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"

264 --permission-mode acceptEdits268 --permission-mode acceptEdits

265 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"269 --allowedTools "Bash Read Edit Write mcp__gitlab"

266 --debug270 --debug

267 # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables271 # Claude Code will use ANTHROPIC_API_KEY from CI/CD variables

268```272```


289 before_script:293 before_script:

290 - apk add --no-cache bash curl jq git python3 py3-pip294 - apk add --no-cache bash curl jq git python3 py3-pip

291 - pip install --no-cache-dir awscli295 - pip install --no-cache-dir awscli

292 - npm install -g @anthropic-ai/claude-code296 - curl -fsSL https://claude.ai/install.sh | bash

293 # Exchange GitLab OIDC token for AWS credentials297 # Exchange GitLab OIDC token for AWS credentials

294 - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"298 - export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"

295 - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi299 - if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi


308 claude312 claude

309 -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"313 -p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"

310 --permission-mode acceptEdits314 --permission-mode acceptEdits

311 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"315 --allowedTools "Bash Read Edit Write mcp__gitlab"

312 --debug316 --debug

313 variables:317 variables:

314 AWS_REGION: "us-west-2"318 AWS_REGION: "us-west-2"

315```319```

316 320 

317<Note>321<Note>

318 Model IDs for Bedrock include region-specific prefixes and version suffixes (for example, `us.anthropic.claude-sonnet-4-5-20250929-v1:0`). Pass the desired model via your job configuration or prompt if your workflow supports it.322 Model IDs for Bedrock include region-specific prefixes (for example, `us.anthropic.claude-sonnet-4-6`). Pass the desired model via your job configuration or prompt if your workflow supports it.

319</Note>323</Note>

320 324 

321### Google Vertex AI job example (Workload Identity Federation)325### Google Vertex AI job example (Workload Identity Federation)


339 rules:343 rules:

340 - if: '$CI_PIPELINE_SOURCE == "web"'344 - if: '$CI_PIPELINE_SOURCE == "web"'

341 before_script:345 before_script:

342 - apt-get update && apt-get install -y git nodejs npm && apt-get clean346 - apt-get update && apt-get install -y git && apt-get clean

343 - npm install -g @anthropic-ai/claude-code347 - curl -fsSL https://claude.ai/install.sh | bash

344 # Authenticate to Google Cloud via WIF (no downloaded keys)348 # Authenticate to Google Cloud via WIF (no downloaded keys)

345 - >349 - >

346 gcloud auth login --cred-file=<(cat <<EOF350 gcloud auth login --cred-file=<(cat <<EOF


361 claude365 claude

362 -p "${AI_FLOW_INPUT:-'Review and update code as requested'}"366 -p "${AI_FLOW_INPUT:-'Review and update code as requested'}"

363 --permission-mode acceptEdits367 --permission-mode acceptEdits

364 --allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"368 --allowedTools "Bash Read Edit Write mcp__gitlab"

365 --debug369 --debug

366 variables:370 variables:

367 CLOUD_ML_REGION: "us-east5"371 CLOUD_ML_REGION: "us-east5"


379 383 

380### Security considerations384### Security considerations

381 385 

382Never commit API keys or cloud credentials to your repository! Always use GitLab CI/CD variables:386**Never commit API keys or cloud credentials to your repository**. Always use GitLab CI/CD variables:

383 387 

384* Add `ANTHROPIC_API_KEY` as a masked variable (and protect it if needed)388* Add `ANTHROPIC_API_KEY` as a masked variable (and protect it if needed)

385* Use provider-specific OIDC where possible (no long-lived keys)389* Use provider-specific OIDC where possible (no long-lived keys)


404* **API costs**:408* **API costs**:

405 * Each Claude interaction consumes tokens based on prompt and response size409 * Each Claude interaction consumes tokens based on prompt and response size

406 * Token usage varies by task complexity and codebase size410 * Token usage varies by task complexity and codebase size

407 * See [Anthropic pricing](/en/docs/about-claude/pricing) for details411 * See [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing) for details

408 412 

409* **Cost optimization tips**:413* **Cost optimization tips**:

410 * Use specific `@claude` commands to reduce unnecessary turns414 * Use specific `@claude` commands to reduce unnecessary turns

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code on Google Vertex AI5# Claude Code on Google Vertex AI

2 6 

3> Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting.7> Learn about configuring Claude Code through Google Vertex AI, including setup, IAM configuration, and troubleshooting.


8 12 

9* A Google Cloud Platform (GCP) account with billing enabled13* A Google Cloud Platform (GCP) account with billing enabled

10* A GCP project with Vertex AI API enabled14* A GCP project with Vertex AI API enabled

11* Access to desired Claude models (e.g., Claude Sonnet 4.5)15* Access to desired Claude models (for example, Claude Sonnet 4.6)

12* Google Cloud SDK (`gcloud`) installed and configured16* Google Cloud SDK (`gcloud`) installed and configured

13* Quota allocated in desired GCP region17* Quota allocated in desired GCP region

14 18 

19<Note>

20 If you are deploying Claude Code to multiple users, [pin your model versions](#5-pin-model-versions) to prevent breakage when Anthropic releases new models.

21</Note>

22 

15## Region Configuration23## Region Configuration

16 24 

17Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.25Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.

18 26 

19<Note>27<Note>

20 Vertex AI may not support the Claude Code default models on all regions. You may need to switch to a [supported region or model](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models).28 Vertex AI may not support the Claude Code default models in all [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models) or on [global endpoints](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models). You may need to switch to a supported region, use a regional endpoint, or specify a supported model.

21</Note>

22 

23<Note>

24 Vertex AI may not support the Claude Code default models on global endpoints. You may need to switch to a regional endpoint or [supported model](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models).

25</Note>29</Note>

26 30 

27## Setup31## Setup


44 48 

451. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)491. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)

462. Search for "Claude" models502. Search for "Claude" models

473. Request access to desired Claude models (e.g., Claude Sonnet 4.5)513. Request access to desired Claude models (for example, Claude Sonnet 4.6)

484. Wait for approval (may take 24-48 hours)524. Wait for approval (may take 24-48 hours)

49 53 

50### 3. Configure GCP credentials54### 3. Configure GCP credentials


67export CLOUD_ML_REGION=global71export CLOUD_ML_REGION=global

68export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID72export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID

69 73 

74# Optional: Override the Vertex endpoint URL for custom endpoints or gateways

75# export ANTHROPIC_VERTEX_BASE_URL=https://aiplatform.googleapis.com

76 

70# Optional: Disable prompt caching if needed77# Optional: Disable prompt caching if needed

71export DISABLE_PROMPT_CACHING=178export DISABLE_PROMPT_CACHING=1

72 79 

73# When CLOUD_ML_REGION=global, override region for unsupported models80# When CLOUD_ML_REGION=global, override region for models that don't support global endpoints

74export VERTEX_REGION_CLAUDE_3_5_HAIKU=us-east581export VERTEX_REGION_CLAUDE_HAIKU_4_5=us-east5

75 82export VERTEX_REGION_CLAUDE_4_6_SONNET=europe-west1

76# Optional: Override regions for other specific models

77export VERTEX_REGION_CLAUDE_3_5_SONNET=us-east5

78export VERTEX_REGION_CLAUDE_3_7_SONNET=us-east5

79export VERTEX_REGION_CLAUDE_4_0_OPUS=europe-west1

80export VERTEX_REGION_CLAUDE_4_0_SONNET=us-east5

81export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1

82```83```

83 84 

84<Note>85Most 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.

85 [Prompt caching](/en/docs/build-with-claude/prompt-caching) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support.

86</Note>

87 86 

88<Note>87[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.

89 When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials.88 

90</Note>89### 5. Pin model versions

90 

91<Warning>

92 Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn't enabled in your Vertex AI project, breaking existing users when Anthropic releases updates.

93</Warning>

94 

95Set these environment variables to specific Vertex AI model IDs:

96 

97```bash theme={null}

98export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'

99export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

100export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

101```

91 102 

92### 5. Model configuration103For 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.

93 104 

94Claude Code uses these default models for Vertex AI:105Claude Code uses these default models when no pinning variables are set:

95 106 

96| Model type | Default value |107| Model type | Default value |

97| :--------------- | :--------------------------- |108| :--------------- | :--------------------------- |

98| Primary model | `claude-sonnet-4-5@20250929` |109| Primary model | `claude-sonnet-4-5@20250929` |

99| Small/fast model | `claude-haiku-4-5@20251001` |110| Small/fast model | `claude-haiku-4-5@20251001` |

100 111 

101<Note>112To customize models further:

102 For Vertex AI users, Claude Code will not automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (e.g., `claude-haiku-4-5@20251001`).

103</Note>

104 

105To customize models:

106 113 

107```bash theme={null}114```bash theme={null}

108export ANTHROPIC_MODEL='claude-opus-4-1@20250805'115export ANTHROPIC_MODEL='claude-opus-4-6'

109export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'116export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5@20251001'

110```117```

111 118 

112## IAM configuration119## IAM configuration


122For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).129For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).

123 130 

124<Note>131<Note>

125 We recommend creating a dedicated GCP project for Claude Code to simplify cost tracking and access control.132 Create a dedicated GCP project for Claude Code to simplify cost tracking and access control.

126</Note>133</Note>

127 134 

128## 1M token context window135## 1M token context window

129 136 

130Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](/en/docs/build-with-claude/context-windows#1m-token-context-window) on Vertex AI.137Claude Opus 4.6, Sonnet 4.6, Sonnet 4.5, and Sonnet 4 support the [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) on Vertex AI. Claude Code automatically enables the extended context window when you select a 1M model variant.

131 138 

132<Note>139To enable the 1M context window for your pinned model, append `[1m]` to the model ID. See [Pin models for third-party deployments](/en/model-config#pin-models-for-third-party-deployments) for details.

133 The 1M token context window is currently in beta. To use the extended context window, include the `context-1m-2025-08-07` beta header in your Vertex AI requests.

134</Note>

135 140 

136## Troubleshooting141## Troubleshooting

137 142 


144* Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)149* Confirm model is Enabled in [Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)

145* Verify you have access to the specified region150* Verify you have access to the specified region

146* 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:151* 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:

147 * Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_SMALL_FAST_MODEL`, or152 * Specify a supported model via `ANTHROPIC_MODEL` or `ANTHROPIC_DEFAULT_HAIKU_MODEL`, or

148 * Set a regional endpoint using `VERTEX_REGION_<MODEL_NAME>` environment variables153 * Set a regional endpoint using `VERTEX_REGION_<MODEL_NAME>` environment variables

149 154 

150If you encounter 429 errors:155If you encounter 429 errors:

headless.md +137 −135

Details

1# Headless mode1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Run Claude Code programmatically without interactive UI5# Run Claude Code programmatically

4 6 

5## Overview7> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.

6 8 

7The headless mode allows you to run Claude Code programmatically from command line scripts and automation tools without any interactive UI.9The [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) gives you the same tools, agent loop, and context management that power Claude Code. It's available as a CLI for scripts and CI/CD, or as [Python](https://platform.claude.com/docs/en/agent-sdk/python) and [TypeScript](https://platform.claude.com/docs/en/agent-sdk/typescript) packages for full programmatic control.

8 10 

9## Basic usage11<Note>

12 The CLI was previously called "headless mode." The `-p` flag and all CLI options work the same way.

13</Note>

10 14 

11The primary command-line interface to Claude Code is the `claude` command. Use the `--print` (or `-p`) flag to run in non-interactive mode and print the final result:15To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](/en/cli-reference):

12 16 

13```bash theme={null}17```bash theme={null}

14claude -p "Stage my changes and write a set of commits for them" \18claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"

15 --allowedTools "Bash,Read" \

16 --permission-mode acceptEdits

17```19```

18 20 

19## Configuration Options21This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview).

20 

21Headless mode leverages all the CLI options available in Claude Code. Here are the key ones for automation and scripting:

22 22 

23| Flag | Description | Example |23## Basic usage

24| :------------------------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |

25| `--print`, `-p` | Run in non-interactive mode | `claude -p "query"` |

26| `--output-format` | Specify output format (`text`, `json`, `stream-json`) | `claude -p --output-format json` |

27| `--resume`, `-r` | Resume a conversation by session ID | `claude --resume abc123` |

28| `--continue`, `-c` | Continue the most recent conversation | `claude --continue` |

29| `--verbose` | Enable verbose logging | `claude --verbose` |

30| `--append-system-prompt` | Append to system prompt (only with `--print`) | `claude --append-system-prompt "Custom instruction"` |

31| `--allowedTools` | Space-separated list of allowed tools, or <br /><br /> string of comma-separated list of allowed tools | `claude --allowedTools mcp__slack mcp__filesystem`<br /><br />`claude --allowedTools "Bash(npm install),mcp__filesystem"` |

32| `--disallowedTools` | Space-separated list of denied tools, or <br /><br /> string of comma-separated list of denied tools | `claude --disallowedTools mcp__splunk mcp__github`<br /><br />`claude --disallowedTools "Bash(git commit),mcp__github"` |

33| `--mcp-config` | Load MCP servers from a JSON file | `claude --mcp-config servers.json` |

34| `--permission-prompt-tool` | MCP tool for handling permission prompts (only with `--print`) | `claude --permission-prompt-tool mcp__auth__prompt` |

35 24 

36For a complete list of CLI options and features, see the [CLI reference](/en/docs/claude-code/cli-reference) documentation.25Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All [CLI options](/en/cli-reference) work with `-p`, including:

37 26 

38## Multi-turn conversations27* `--continue` for [continuing conversations](#continue-conversations)

28* `--allowedTools` for [auto-approving tools](#auto-approve-tools)

29* `--output-format` for [structured output](#get-structured-output)

39 30 

40For multi-turn conversations, you can resume conversations or continue from the most recent session:31This example asks Claude a question about your codebase and prints the response:

41 32 

42```bash theme={null}33```bash theme={null}

43# Continue the most recent conversation34claude -p "What does the auth module do?"

44claude --continue "Now refactor this for better performance"35```

45 36 

46# Resume a specific conversation by session ID37### Start faster with bare mode

47claude --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests"

48 38 

49# Resume in non-interactive mode39Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](/en/how-claude-code-works#the-context-window) an interactive session would, including anything configured in the working directory or `~/.claude`.

50claude --resume 550e8400-e29b-41d4-a716-446655440000 "Fix all linting issues" --no-interactive

51```

52 40 

53## Output Formats41Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate's `~/.claude` or an MCP server in the project's `.mcp.json` won't run, because bare mode never reads them. Only flags you pass explicitly take effect.

54 42 

55### Text Output (Default)43This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt:

56 44 

57```bash theme={null}45```bash theme={null}

58claude -p "Explain file src/components/Header.tsx"46claude --bare -p "Summarize this file" --allowedTools "Read"

59# Output: This is a React component showing...

60```47```

61 48 

62### JSON Output49In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag:

63 50 

64Returns structured data including metadata:51| To load | Use |

52| ----------------------- | ------------------------------------------------------- |

53| System prompt additions | `--append-system-prompt`, `--append-system-prompt-file` |

54| Settings | `--settings <file-or-json>` |

55| MCP servers | `--mcp-config <file-or-json>` |

56| Custom agents | `--agents <json>` |

57| A plugin directory | `--plugin-dir <path>` |

65 58 

66```bash theme={null}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.

67claude -p "How does the data layer work?" --output-format json

68```

69 60 

70Response format:61<Note>

71 62 `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release.

72```json theme={null}63</Note>

73{

74 "type": "result",

75 "subtype": "success",

76 "total_cost_usd": 0.003,

77 "is_error": false,

78 "duration_ms": 1234,

79 "duration_api_ms": 800,

80 "num_turns": 6,

81 "result": "The response text here...",

82 "session_id": "abc123"

83}

84```

85 64 

86### Streaming JSON Output65## Examples

87 66 

88Streams each message as it is received: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.

89 68 

90```bash theme={null}69### Get structured output

91claude -p "Build an application" --output-format stream-json

92```

93 70 

94Each conversation begins with an initial `init` system message, followed by a list of user and assistant messages, followed by a final `result` system message with stats. Each message is emitted as a separate JSON object.71Use `--output-format` to control how responses are returned:

95 72 

96## Input Formats73* `text` (default): plain text output

74* `json`: structured JSON with result, session ID, and metadata

75* `stream-json`: newline-delimited JSON for real-time streaming

97 76 

98### Text Input (Default)77This example returns a project summary as JSON with session metadata, with the text result in the `result` field:

99 78 

100```bash theme={null}79```bash theme={null}

101# Direct argument80claude -p "Summarize this project" --output-format json

102claude -p "Explain this code"

103 

104# From stdin

105echo "Explain this code" | claude -p

106```81```

107 82 

108### Streaming JSON Input83To get output conforming to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](https://json-schema.org/) definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the `structured_output` field.

109 84 

110A stream of messages provided via `stdin` where each message represents a user turn. This allows multiple turns of a conversation without re-launching the `claude` binary and allows providing guidance to the model while it is processing a request.85This example extracts function names and returns them as an array of strings:

111 

112Each message is a JSON 'User message' object, following the same format as the output message schema. Messages are formatted using the [jsonl](https://jsonlines.org/) format where each line of input is a complete JSON object. Streaming JSON input requires `-p` and `--output-format stream-json`.

113 86 

114```bash theme={null}87```bash theme={null}

115echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' | claude -p --output-format=stream-json --input-format=stream-json --verbose88claude -p "Extract the main function names from auth.py" \

89 --output-format json \

90 --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

116```91```

117 92 

118## Agent Integration Examples93<Tip>

94 Use a tool like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields:

119 95 

120### SRE Incident Response Bot96 ```bash theme={null}

97 # Extract the text result

98 claude -p "Summarize this project" --output-format json | jq -r '.result'

121 99 

122```bash theme={null}100 # Extract structured output

123#!/bin/bash101 claude -p "Extract function names from auth.py" \

102 --output-format json \

103 --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \

104 | jq '.structured_output'

105 ```

106</Tip>

124 107 

125# Automated incident response agent108### Stream responses

126investigate_incident() {

127 local incident_description="$1"

128 local severity="${2:-medium}"

129 109 

130 claude -p "Incident: $incident_description (Severity: $severity)" \110Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they're generated. Each line is a JSON object representing an event:

131 --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \

132 --output-format json \

133 --allowedTools "Bash,Read,WebSearch,mcp__datadog" \

134 --mcp-config monitoring-tools.json

135}

136 111 

137# Usage112```bash theme={null}

138investigate_incident "Payment API returning 500 errors" "high"113claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages

139```114```

140 115 

141### Automated Security Review116The following example uses [jq](https://jqlang.github.io/jq/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:

142 117 

143```bash theme={null}118```bash theme={null}

144# Security audit agent for pull requests119claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \

145audit_pr() {120 jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

146 local pr_number="$1"121```

147 122 

148 gh pr diff "$pr_number" | claude -p \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.

149 --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \124 

150 --output-format json \125| Field | Type | Description |

151 --allowedTools "Read,Grep,WebSearch"126| ---------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |

152}127| `type` | `"system"` | message type |

128| `subtype` | `"api_retry"` | identifies this as a retry event |

129| `attempt` | integer | current attempt number, starting at 1 |

130| `max_retries` | integer | total retries permitted |

131| `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 |

133| `error` | string | error category: `authentication_failed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |

134| `uuid` | string | unique event identifier |

135| `session_id` | string | session the event belongs to |

136 

137For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](https://platform.claude.com/docs/en/agent-sdk/streaming-output) in the Agent SDK documentation.

153 138 

154# Usage and save to file139### Auto-approve tools

155audit_pr 123 > security-report.json140 

141Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:

142 

143```bash theme={null}

144claude -p "Run the test suite and fix any failures" \

145 --allowedTools "Bash,Read,Edit"

156```146```

157 147 

158### Multi-turn Legal Assistant148To 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, but shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted:

159 149 

160```bash theme={null}150```bash theme={null}

161# Legal document review with session persistence151claude -p "Apply the lint fixes" --permission-mode acceptEdits

162session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id')152```

153 

154### Create a commit

155 

156This example reviews staged changes and creates a commit with an appropriate message:

163 157 

164# Review contract in multiple steps158```bash theme={null}

165claude -p --resume "$session_id" "Review contract.pdf for liability clauses"159claude -p "Look at my staged changes and create an appropriate commit" \

166claude -p --resume "$session_id" "Check compliance with GDPR requirements"160 --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

167claude -p --resume "$session_id" "Generate executive summary of risks"

168```161```

169 162 

170## Best Practices163The `--allowedTools` flag uses [permission rule syntax](/en/settings#permission-rule-syntax). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`.

171 164 

172* **Use JSON output format** for programmatic parsing of responses:165<Note>

166 User-invoked [skills](/en/skills) like `/commit` and [built-in commands](/en/commands) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.

167</Note>

173 168 

174 ```bash theme={null}169### Customize the system prompt

175 # Parse JSON response with jq

176 result=$(claude -p "Generate code" --output-format json)

177 code=$(echo "$result" | jq -r '.result')

178 cost=$(echo "$result" | jq -r '.cost_usd')

179 ```

180 170 

181* **Handle errors gracefully** - check exit codes and stderr:171Use `--append-system-prompt` to add instructions while keeping Claude Code's default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities:

182 172 

183 ```bash theme={null}173```bash theme={null}

184 if ! claude -p "$prompt" 2>error.log; then174gh pr diff "$1" | claude -p \

185 echo "Error occurred:" >&2175 --append-system-prompt "You are a security engineer. Review for vulnerabilities." \

186 cat error.log >&2176 --output-format json

187 exit 1177```

188 fi

189 ```

190 178 

191* **Use session management** for maintaining context in multi-turn conversations179See [system prompt flags](/en/cli-reference#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt.

192 180 

193* **Consider timeouts** for long-running operations:181### Continue conversations

194 182 

195 ```bash theme={null}183Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts:

196 timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"

197 ```

198 184 

199* **Respect rate limits** when making multiple requests by adding delays between calls185```bash theme={null}

186# First request

187claude -p "Review this codebase for performance issues"

188 

189# Continue the most recent conversation

190claude -p "Now focus on the database queries" --continue

191claude -p "Generate a summary of all issues found" --continue

192```

193 

194If you're running multiple conversations, capture the session ID to resume a specific one:

195 

196```bash theme={null}

197session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')

198claude -p "Continue that review" --resume "$session_id"

199```

200 200 

201## Related Resources201## Next steps

202 202 

203* [CLI usage and controls](/en/docs/claude-code/cli-reference) - Complete CLI documentation203* [Agent SDK quickstart](https://platform.claude.com/docs/en/agent-sdk/quickstart): build your first agent with Python or TypeScript

204* [Common workflows](/en/docs/claude-code/common-workflows) - Step-by-step guides for common use cases204* [CLI reference](/en/cli-reference): all CLI flags and options

205* [GitHub Actions](/en/github-actions): use the Agent SDK in GitHub workflows

206* [GitLab CI/CD](/en/gitlab-ci-cd): use the Agent SDK in GitLab pipelines

hooks.md +1934 −703

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Hooks reference5# Hooks reference

2 6 

3> This page provides reference documentation for implementing hooks in Claude Code.7> Reference for Claude Code hook events, configuration schema, JSON input/output formats, exit codes, async hooks, HTTP hooks, prompt hooks, and MCP tool hooks.

4 8 

5<Tip>9<Tip>

6 For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/docs/claude-code/hooks-guide).10 For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide).

7</Tip>11</Tip>

8 12 

9## Configuration13Hooks are user-defined shell commands, HTTP endpoints, or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks, HTTP hooks, and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead.

10 14 

11Claude Code hooks are configured in your [settings files](/en/docs/claude-code/settings):15## Hook lifecycle

12 16 

13* `~/.claude/settings.json` - User settings17Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, input arrives on stdin. For HTTP hooks, it arrives as the POST request body. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:

14* `.claude/settings.json` - Project settings18 

15* `.claude/settings.local.json` - Local project settings (not committed)19<div style={{maxWidth: "500px", margin: "0 auto"}}>

16* Enterprise managed policy settings20 <Frame>

17 21 <img src="https://mintcdn.com/claude-code/WLZtXlltXc8aIoIM/images/hooks-lifecycle.svg?fit=max&auto=format&n=WLZtXlltXc8aIoIM&q=85&s=6a0bf67eeb570a96e36b564721fa2a93" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop (PreToolUse, PermissionRequest, PostToolUse, SubagentStart/Stop, TaskCreated, TaskCompleted) to Stop or StopFailure, 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" />

18### Structure22 </Frame>

19 23</div>

20Hooks are organized by matchers, where each matcher can have multiple hooks: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.

26 

27| Event | When it fires |

28| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

29| `SessionStart` | When a session begins or resumes |

30| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

31| `PreToolUse` | Before a tool call executes. Can block it |

32| `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 |

34| `PostToolUse` | After a tool call succeeds |

35| `PostToolUseFailure` | After a tool call fails |

36| `Notification` | When Claude Code sends a notification |

37| `SubagentStart` | When a subagent is spawned |

38| `SubagentStop` | When a subagent finishes |

39| `TaskCreated` | When a task is being created via `TaskCreate` |

40| `TaskCompleted` | When a task is being marked as completed |

41| `Stop` | When Claude finishes responding |

42| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |

43| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

44| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

45| `ConfigChange` | When a configuration file changes during a session |

46| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |

47| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |

48| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

49| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

50| `PreCompact` | Before context compaction |

51| `PostCompact` | After context compaction completes |

52| `Elicitation` | When an MCP server requests user input during a tool call |

53| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

54| `SessionEnd` | When a session terminates |

55 

56### How a hook resolves

57 

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:

21 59 

22```json theme={null}60```json theme={null}

23{61{

24 "hooks": {62 "hooks": {

25 "EventName": [63 "PreToolUse": [

26 {64 {

27 "matcher": "ToolPattern",65 "matcher": "Bash",

28 "hooks": [66 "hooks": [

29 {67 {

30 "type": "command",68 "type": "command",

31 "command": "your-command-here"69 "if": "Bash(rm *)",

70 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh"

32 }71 }

33 ]72 ]

34 }73 }


37}76}

38```77```

39 78 

40* **matcher**: Pattern to match tool names, case-sensitive (only applicable for79The script reads the JSON input from stdin, extracts the command, and returns a `permissionDecision` of `"deny"` if it contains `rm -rf`:

41 `PreToolUse` and `PostToolUse`)

42 * Simple strings match exactly: `Write` matches only the Write tool

43 * Supports regex: `Edit|Write` or `Notebook.*`

44 * Use `*` to match all tools. You can also use empty string (`""`) or leave

45 `matcher` blank.

46* **hooks**: Array of hooks to execute when the pattern matches

47 * `type`: Hook execution type - `"command"` for bash commands or `"prompt"` for LLM-based evaluation

48 * `command`: (For `type: "command"`) The bash command to execute (can use `$CLAUDE_PROJECT_DIR` environment variable)

49 * `prompt`: (For `type: "prompt"`) The prompt to send to the LLM for evaluation

50 * `timeout`: (Optional) How long a hook should run, in seconds, before canceling that specific hook

51 80 

52For events like `UserPromptSubmit`, `Notification`, `Stop`, and `SubagentStop`81```bash theme={null}

53that don't use matchers, you can omit the matcher field:82#!/bin/bash

83# .claude/hooks/block-rm.sh

84COMMAND=$(jq -r '.tool_input.command')

85 

86if echo "$COMMAND" | grep -q 'rm -rf'; then

87 jq -n '{

88 hookSpecificOutput: {

89 hookEventName: "PreToolUse",

90 permissionDecision: "deny",

91 permissionDecisionReason: "Destructive command blocked by hook"

92 }

93 }'

94else

95 exit 0 # allow the command

96fi

97```

54 98 

55```json theme={null}99Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:

56{100 

57 "hooks": {101<Frame>

58 "UserPromptSubmit": [102 <img src="https://mintcdn.com/claude-code/-tYw1BD_DEqfyyOZ/images/hook-resolution.svg?fit=max&auto=format&n=-tYw1BD_DEqfyyOZ&q=85&s=c73ebc1eeda2037570427d7af1e0a891" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, if condition checks for Bash(rm *) match, hook handler runs, result returns to Claude Code" width="930" height="290" data-path="images/hook-resolution.svg" />

59 {103</Frame>

60 "hooks": [104 

105<Steps>

106 <Step title="Event fires">

107 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:

108 

109 ```json theme={null}

110 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }

111 ```

112 </Step>

113 

114 <Step title="Matcher checks">

115 The matcher `"Bash"` matches the tool name, so this hook group activates. If you omit the matcher or use `"*"`, the group activates on every occurrence of the event.

116 </Step>

117 

118 <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.

120 </Step>

121 

122 <Step title="Hook handler runs">

123 The script inspects the full command and finds `rm -rf`, so it prints a decision to stdout:

124 

125 ```json theme={null}

61 {126 {

62 "type": "command",127 "hookSpecificOutput": {

63 "command": "/path/to/prompt-validator.py"128 "hookEventName": "PreToolUse",

64 }129 "permissionDecision": "deny",

65 ]130 "permissionDecisionReason": "Destructive command blocked by hook"

66 }131 }

67 ]

68 }132 }

69}133 ```

70```

71 134 

72### Project-Specific Hook Scripts135 If the command had been a safer `rm` variant like `rm file.txt`, the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.

136 </Step>

73 137 

74You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when138 <Step title="Claude Code acts on the result">

75Claude Code spawns the hook command) to reference scripts stored in your project,139 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.

76ensuring they work regardless of Claude's current directory:140 </Step>

141</Steps>

142 

143The [Configuration](#configuration) section below documents the full schema, and each [hook event](#hook-events) section documents what input your command receives and what output it can return.

144 

145## Configuration

146 

147Hooks are defined in JSON settings files. The configuration has three levels of nesting:

148 

1491. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`

1502. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"

1513. Define one or more [hook handlers](#hook-handler-fields) to run when matched

152 

153See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.

154 

155<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.

157</Note>

158 

159### Hook locations

160 

161Where you define a hook determines its scope:

162 

163| Location | Scope | Shareable |

164| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |

165| `~/.claude/settings.json` | All your projects | No, local to your machine |

166| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

167| `.claude/settings.local.json` | Single project | No, gitignored |

168| Managed policy settings | Organization-wide | Yes, admin-controlled |

169| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

170| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |

171 

172For details on settings file resolution, see [settings](/en/settings). Enterprise administrators can use `allowManagedHooksOnly` to block user, project, and plugin hooks. See [Hook configuration](/en/settings#hook-configuration).

173 

174### Matcher patterns

175 

176The `matcher` field is a regex string that filters when hooks fire. Use `"*"`, `""`, or omit `matcher` entirely to match all occurrences. Each event type matches on a different field:

177 

178| Event | What the matcher filters | Example matcher values |

179| :------------------------------------------------------------------------------------------------------------- | :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |

180| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

181| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

182| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

183| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

184| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

185| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |

186| `SubagentStop` | agent type | same values as `SubagentStart` |

187| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

188| `CwdChanged` | no matcher support | always fires on every directory change |

189| `FileChanged` | filename (basename of the changed file) | `.envrc`, `.env`, any filename you want to watch |

190| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |

191| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |

192| `Elicitation` | MCP server name | your configured MCP server names |

193| `ElicitationResult` | MCP server name | same values as `Elicitation` |

194| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove` | no matcher support | always fires on every occurrence |

195 

196The matcher is a regex, so `Edit|Write` matches either tool and `Notebook.*` matches any tool starting with Notebook. The matcher runs against a field from the [JSON input](#hook-input-and-output) that Claude Code sends to your hook on stdin. For tool events, that field is `tool_name`. Each [hook event](#hook-events) section lists the full set of matcher values and the input schema for that event.

197 

198This example runs a linting script only when Claude writes or edits a file:

77 199 

78```json theme={null}200```json theme={null}

79{201{

80 "hooks": {202 "hooks": {

81 "PostToolUse": [203 "PostToolUse": [

82 {204 {

83 "matcher": "Write|Edit",205 "matcher": "Edit|Write",

84 "hooks": [206 "hooks": [

85 {207 {

86 "type": "command",208 "type": "command",

87 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"209 "command": "/path/to/lint-check.sh"

88 }210 }

89 ]211 ]

90 }212 }


93}215}

94```216```

95 217 

96### Plugin hooks218`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.

219 

220For 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.

221 

222#### Match MCP tools

223 

224[MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied`), so you can match them the same way you match any other tool name.

225 

226MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:

97 227 

98[Plugins](/en/docs/claude-code/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled.228* `mcp__memory__create_entities`: Memory server's create entities tool

229* `mcp__filesystem__read_file`: Filesystem server's read file tool

230* `mcp__github__search_repositories`: GitHub server's search tool

99 231 

100**How plugin hooks work**:232Use regex patterns to target specific MCP tools or groups of tools:

101 233 

102* Plugin hooks are defined in the plugin's `hooks/hooks.json` file or in a file given by a custom path to the `hooks` field.234* `mcp__memory__.*` matches all tools from the `memory` server

103* When a plugin is enabled, its hooks are merged with user and project hooks235* `mcp__.*__write.*` matches any tool containing "write" from any server

104* Multiple hooks from different sources can respond to the same event

105* Plugin hooks use the `${CLAUDE_PLUGIN_ROOT}` environment variable to reference plugin files

106 236 

107**Example plugin hook configuration**:237This example logs all memory server operations and validates write operations from any MCP server:

108 238 

109```json theme={null}239```json theme={null}

110{240{

111 "description": "Automatic code formatting",

112 "hooks": {241 "hooks": {

113 "PostToolUse": [242 "PreToolUse": [

114 {243 {

115 "matcher": "Write|Edit",244 "matcher": "mcp__memory__.*",

116 "hooks": [245 "hooks": [

117 {246 {

118 "type": "command",247 "type": "command",

119 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",248 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

120 "timeout": 30249 }

250 ]

251 },

252 {

253 "matcher": "mcp__.*__write.*",

254 "hooks": [

255 {

256 "type": "command",

257 "command": "/home/user/scripts/validate-mcp-write.py"

121 }258 }

122 ]259 ]

123 }260 }


126}263}

127```264```

128 265 

129<Note>266### Hook handler fields

130 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.

131</Note>

132 267 

133<Note>268Each 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:

134 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.

135</Note>

136 269 

137**Environment variables for plugins**:270* **[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.

271* **[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.

272* **[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).

273* **[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).

138 274 

139* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory275#### Common fields

140* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)

141* All standard environment variables are available

142 276 

143See the [plugin components reference](/en/docs/claude-code/plugins-reference#hooks) for details on creating plugin hooks.277These fields apply to all hook types:

144 278 

145## Prompt-Based Hooks279| Field | Required | Description |

280| :-------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

281| `type` | yes | `"command"`, `"http"`, `"prompt"`, or `"agent"` |

282| `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) |

283| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |

284| `statusMessage` | no | Custom spinner message displayed while the hook runs |

285| `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) |

146 286 

147In addition to bash command hooks (`type: "command"`), Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action. Prompt-based hooks are currently only supported for `Stop` and `SubagentStop` hooks, where they enable intelligent, context-aware decisions.287#### Command hook fields

148 288 

149### How prompt-based hooks work289In addition to the [common fields](#common-fields), command hooks accept these fields:

150 290 

151Instead of executing a bash command, prompt-based hooks:291| Field | Required | Description |

292| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

293| `command` | yes | Shell command to execute |

294| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |

295| `shell` | no | Shell to use for this hook. Accepts `"bash"` (default) or `"powershell"`. Setting `"powershell"` runs the command via PowerShell on Windows. Does not require `CLAUDE_CODE_USE_POWERSHELL_TOOL` since hooks spawn PowerShell directly |

152 296 

1531. Send the hook input and your prompt to a fast LLM (Haiku)297#### HTTP hook fields

1542. The LLM responds with structured JSON containing a decision

1553. Claude Code processes the decision automatically

156 298 

157### Configuration299In addition to the [common fields](#common-fields), HTTP hooks accept these fields:

300 

301| Field | Required | Description |

302| :--------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

303| `url` | yes | URL to send the POST request to |

304| `headers` | no | Additional HTTP headers as key-value pairs. Values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in `allowedEnvVars` are resolved |

305| `allowedEnvVars` | no | List of environment variable names that may be interpolated into header values. References to unlisted variables are replaced with empty strings. Required for any env var interpolation to work |

306 

307Claude Code sends the hook's [JSON input](#hook-input-and-output) as the POST request body with `Content-Type: application/json`. The response body uses the same [JSON output format](#json-output) as command hooks.

308 

309Error handling differs from command hooks: non-2xx responses, connection failures, and timeouts all produce non-blocking errors that allow execution to continue. To block a tool call or deny a permission, return a 2xx response with a JSON body containing `decision: "block"` or a `hookSpecificOutput` with `permissionDecision: "deny"`.

310 

311This example sends `PreToolUse` events to a local validation service, authenticating with a token from the `MY_TOKEN` environment variable:

158 312 

159```json theme={null}313```json theme={null}

160{314{

161 "hooks": {315 "hooks": {

162 "Stop": [316 "PreToolUse": [

163 {317 {

318 "matcher": "Bash",

164 "hooks": [319 "hooks": [

165 {320 {

166 "type": "prompt",321 "type": "http",

167 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."322 "url": "http://localhost:8080/hooks/pre-tool-use",

323 "timeout": 30,

324 "headers": {

325 "Authorization": "Bearer $MY_TOKEN"

326 },

327 "allowedEnvVars": ["MY_TOKEN"]

168 }328 }

169 ]329 ]

170 }330 }


173}333}

174```334```

175 335 

176**Fields:**336#### Prompt and agent hook fields

177 

178* `type`: Must be `"prompt"`

179* `prompt`: The prompt text to send to the LLM

180 * Use `$ARGUMENTS` as a placeholder for the hook input JSON

181 * If `$ARGUMENTS` is not present, input JSON is appended to the prompt

182* `timeout`: (Optional) Timeout in seconds (default: 30 seconds)

183 

184### Response schema

185 

186The LLM must respond with JSON containing:

187 337 

188```json theme={null}338In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:

189{

190 "decision": "approve" | "block",

191 "reason": "Explanation for the decision",

192 "continue": false, // Optional: stops Claude entirely

193 "stopReason": "Message shown to user", // Optional: custom stop message

194 "systemMessage": "Warning or context" // Optional: shown to user

195}

196```

197 339 

198**Response fields:**340| Field | Required | Description |

341| :------- | :------- | :------------------------------------------------------------------------------------------ |

342| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

343| `model` | no | Model to use for evaluation. Defaults to a fast model |

199 344 

200* `decision`: `"approve"` allows the action, `"block"` prevents it345All matching hooks run in parallel, and identical handlers are deduplicated automatically. Command hooks are deduplicated by command string, and HTTP hooks are deduplicated by URL. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.

201* `reason`: Explanation shown to Claude when decision is `"block"`

202* `continue`: (Optional) If `false`, stops Claude's execution entirely

203* `stopReason`: (Optional) Message shown when `continue` is false

204* `systemMessage`: (Optional) Additional message shown to the user

205 346 

206### Supported hook events347### Reference scripts by path

207 348 

208Prompt-based hooks work with any hook event, but are most useful for:349Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:

209 350 

210* **Stop**: Intelligently decide if Claude should continue working351* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.

211* **SubagentStop**: Evaluate if a subagent has completed its task352* `${CLAUDE_PLUGIN_ROOT}`: the plugin's installation directory, for scripts bundled with a [plugin](/en/plugins). Changes on each plugin update.

212* **UserPromptSubmit**: Validate user prompts with LLM assistance353* `${CLAUDE_PLUGIN_DATA}`: the plugin's [persistent data directory](/en/plugins-reference#persistent-data-directory), for dependencies and state that should survive plugin updates.

213* **PreToolUse**: Make context-aware permission decisions

214 354 

215### Example: Intelligent Stop hook355<Tabs>

356 <Tab title="Project scripts">

357 This example uses `$CLAUDE_PROJECT_DIR` to run a style checker from the project's `.claude/hooks/` directory after any `Write` or `Edit` tool call:

216 358 

217```json theme={null}359 ```json theme={null}

218{360 {

219 "hooks": {361 "hooks": {

220 "Stop": [362 "PostToolUse": [

221 {363 {

364 "matcher": "Write|Edit",

222 "hooks": [365 "hooks": [

223 {366 {

224 "type": "prompt",367 "type": "command",

225 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"decision\": \"approve\" or \"block\", \"reason\": \"your explanation\"}",368 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"

226 "timeout": 30

227 }369 }

228 ]370 ]

229 }371 }

230 ]372 ]

231 }373 }

232}374 }

233```375 ```

376 </Tab>

234 377 

235### Example: SubagentStop with custom logic378 <Tab title="Plugin scripts">

379 Define plugin hooks in `hooks/hooks.json` with an optional top-level `description` field. When a plugin is enabled, its hooks merge with your user and project hooks.

236 380 

237```json theme={null}381 This example runs a formatting script bundled with the plugin:

238{382 

383 ```json theme={null}

384 {

385 "description": "Automatic code formatting",

239 "hooks": {386 "hooks": {

240 "SubagentStop": [387 "PostToolUse": [

241 {388 {

389 "matcher": "Write|Edit",

242 "hooks": [390 "hooks": [

243 {391 {

244 "type": "prompt",392 "type": "command",

245 "prompt": "Evaluate if this subagent should stop. Input: $ARGUMENTS\n\nCheck if:\n- The subagent completed its assigned task\n- Any errors occurred that need fixing\n- Additional context gathering is needed\n\nReturn: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"393 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",

394 "timeout": 30

246 }395 }

247 ]396 ]

248 }397 }

249 ]398 ]

250 }399 }

251}400 }

401 ```

402 

403 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.

404 </Tab>

405</Tabs>

406 

407### Hooks in skills and agents

408 

409In addition to settings files and plugins, hooks can be defined directly in [skills](/en/skills) and [subagents](/en/sub-agents) using frontmatter. These hooks are scoped to the component's lifecycle and only run when that component is active.

410 

411All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.

412 

413Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.

414 

415This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:

416 

417```yaml theme={null}

418---

419name: secure-operations

420description: Perform operations with security checks

421hooks:

422 PreToolUse:

423 - matcher: "Bash"

424 hooks:

425 - type: command

426 command: "./scripts/security-check.sh"

427---

252```428```

253 429 

254### Comparison with bash command hooks430Agents use the same format in their YAML frontmatter.

255 431 

256| Feature | Bash Command Hooks | Prompt-Based Hooks |432### The `/hooks` menu

257| --------------------- | ----------------------- | ------------------------------ |

258| **Execution** | Runs bash script | Queries LLM |

259| **Decision logic** | You implement in code | LLM evaluates context |

260| **Setup complexity** | Requires script file | Just configure prompt |

261| **Context awareness** | Limited to script logic | Natural language understanding |

262| **Performance** | Fast (local execution) | Slower (API call) |

263| **Use case** | Deterministic rules | Context-aware decisions |

264 433 

265### Best practices434Type `/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.

266 435 

267* **Be specific in prompts**: Clearly state what you want the LLM to evaluate436The 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:

268* **Include decision criteria**: List the factors the LLM should consider

269* **Test your prompts**: Verify the LLM makes correct decisions for your use cases

270* **Set appropriate timeouts**: Default is 30 seconds, adjust if needed

271* **Use for complex decisions**: Bash hooks are better for simple, deterministic rules

272 437 

273See the [plugin components reference](/en/docs/claude-code/plugins-reference#hooks) for details on creating plugin hooks.438* `User`: from `~/.claude/settings.json`

439* `Project`: from `.claude/settings.json`

440* `Local`: from `.claude/settings.local.json`

441* `Plugin`: from a plugin's `hooks/hooks.json`

442* `Session`: registered in memory for the current session

443* `Built-in`: registered internally by Claude Code

274 444 

275## Hook Events445Selecting a hook opens a detail view showing its event, matcher, type, source file, and the full command, prompt, or URL. The menu is read-only: to add, modify, or remove hooks, edit the settings JSON directly or ask Claude to make the change.

276 446 

277### PreToolUse447### Disable or remove hooks

278 448 

279Runs after Claude creates tool parameters and before processing the tool call.449To remove a hook, delete its entry from the settings JSON file.

280 450 

281**Common matchers:**451To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file. There is no way to disable an individual hook while keeping it in the configuration.

282 452 

283* `Task` - Subagent tasks (see [subagents documentation](/en/docs/claude-code/sub-agents))453The `disableAllHooks` setting respects the managed settings hierarchy. If an administrator has configured hooks through managed policy settings, `disableAllHooks` set in user, project, or local settings cannot disable those managed hooks. Only `disableAllHooks` set at the managed settings level can disable managed hooks.

284* `Bash` - Shell commands

285* `Glob` - File pattern matching

286* `Grep` - Content search

287* `Read` - File reading

288* `Edit` - File editing

289* `Write` - File writing

290* `WebFetch`, `WebSearch` - Web operations

291 454 

292### PostToolUse455Direct edits to hooks in settings files are normally picked up automatically by the file watcher.

293 456 

294Runs immediately after a tool completes successfully.457## Hook input and output

295 458 

296Recognizes the same matcher values as PreToolUse.459Command hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. HTTP hooks receive the same JSON as the POST request body and communicate results through the HTTP response body. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options.

297 460 

298### PostCustomToolCall461### Common input fields

299 462 

300Runs after an MCP tool completes but **before** `PostToolUse` hooks execute. This hook allows you to modify the tool's output before it's processed further or shown to the model.463Hook 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.

301 464 

302**Key characteristics:**465| Field | Description |

466| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

467| `session_id` | Current session identifier |

468| `transcript_path` | Path to conversation JSON |

469| `cwd` | Current working directory when the hook is invoked |

470| `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 |

471| `hook_event_name` | Name of the event that fired |

303 472 

304* **Only runs for MCP tools** (tools starting with `mcp__`)473When running with `--agent` or inside a subagent, two additional fields are included:

305* Executes after the tool completes but before `PostToolUse` hooks

306* Can modify tool output using the `updatedOutput` field

307* Original tool response is replaced with modified output

308 474 

309**Common use cases:**475| Field | Description |

476| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

477| `agent_id` | Unique identifier for the subagent. Present only when the hook fires inside a subagent call. Use this to distinguish subagent hook calls from main-thread calls. |

478| `agent_type` | Agent name (for example, `"Explore"` or `"security-reviewer"`). Present when the session uses `--agent` or the hook fires inside a subagent. For subagents, the subagent's type takes precedence over the session's `--agent` value. |

310 479 

311* Adding metadata to MCP tool responses480For example, a `PreToolUse` hook for a Bash command receives this on stdin:

312* Filtering sensitive information from tool outputs

313* Transforming response formats

314* Logging MCP tool usage with enriched data

315 481 

316**Important**: If multiple hooks provide `updatedOutput` for the same tool call, they may conflict. Hook execution order is non-deterministic when hooks run in parallel. Only configure one hook per tool to modify output.482```json theme={null}

483{

484 "session_id": "abc123",

485 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",

486 "cwd": "/home/user/my-project",

487 "permission_mode": "default",

488 "hook_event_name": "PreToolUse",

489 "tool_name": "Bash",

490 "tool_input": {

491 "command": "npm test"

492 }

493}

494```

317 495 

318**Matchers:**496The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.

319Recognizes the same matcher values as PreToolUse, but will only execute for MCP tools (`mcp__*`).

320 497 

321### Notification498### Exit code output

322 499 

323Runs when Claude Code sends notifications. Notifications are sent when:500The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.

324 501 

3251. Claude needs your permission to use a tool. Example: "Claude needs your502**Exit 0** means success. Claude Code parses stdout for [JSON output fields](#json-output). JSON output is only processed on exit 0. For most events, stdout is only shown in verbose mode (`Ctrl+O`). The exceptions are `UserPromptSubmit` and `SessionStart`, where stdout is added as context that Claude can see and act on.

326 permission to use Bash"

3272. The prompt input has been idle for at least 60 seconds. "Claude is waiting

328 for your input"

329 503 

330### UserPromptSubmit504**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.

331 505 

332Runs when the user submits a prompt, before Claude processes it. This allows you506**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.

333to add additional context based on the prompt/conversation, validate prompts, or

334block certain types of prompts.

335 507 

336### Stop508For example, a hook command script that blocks dangerous Bash commands:

337 509 

338Runs when the main Claude Code agent has finished responding. Does not run if510```bash theme={null}

339the stoppage occurred due to a user interrupt.511#!/bin/bash

512# Reads JSON input from stdin, checks the command

513command=$(jq -r '.tool_input.command' < /dev/stdin)

340 514 

341### SubagentStop515if [[ "$command" == rm* ]]; then

516 echo "Blocked: rm commands are not allowed" >&2

517 exit 2 # Blocking error: tool call is prevented

518fi

342 519 

343Runs when a Claude Code subagent (Task tool call) has finished responding.520exit 0 # Success: tool call proceeds

521```

344 522 

345### PreCompact523#### Exit code 2 behavior per event

524 

525Exit 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.

526 

527| Hook event | Can block? | What happens on exit 2 |

528| :------------------- | :--------- | :----------------------------------------------------------------------------------------------------------------------------------- |

529| `PreToolUse` | Yes | Blocks the tool call |

530| `PermissionRequest` | Yes | Denies the permission |

531| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |

532| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |

533| `SubagentStop` | Yes | Prevents the subagent from stopping |

534| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |

535| `TaskCreated` | Yes | Rolls back the task creation |

536| `TaskCompleted` | Yes | Prevents the task from being marked as completed |

537| `ConfigChange` | Yes | Blocks the configuration change from taking effect (except `policy_settings`) |

538| `StopFailure` | No | Output and exit code are ignored |

539| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |

540| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |

541| `PermissionDenied` | No | Exit code and stderr are ignored (denial already occurred). Use JSON `hookSpecificOutput.retry: true` to tell the model it may retry |

542| `Notification` | No | Shows stderr to user only |

543| `SubagentStart` | No | Shows stderr to user only |

544| `SessionStart` | No | Shows stderr to user only |

545| `SessionEnd` | No | Shows stderr to user only |

546| `CwdChanged` | No | Shows stderr to user only |

547| `FileChanged` | No | Shows stderr to user only |

548| `PreCompact` | No | Shows stderr to user only |

549| `PostCompact` | No | Shows stderr to user only |

550| `Elicitation` | Yes | Denies the elicitation |

551| `ElicitationResult` | Yes | Blocks the response (action becomes decline) |

552| `WorktreeCreate` | Yes | Any non-zero exit code causes worktree creation to fail |

553| `WorktreeRemove` | No | Failures are logged in debug mode only |

554| `InstructionsLoaded` | No | Exit code is ignored |

555 

556### HTTP response handling

557 

558HTTP hooks use HTTP status codes and response bodies instead of exit codes and stdout:

559 

560* **2xx with an empty body**: success, equivalent to exit code 0 with no output

561* **2xx with a plain text body**: success, the text is added as context

562* **2xx with a JSON body**: success, parsed using the same [JSON output](#json-output) schema as command hooks

563* **Non-2xx status**: non-blocking error, execution continues

564* **Connection failure or timeout**: non-blocking error, execution continues

565 

566Unlike command hooks, HTTP hooks cannot signal a blocking error through status codes alone. To block a tool call or deny a permission, return a 2xx response with a JSON body containing the appropriate decision fields.

567 

568### JSON output

569 

570Exit codes let you allow or block, but JSON output gives you finer-grained control. Instead of exiting with code 2 to block, exit 0 and print a JSON object to stdout. Claude Code reads specific fields from that JSON to control behavior, including [decision control](#decision-control) for blocking, allowing, or escalating to the user.

346 571 

347Runs before Claude Code is about to run a compact operation.572<Note>

573 You must choose one approach per hook, not both: either use exit codes alone for signaling, or exit 0 and print JSON for structured control. Claude Code only processes JSON on exit 0. If you exit 2, any JSON is ignored.

574</Note>

575 

576Your hook's stdout must contain only the JSON object. If your shell profile prints text on startup, it can interfere with JSON parsing. See [JSON validation failed](/en/hooks-guide#json-validation-failed) in the troubleshooting guide.

577 

578Hook output injected into context (`additionalContext`, `systemMessage`, or plain stdout) is capped at 10,000 characters. Output that exceeds this limit is saved to a file and replaced with a preview and file path, the same way large tool results are handled.

579 

580The JSON object supports three kinds of fields:

581 

582* **Universal fields** like `continue` work across all events. These are listed in the table below.

583* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.

584* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.

585 

586| Field | Default | Description |

587| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |

588| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |

589| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |

590| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |

591| `systemMessage` | none | Warning message shown to the user |

592 

593To stop Claude entirely regardless of event type:

594 

595```json theme={null}

596{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }

597```

598 

599#### Decision control

600 

601Not 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:

602 

603| Events | Decision pattern | Key fields |

604| :-------------------------------------------------------------------------------------------------------------------------- | :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

605| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop, ConfigChange | Top-level `decision` | `decision: "block"`, `reason` |

606| 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 |

607| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask/defer), `permissionDecisionReason` |

608| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |

609| PermissionDenied | `hookSpecificOutput` | `retry: true` tells the model it may retry the denied tool call |

610| WorktreeCreate | path return | Command hook prints path on stdout; HTTP hook returns `hookSpecificOutput.worktreePath`. Hook failure or missing path fails creation |

611| Elicitation | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values for accept) |

612| ElicitationResult | `hookSpecificOutput` | `action` (accept/decline/cancel), `content` (form field values override) |

613| WorktreeRemove, Notification, SessionEnd, PreCompact, PostCompact, InstructionsLoaded, StopFailure, CwdChanged, FileChanged | None | No decision control. Used for side effects like logging or cleanup |

614 

615Here are examples of each pattern in action:

616 

617<Tabs>

618 <Tab title="Top-level decision">

619 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStop`, and `ConfigChange`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:

620 

621 ```json theme={null}

622 {

623 "decision": "block",

624 "reason": "Test suite must pass before proceeding"

625 }

626 ```

627 </Tab>

628 

629 <Tab title="PreToolUse">

630 Uses `hookSpecificOutput` for richer control: allow, deny, or escalate to the user. You can also modify tool input before it runs or inject additional context for Claude. See [PreToolUse decision control](#pretooluse-decision-control) for the full set of options.

631 

632 ```json theme={null}

633 {

634 "hookSpecificOutput": {

635 "hookEventName": "PreToolUse",

636 "permissionDecision": "deny",

637 "permissionDecisionReason": "Database writes are not allowed"

638 }

639 }

640 ```

641 </Tab>

642 

643 <Tab title="PermissionRequest">

644 Uses `hookSpecificOutput` to allow or deny a permission request on behalf of the user. When allowing, you can also modify the tool's input or apply permission rules so the user isn't prompted again. See [PermissionRequest decision control](#permissionrequest-decision-control) for the full set of options.

645 

646 ```json theme={null}

647 {

648 "hookSpecificOutput": {

649 "hookEventName": "PermissionRequest",

650 "decision": {

651 "behavior": "allow",

652 "updatedInput": {

653 "command": "npm run lint"

654 }

655 }

656 }

657 }

658 ```

659 </Tab>

660</Tabs>

661 

662For extended examples including Bash command validation, prompt filtering, and auto-approval scripts, see [What you can automate](/en/hooks-guide#what-you-can-automate) in the guide and the [Bash command validator reference implementation](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py).

348 663 

349**Matchers:**664## Hook events

350 665 

351* `manual` - Invoked from `/compact`666Each event corresponds to a point in Claude Code's lifecycle where hooks can run. The sections below are ordered to match the lifecycle: from session setup through the agentic loop to session end. Each section describes when the event fires, what matchers it supports, the JSON input it receives, and how to control behavior through output.

352* `auto` - Invoked from auto-compact (due to full context window)

353 667 

354### SessionStart668### SessionStart

355 669 

356Runs when Claude Code starts a new session or resumes an existing session (which670Runs 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.

357currently does start a new session under the hood). Useful for loading in671 

358development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.672SessionStart runs on every session, so keep these hooks fast. Only `type: "command"` hooks are supported.

673 

674The matcher value corresponds to how the session was initiated:

675 

676| Matcher | When it fires |

677| :-------- | :------------------------------------- |

678| `startup` | New session |

679| `resume` | `--resume`, `--continue`, or `/resume` |

680| `clear` | `/clear` |

681| `compact` | Auto or manual compaction |

682 

683#### SessionStart input

684 

685In addition to the [common input fields](#common-input-fields), SessionStart hooks receive `source`, `model`, and optionally `agent_type`. The `source` field indicates how the session started: `"startup"` for new sessions, `"resume"` for resumed sessions, `"clear"` after `/clear`, or `"compact"` after compaction. The `model` field contains the model identifier. If you start Claude Code with `claude --agent <name>`, an `agent_type` field contains the agent name.

686 

687```json theme={null}

688{

689 "session_id": "abc123",

690 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

691 "cwd": "/Users/...",

692 "hook_event_name": "SessionStart",

693 "source": "startup",

694 "model": "claude-sonnet-4-6"

695}

696```

697 

698#### SessionStart decision control

699 

700Any 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:

359 701 

360**Matchers:**702| Field | Description |

703| :------------------ | :------------------------------------------------------------------------ |

704| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |

361 705 

362* `startup` - Invoked from startup706```json theme={null}

363* `resume` - Invoked from `--resume`, `--continue`, or `/resume`707{

364* `clear` - Invoked from `/clear`708 "hookSpecificOutput": {

365* `compact` - Invoked from auto or manual compact.709 "hookEventName": "SessionStart",

710 "additionalContext": "My additional context here"

711 }

712}

713```

366 714 

367#### Persisting environment variables715#### Persist environment variables

368 716 

369SessionStart 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.717SessionStart 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.

370 718 

371**Example: Setting individual environment variables**719To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:

372 720 

373```bash theme={null}721```bash theme={null}

374#!/bin/bash722#!/bin/bash

375 723 

376if [ -n "$CLAUDE_ENV_FILE" ]; then724if [ -n "$CLAUDE_ENV_FILE" ]; then

377 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"725 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"

378 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"726 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"

379 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"727 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"

380fi728fi

381 729 

382exit 0730exit 0

383```731```

384 732 

385**Example: Persisting all environment changes from the hook**733To capture all environment changes from setup commands, compare the exported variables before and after:

386 

387When your setup modifies the environment (e.g., `nvm use`), capture and persist all changes by diffing the environment:

388 734 

389```bash theme={null}735```bash theme={null}

390#!/bin/bash736#!/bin/bash


403exit 0749exit 0

404```750```

405 751 

406Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.752Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.

407 753 

408<Note>754<Note>

409 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.755 `CLAUDE_ENV_FILE` is available for SessionStart, [CwdChanged](#cwdchanged), and [FileChanged](#filechanged) hooks. Other hook types do not have access to this variable.

410</Note>756</Note>

411 757 

412### SessionEnd758### InstructionsLoaded

413 759 

414Runs when a Claude Code session ends. Useful for cleanup tasks, logging session760Fires 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.

415statistics, or saving session state.

416 761 

417The `reason` field in the hook input will be one of:762The matcher runs against `load_reason`. For example, use `"matcher": "session_start"` to fire only for files loaded at session start, or `"matcher": "path_glob_match|nested_traversal"` to fire only for lazy loads.

418 763 

419* `clear` - Session cleared with /clear command764#### InstructionsLoaded input

420* `logout` - User logged out

421* `prompt_input_exit` - User exited while prompt input was visible

422* `other` - Other exit reasons

423 765 

424## Hook Input766In addition to the [common input fields](#common-input-fields), InstructionsLoaded hooks receive these fields:

425 767 

426Hooks receive JSON data via stdin containing session information and768| Field | Description |

427event-specific data:769| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

770| `file_path` | Absolute path to the instruction file that was loaded |

771| `memory_type` | Scope of the file: `"User"`, `"Project"`, `"Local"`, or `"Managed"` |

772| `load_reason` | Why the file was loaded: `"session_start"`, `"nested_traversal"`, `"path_glob_match"`, `"include"`, or `"compact"`. The `"compact"` value fires when instruction files are re-loaded after a compaction event |

773| `globs` | Path glob patterns from the file's `paths:` frontmatter, if any. Present only for `path_glob_match` loads |

774| `trigger_file_path` | Path to the file whose access triggered this load, for lazy loads |

775| `parent_file_path` | Path to the parent instruction file that included this one, for `include` loads |

428 776 

429```typescript theme={null}777```json theme={null}

430{778{

431 // Common fields779 "session_id": "abc123",

432 session_id: string780 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

433 transcript_path: string // Path to conversation JSON781 "cwd": "/Users/my-project",

434 cwd: string // The current working directory when the hook is invoked782 "hook_event_name": "InstructionsLoaded",

435 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"783 "file_path": "/Users/my-project/CLAUDE.md",

436 784 "memory_type": "Project",

437 // Event-specific fields785 "load_reason": "session_start"

438 hook_event_name: string

439 ...

440}786}

441```787```

442 788 

443### PreToolUse Input789#### InstructionsLoaded decision control

444 790 

445The exact schema for `tool_input` depends on the tool.791InstructionsLoaded hooks have no decision control. They cannot block or modify instruction loading. Use this event for audit logging, compliance tracking, or observability.

446 792 

447```json theme={null}793### UserPromptSubmit

448{794 

449 "session_id": "abc123",795Runs when the user submits a prompt, before Claude processes it. This allows you

450 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",796to add additional context based on the prompt/conversation, validate prompts, or

451 "cwd": "/Users/...",797block certain types of prompts.

452 "permission_mode": "default",

453 "hook_event_name": "PreToolUse",

454 "tool_name": "Write",

455 "tool_input": {

456 "file_path": "/path/to/file.txt",

457 "content": "file content"

458 }

459}

460```

461 798 

462### PostToolUse Input799#### UserPromptSubmit input

463 800 

464The exact schema for `tool_input` and `tool_response` depends on the tool.801In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.

465 802 

466```json theme={null}803```json theme={null}

467{804{


469 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",806 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

470 "cwd": "/Users/...",807 "cwd": "/Users/...",

471 "permission_mode": "default",808 "permission_mode": "default",

472 "hook_event_name": "PostToolUse",809 "hook_event_name": "UserPromptSubmit",

473 "tool_name": "Write",810 "prompt": "Write a function to calculate the factorial of a number"

474 "tool_input": {

475 "file_path": "/path/to/file.txt",

476 "content": "file content"

477 },

478 "tool_response": {

479 "filePath": "/path/to/file.txt",

480 "success": true

481 }

482}811}

483```812```

484 813 

485### PostCustomToolCall Input814#### UserPromptSubmit decision control

486 815 

487The exact schema for `tool_input` and `tool_response` depends on the MCP tool.816`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.

488 817 

489```json theme={null}818There are two ways to add context to the conversation on exit code 0:

490{819 

820* **Plain text stdout**: any non-JSON text written to stdout is added as context

821* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context

822 

823Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.

824 

825To block a prompt, return a JSON object with `decision` set to `"block"`:

826 

827| Field | Description |

828| :------------------ | :----------------------------------------------------------------------------------------------------------------- |

829| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |

830| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |

831| `additionalContext` | String added to Claude's context |

832 

833```json theme={null}

834{

835 "decision": "block",

836 "reason": "Explanation for decision",

837 "hookSpecificOutput": {

838 "hookEventName": "UserPromptSubmit",

839 "additionalContext": "My additional context here"

840 }

841}

842```

843 

844<Note>

845 The JSON format isn't required for simple use cases. To add context, you can print plain text to stdout with exit code 0. Use JSON when you need to

846 block prompts or want more structured control.

847</Note>

848 

849### PreToolUse

850 

851Runs 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).

852 

853Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, ask, or defer the tool call.

854 

855#### PreToolUse input

856 

857In addition to the [common input fields](#common-input-fields), PreToolUse hooks receive `tool_name`, `tool_input`, and `tool_use_id`. The `tool_input` fields depend on the tool:

858 

859##### Bash

860 

861Executes shell commands.

862 

863| Field | Type | Example | Description |

864| :------------------ | :------ | :----------------- | :-------------------------------------------- |

865| `command` | string | `"npm test"` | The shell command to execute |

866| `description` | string | `"Run test suite"` | Optional description of what the command does |

867| `timeout` | number | `120000` | Optional timeout in milliseconds |

868| `run_in_background` | boolean | `false` | Whether to run the command in background |

869 

870##### Write

871 

872Creates or overwrites a file.

873 

874| Field | Type | Example | Description |

875| :---------- | :----- | :-------------------- | :--------------------------------- |

876| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |

877| `content` | string | `"file content"` | Content to write to the file |

878 

879##### Edit

880 

881Replaces a string in an existing file.

882 

883| Field | Type | Example | Description |

884| :------------ | :------ | :-------------------- | :--------------------------------- |

885| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |

886| `old_string` | string | `"original text"` | Text to find and replace |

887| `new_string` | string | `"replacement text"` | Replacement text |

888| `replace_all` | boolean | `false` | Whether to replace all occurrences |

889 

890##### Read

891 

892Reads file contents.

893 

894| Field | Type | Example | Description |

895| :---------- | :----- | :-------------------- | :----------------------------------------- |

896| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |

897| `offset` | number | `10` | Optional line number to start reading from |

898| `limit` | number | `50` | Optional number of lines to read |

899 

900##### Glob

901 

902Finds files matching a glob pattern.

903 

904| Field | Type | Example | Description |

905| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |

906| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |

907| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |

908 

909##### Grep

910 

911Searches file contents with regular expressions.

912 

913| Field | Type | Example | Description |

914| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |

915| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |

916| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |

917| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |

918| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |

919| `-i` | boolean | `true` | Case insensitive search |

920| `multiline` | boolean | `false` | Enable multiline matching |

921 

922##### WebFetch

923 

924Fetches and processes web content.

925 

926| Field | Type | Example | Description |

927| :------- | :----- | :---------------------------- | :----------------------------------- |

928| `url` | string | `"https://example.com/api"` | URL to fetch content from |

929| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |

930 

931##### WebSearch

932 

933Searches the web.

934 

935| Field | Type | Example | Description |

936| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |

937| `query` | string | `"react hooks best practices"` | Search query |

938| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |

939| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |

940 

941##### Agent

942 

943Spawns a [subagent](/en/sub-agents).

944 

945| Field | Type | Example | Description |

946| :-------------- | :----- | :------------------------- | :------------------------------------------- |

947| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |

948| `description` | string | `"Find API endpoints"` | Short description of the task |

949| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |

950| `model` | string | `"sonnet"` | Optional model alias to override the default |

951 

952##### AskUserQuestion

953 

954Asks the user one to four multiple-choice questions.

955 

956| Field | Type | Example | Description |

957| :---------- | :----- | :----------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

958| `questions` | array | `[{"question": "Which framework?", "header": "Framework", "options": [{"label": "React"}], "multiSelect": false}]` | Questions to present, each with a `question` string, short `header`, `options` array, and optional `multiSelect` flag |

959| `answers` | object | `{"Which framework?": "React"}` | Optional. Maps question text to the selected option label. Multi-select answers join labels with commas. Claude does not set this field; supply it via `updatedInput` to answer programmatically |

960 

961#### PreToolUse decision control

962 

963`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: four outcomes (allow, deny, ask, or defer) plus the ability to modify tool input before execution.

964 

965| Field | Description |

966| :------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

967| `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) still apply when a hook returns `"allow"` |

968| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude. For `"defer"`, ignored |

969| `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 |

970| `additionalContext` | String added to Claude's context before the tool executes. For `"defer"`, ignored |

971 

972When multiple PreToolUse hooks return different decisions, precedence is `deny` > `defer` > `ask` > `allow`.

973 

974When a hook returns `"ask"`, the permission prompt displayed to the user includes a label identifying where the hook came from: for example, `[User]`, `[Project]`, `[Plugin]`, or `[Local]`. This helps users understand which configuration source is requesting confirmation.

975 

976```json theme={null}

977{

978 "hookSpecificOutput": {

979 "hookEventName": "PreToolUse",

980 "permissionDecision": "allow",

981 "permissionDecisionReason": "My reason here",

982 "updatedInput": {

983 "field_to_modify": "new value"

984 },

985 "additionalContext": "Current environment: production. Proceed with caution."

986 }

987}

988```

989 

990`AskUserQuestion` and `ExitPlanMode` require user interaction and normally block in [non-interactive mode](/en/headless) with the `-p` flag. Returning `permissionDecision: "allow"` together with `updatedInput` satisfies that requirement: the hook reads the tool's input from stdin, collects the answer through your own UI, and returns it in `updatedInput` so the tool runs without prompting. Returning `"allow"` alone is not sufficient for these tools. For `AskUserQuestion`, echo back the original `questions` array and add an [`answers`](#askuserquestion) object mapping each question's text to the chosen answer.

991 

992<Note>

993 PreToolUse previously used top-level `decision` and `reason` fields, but these are deprecated for this event. Use `hookSpecificOutput.permissionDecision` and `hookSpecificOutput.permissionDecisionReason` instead. The deprecated values `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively. Other events like PostToolUse and Stop continue to use top-level `decision` and `reason` as their current format.

994</Note>

995 

996#### Defer a tool call for later

997 

998`"defer"` is for integrations that run `claude -p` as a subprocess and read its JSON output, such as an Agent SDK app or a custom UI built on top of Claude Code. It lets that calling process pause Claude at a tool call, collect input through its own interface, and resume where it left off. Claude Code honors this value only in [non-interactive mode](/en/headless) with the `-p` flag. In interactive sessions it logs a warning and ignores the hook result.

999 

1000<Note>

1001 The `defer` value requires Claude Code v2.1.89 or later. Earlier versions do not recognize it and the tool proceeds through the normal permission flow.

1002</Note>

1003 

1004The `AskUserQuestion` tool is the typical case: Claude wants to ask the user something, but there is no terminal to answer in. The round trip works like this:

1005 

10061. Claude calls `AskUserQuestion`. The `PreToolUse` hook fires.

10072. The hook returns `permissionDecision: "defer"`. The tool does not execute. The process exits with `stop_reason: "tool_deferred"` and the pending tool call preserved in the transcript.

10083. The calling process reads `deferred_tool_use` from the SDK result, surfaces the question in its own UI, and waits for an answer.

10094. The calling process runs `claude -p --resume <session-id>`. The same tool call fires `PreToolUse` again.

10105. The hook returns `permissionDecision: "allow"` with the answer in `updatedInput`. The tool executes and Claude continues.

1011 

1012The `deferred_tool_use` field carries the tool's `id`, `name`, and `input`. The `input` is the parameters Claude generated for the tool call, captured before execution:

1013 

1014```json theme={null}

1015{

1016 "type": "result",

1017 "subtype": "success",

1018 "stop_reason": "tool_deferred",

1019 "session_id": "abc123",

1020 "deferred_tool_use": {

1021 "id": "toolu_01abc",

1022 "name": "AskUserQuestion",

1023 "input": { "questions": [{ "question": "Which framework?", "header": "Framework", "options": [{"label": "React"}, {"label": "Vue"}], "multiSelect": false }] }

1024 }

1025}

1026```

1027 

1028There 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.

1029 

1030`"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.

1031 

1032If 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.

1033 

1034<Warning>

1035 `--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.

1036</Warning>

1037 

1038### PermissionRequest

1039 

1040Runs when the user is shown a permission dialog.

1041Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

1042 

1043Matches on tool name, same values as PreToolUse.

1044 

1045#### PermissionRequest input

1046 

1047PermissionRequest hooks receive `tool_name` and `tool_input` fields like PreToolUse hooks, but without `tool_use_id`. An optional `permission_suggestions` array contains the "always allow" options the user would normally see in the permission dialog. The difference is when the hook fires: PermissionRequest hooks run when a permission dialog is about to be shown to the user, while PreToolUse hooks run before tool execution regardless of permission status.

1048 

1049```json theme={null}

1050{

491 "session_id": "abc123",1051 "session_id": "abc123",

492 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1052 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

493 "cwd": "/Users/...",1053 "cwd": "/Users/...",

494 "permission_mode": "default",1054 "permission_mode": "default",

495 "hook_event_name": "PostCustomToolCall",1055 "hook_event_name": "PermissionRequest",

496 "tool_name": "mcp__github__create_issue",1056 "tool_name": "Bash",

497 "tool_input": {1057 "tool_input": {

498 "title": "Bug report",1058 "command": "rm -rf node_modules",

499 "body": "Description of the issue"1059 "description": "Remove node_modules directory"

1060 },

1061 "permission_suggestions": [

1062 {

1063 "type": "addRules",

1064 "rules": [{ "toolName": "Bash", "ruleContent": "rm -rf node_modules" }],

1065 "behavior": "allow",

1066 "destination": "localSettings"

1067 }

1068 ]

1069}

1070```

1071 

1072#### PermissionRequest decision control

1073 

1074`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:

1075 

1076| Field | Description |

1077| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1078| `behavior` | `"allow"` grants the permission, `"deny"` denies it |

1079| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution. Replaces the entire input object, so include unchanged fields alongside modified ones |

1080| `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 |

1081| `message` | For `"deny"` only: tells Claude why the permission was denied |

1082| `interrupt` | For `"deny"` only: if `true`, stops Claude |

1083 

1084```json theme={null}

1085{

1086 "hookSpecificOutput": {

1087 "hookEventName": "PermissionRequest",

1088 "decision": {

1089 "behavior": "allow",

1090 "updatedInput": {

1091 "command": "npm run lint"

1092 }

1093 }

1094 }

1095}

1096```

1097 

1098#### Permission update entries

1099 

1100The `updatedPermissions` output field and the [`permission_suggestions` input field](#permissionrequest-input) both use the same array of entry objects. Each entry has a `type` that determines its other fields, and a `destination` that controls where the change is written.

1101 

1102| `type` | Fields | Effect |

1103| :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1104| `addRules` | `rules`, `behavior`, `destination` | Adds permission rules. `rules` is an array of `{toolName, ruleContent?}` objects. Omit `ruleContent` to match the whole tool. `behavior` is `"allow"`, `"deny"`, or `"ask"` |

1105| `replaceRules` | `rules`, `behavior`, `destination` | Replaces all rules of the given `behavior` at the `destination` with the provided `rules` |

1106| `removeRules` | `rules`, `behavior`, `destination` | Removes matching rules of the given `behavior` |

1107| `setMode` | `mode`, `destination` | Changes the permission mode. Valid modes are `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, and `plan` |

1108| `addDirectories` | `directories`, `destination` | Adds working directories. `directories` is an array of path strings |

1109| `removeDirectories` | `directories`, `destination` | Removes working directories |

1110 

1111The `destination` field on every entry determines whether the change stays in memory or persists to a settings file.

1112 

1113| `destination` | Writes to |

1114| :---------------- | :---------------------------------------------- |

1115| `session` | in-memory only, discarded when the session ends |

1116| `localSettings` | `.claude/settings.local.json` |

1117| `projectSettings` | `.claude/settings.json` |

1118| `userSettings` | `~/.claude/settings.json` |

1119 

1120A hook can echo one of the `permission_suggestions` it received as its own `updatedPermissions` output, which is equivalent to the user selecting that "always allow" option in the dialog.

1121 

1122### PostToolUse

1123 

1124Runs immediately after a tool completes successfully.

1125 

1126Matches on tool name, same values as PreToolUse.

1127 

1128#### PostToolUse input

1129 

1130`PostToolUse` hooks fire after a tool has already executed successfully. The input includes both `tool_input`, the arguments sent to the tool, and `tool_response`, the result it returned. The exact schema for both depends on the tool.

1131 

1132```json theme={null}

1133{

1134 "session_id": "abc123",

1135 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1136 "cwd": "/Users/...",

1137 "permission_mode": "default",

1138 "hook_event_name": "PostToolUse",

1139 "tool_name": "Write",

1140 "tool_input": {

1141 "file_path": "/path/to/file.txt",

1142 "content": "file content"

500 },1143 },

501 "tool_response": {1144 "tool_response": {

502 "issue_number": 42,1145 "filePath": "/path/to/file.txt",

503 "url": "https://github.com/org/repo/issues/42"1146 "success": true

1147 },

1148 "tool_use_id": "toolu_01ABC123..."

1149}

1150```

1151 

1152#### PostToolUse decision control

1153 

1154`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:

1155 

1156| Field | Description |

1157| :--------------------- | :----------------------------------------------------------------------------------------- |

1158| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |

1159| `reason` | Explanation shown to Claude when `decision` is `"block"` |

1160| `additionalContext` | Additional context for Claude to consider |

1161| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |

1162 

1163```json theme={null}

1164{

1165 "decision": "block",

1166 "reason": "Explanation for decision",

1167 "hookSpecificOutput": {

1168 "hookEventName": "PostToolUse",

1169 "additionalContext": "Additional information for Claude"

1170 }

1171}

1172```

1173 

1174### PostToolUseFailure

1175 

1176Runs 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.

1177 

1178Matches on tool name, same values as PreToolUse.

1179 

1180#### PostToolUseFailure input

1181 

1182PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:

1183 

1184```json theme={null}

1185{

1186 "session_id": "abc123",

1187 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1188 "cwd": "/Users/...",

1189 "permission_mode": "default",

1190 "hook_event_name": "PostToolUseFailure",

1191 "tool_name": "Bash",

1192 "tool_input": {

1193 "command": "npm test",

1194 "description": "Run test suite"

1195 },

1196 "tool_use_id": "toolu_01ABC123...",

1197 "error": "Command exited with non-zero status code 1",

1198 "is_interrupt": false

1199}

1200```

1201 

1202| Field | Description |

1203| :------------- | :------------------------------------------------------------------------------ |

1204| `error` | String describing what went wrong |

1205| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |

1206 

1207#### PostToolUseFailure decision control

1208 

1209`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:

1210 

1211| Field | Description |

1212| :------------------ | :------------------------------------------------------------ |

1213| `additionalContext` | Additional context for Claude to consider alongside the error |

1214 

1215```json theme={null}

1216{

1217 "hookSpecificOutput": {

1218 "hookEventName": "PostToolUseFailure",

1219 "additionalContext": "Additional information about the failure for Claude"

1220 }

1221}

1222```

1223 

1224### PermissionDenied

1225 

1226Runs 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.

1227 

1228Matches on tool name, same values as PreToolUse.

1229 

1230#### PermissionDenied input

1231 

1232In addition to the [common input fields](#common-input-fields), PermissionDenied hooks receive `tool_name`, `tool_input`, `tool_use_id`, and `reason`.

1233 

1234```json theme={null}

1235{

1236 "session_id": "abc123",

1237 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1238 "cwd": "/Users/...",

1239 "permission_mode": "auto",

1240 "hook_event_name": "PermissionDenied",

1241 "tool_name": "Bash",

1242 "tool_input": {

1243 "command": "rm -rf /tmp/build",

1244 "description": "Clean build directory"

1245 },

1246 "tool_use_id": "toolu_01ABC123...",

1247 "reason": "Auto mode denied: command targets a path outside the project"

1248}

1249```

1250 

1251| Field | Description |

1252| :------- | :------------------------------------------------------------ |

1253| `reason` | The classifier's explanation for why the tool call was denied |

1254 

1255#### PermissionDenied decision control

1256 

1257PermissionDenied hooks can tell the model it may retry the denied tool call. Return a JSON object with `hookSpecificOutput.retry` set to `true`:

1258 

1259```json theme={null}

1260{

1261 "hookSpecificOutput": {

1262 "hookEventName": "PermissionDenied",

1263 "retry": true

1264 }

1265}

1266```

1267 

1268When `retry` is `true`, Claude Code adds a message to the conversation telling the model it may retry the tool call. The denial itself is not reversed. If your hook does not return JSON, or returns `retry: false`, the denial stands and the model receives the original rejection message.

1269 

1270### Notification

1271 

1272Runs 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.

1273 

1274Use 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:

1275 

1276```json theme={null}

1277{

1278 "hooks": {

1279 "Notification": [

1280 {

1281 "matcher": "permission_prompt",

1282 "hooks": [

1283 {

1284 "type": "command",

1285 "command": "/path/to/permission-alert.sh"

1286 }

1287 ]

1288 },

1289 {

1290 "matcher": "idle_prompt",

1291 "hooks": [

1292 {

1293 "type": "command",

1294 "command": "/path/to/idle-notification.sh"

1295 }

1296 ]

1297 }

1298 ]

1299 }

1300}

1301```

1302 

1303#### Notification input

1304 

1305In addition to the [common input fields](#common-input-fields), Notification hooks receive `message` with the notification text, an optional `title`, and `notification_type` indicating which type fired.

1306 

1307```json theme={null}

1308{

1309 "session_id": "abc123",

1310 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1311 "cwd": "/Users/...",

1312 "hook_event_name": "Notification",

1313 "message": "Claude needs your permission to use Bash",

1314 "title": "Permission needed",

1315 "notification_type": "permission_prompt"

1316}

1317```

1318 

1319Notification 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:

1320 

1321| Field | Description |

1322| :------------------ | :------------------------------- |

1323| `additionalContext` | String added to Claude's context |

1324 

1325### SubagentStart

1326 

1327Runs 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/`).

1328 

1329#### SubagentStart input

1330 

1331In 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).

1332 

1333```json theme={null}

1334{

1335 "session_id": "abc123",

1336 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1337 "cwd": "/Users/...",

1338 "hook_event_name": "SubagentStart",

1339 "agent_id": "agent-abc123",

1340 "agent_type": "Explore"

1341}

1342```

1343 

1344SubagentStart 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:

1345 

1346| Field | Description |

1347| :------------------ | :------------------------------------- |

1348| `additionalContext` | String added to the subagent's context |

1349 

1350```json theme={null}

1351{

1352 "hookSpecificOutput": {

1353 "hookEventName": "SubagentStart",

1354 "additionalContext": "Follow security guidelines for this task"

1355 }

1356}

1357```

1358 

1359### SubagentStop

1360 

1361Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.

1362 

1363#### SubagentStop input

1364 

1365In addition to the [common input fields](#common-input-fields), SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, `agent_transcript_path`, and `last_assistant_message`. The `agent_type` field is the value used for matcher filtering. The `transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder. The `last_assistant_message` field contains the text content of the subagent's final response, so hooks can access it without parsing the transcript file.

1366 

1367```json theme={null}

1368{

1369 "session_id": "abc123",

1370 "transcript_path": "~/.claude/projects/.../abc123.jsonl",

1371 "cwd": "/Users/...",

1372 "permission_mode": "default",

1373 "hook_event_name": "SubagentStop",

1374 "stop_hook_active": false,

1375 "agent_id": "def456",

1376 "agent_type": "Explore",

1377 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl",

1378 "last_assistant_message": "Analysis complete. Found 3 potential issues..."

1379}

1380```

1381 

1382SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).

1383 

1384### TaskCreated

1385 

1386Runs when a task is being created via the `TaskCreate` tool. Use this to enforce naming conventions, require task descriptions, or prevent certain tasks from being created.

1387 

1388When a `TaskCreated` hook exits with code 2, the task is not created and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCreated hooks do not support matchers and fire on every occurrence.

1389 

1390#### TaskCreated input

1391 

1392In addition to the [common input fields](#common-input-fields), TaskCreated hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.

1393 

1394```json theme={null}

1395{

1396 "session_id": "abc123",

1397 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1398 "cwd": "/Users/...",

1399 "permission_mode": "default",

1400 "hook_event_name": "TaskCreated",

1401 "task_id": "task-001",

1402 "task_subject": "Implement user authentication",

1403 "task_description": "Add login and signup endpoints",

1404 "teammate_name": "implementer",

1405 "team_name": "my-project"

1406}

1407```

1408 

1409| Field | Description |

1410| :----------------- | :---------------------------------------------------- |

1411| `task_id` | Identifier of the task being created |

1412| `task_subject` | Title of the task |

1413| `task_description` | Detailed description of the task. May be absent |

1414| `teammate_name` | Name of the teammate creating the task. May be absent |

1415| `team_name` | Name of the team. May be absent |

1416 

1417#### TaskCreated decision control

1418 

1419TaskCreated hooks support two ways to control task creation:

1420 

1421* **Exit code 2**: the task is not created and the stderr message is fed back to the model as feedback.

1422* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.

1423 

1424This example blocks tasks whose subjects don't follow the required format:

1425 

1426```bash theme={null}

1427#!/bin/bash

1428INPUT=$(cat)

1429TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

1430 

1431if [[ ! "$TASK_SUBJECT" =~ ^\[TICKET-[0-9]+\] ]]; then

1432 echo "Task subject must start with a ticket number, e.g. '[TICKET-123] Add feature'" >&2

1433 exit 2

1434fi

1435 

1436exit 0

1437```

1438 

1439### TaskCompleted

1440 

1441Runs when a task is being marked as completed. This fires in two situations: when any agent explicitly marks a task as completed through the TaskUpdate tool, or when an [agent team](/en/agent-teams) teammate finishes its turn with in-progress tasks. Use this to enforce completion criteria like passing tests or lint checks before a task can close.

1442 

1443When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TaskCompleted hooks do not support matchers and fire on every occurrence.

1444 

1445#### TaskCompleted input

1446 

1447In addition to the [common input fields](#common-input-fields), TaskCompleted hooks receive `task_id`, `task_subject`, and optionally `task_description`, `teammate_name`, and `team_name`.

1448 

1449```json theme={null}

1450{

1451 "session_id": "abc123",

1452 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1453 "cwd": "/Users/...",

1454 "permission_mode": "default",

1455 "hook_event_name": "TaskCompleted",

1456 "task_id": "task-001",

1457 "task_subject": "Implement user authentication",

1458 "task_description": "Add login and signup endpoints",

1459 "teammate_name": "implementer",

1460 "team_name": "my-project"

1461}

1462```

1463 

1464| Field | Description |

1465| :----------------- | :------------------------------------------------------ |

1466| `task_id` | Identifier of the task being completed |

1467| `task_subject` | Title of the task |

1468| `task_description` | Detailed description of the task. May be absent |

1469| `teammate_name` | Name of the teammate completing the task. May be absent |

1470| `team_name` | Name of the team. May be absent |

1471 

1472#### TaskCompleted decision control

1473 

1474TaskCompleted hooks support two ways to control task completion:

1475 

1476* **Exit code 2**: the task is not marked as completed and the stderr message is fed back to the model as feedback.

1477* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.

1478 

1479This example runs tests and blocks task completion if they fail:

1480 

1481```bash theme={null}

1482#!/bin/bash

1483INPUT=$(cat)

1484TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

1485 

1486# Run the test suite

1487if ! npm test 2>&1; then

1488 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2

1489 exit 2

1490fi

1491 

1492exit 0

1493```

1494 

1495### Stop

1496 

1497Runs when the main Claude Code agent has finished responding. Does not run if

1498the stoppage occurred due to a user interrupt. API errors fire

1499[StopFailure](#stopfailure) instead.

1500 

1501#### Stop input

1502 

1503In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active` and `last_assistant_message`. The `stop_hook_active` field is `true` when Claude Code is already continuing as a result of a stop hook. Check this value or process the transcript to prevent Claude Code from running indefinitely. The `last_assistant_message` field contains the text content of Claude's final response, so hooks can access it without parsing the transcript file.

1504 

1505```json theme={null}

1506{

1507 "session_id": "abc123",

1508 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1509 "cwd": "/Users/...",

1510 "permission_mode": "default",

1511 "hook_event_name": "Stop",

1512 "stop_hook_active": true,

1513 "last_assistant_message": "I've completed the refactoring. Here's a summary..."

1514}

1515```

1516 

1517#### Stop decision control

1518 

1519`Stop` and `SubagentStop` hooks can control whether Claude continues. In addition to the [JSON output fields](#json-output) available to all hooks, your hook script can return these event-specific fields:

1520 

1521| Field | Description |

1522| :--------- | :------------------------------------------------------------------------- |

1523| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |

1524| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |

1525 

1526```json theme={null}

1527{

1528 "decision": "block",

1529 "reason": "Must be provided when Claude is blocked from stopping"

1530}

1531```

1532 

1533### StopFailure

1534 

1535Runs instead of [Stop](#stop) when the turn ends due to an API error. Output and exit code are ignored. Use this to log failures, send alerts, or take recovery actions when Claude cannot complete a response due to rate limits, authentication problems, or other API errors.

1536 

1537#### StopFailure input

1538 

1539In addition to the [common input fields](#common-input-fields), StopFailure hooks receive `error`, optional `error_details`, and optional `last_assistant_message`. The `error` field identifies the error type and is used for matcher filtering.

1540 

1541| Field | Description |

1542| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1543| `error` | Error type: `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` |

1544| `error_details` | Additional details about the error, when available |

1545| `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"` |

1546 

1547```json theme={null}

1548{

1549 "session_id": "abc123",

1550 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1551 "cwd": "/Users/...",

1552 "hook_event_name": "StopFailure",

1553 "error": "rate_limit",

1554 "error_details": "429 Too Many Requests",

1555 "last_assistant_message": "API Error: Rate limit reached"

1556}

1557```

1558 

1559StopFailure hooks have no decision control. They run for notification and logging purposes only.

1560 

1561### TeammateIdle

1562 

1563Runs when an [agent team](/en/agent-teams) teammate is about to go idle after finishing its turn. Use this to enforce quality gates before a teammate stops working, such as requiring passing lint checks or verifying that output files exist.

1564 

1565When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. To stop the teammate entirely instead of re-running it, return JSON with `{"continue": false, "stopReason": "..."}`. TeammateIdle hooks do not support matchers and fire on every occurrence.

1566 

1567#### TeammateIdle input

1568 

1569In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.

1570 

1571```json theme={null}

1572{

1573 "session_id": "abc123",

1574 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1575 "cwd": "/Users/...",

1576 "permission_mode": "default",

1577 "hook_event_name": "TeammateIdle",

1578 "teammate_name": "researcher",

1579 "team_name": "my-project"

1580}

1581```

1582 

1583| Field | Description |

1584| :-------------- | :-------------------------------------------- |

1585| `teammate_name` | Name of the teammate that is about to go idle |

1586| `team_name` | Name of the team |

1587 

1588#### TeammateIdle decision control

1589 

1590TeammateIdle hooks support two ways to control teammate behavior:

1591 

1592* **Exit code 2**: the teammate receives the stderr message as feedback and continues working instead of going idle.

1593* **JSON `{"continue": false, "stopReason": "..."}`**: stops the teammate entirely, matching `Stop` hook behavior. The `stopReason` is shown to the user.

1594 

1595This example checks that a build artifact exists before allowing a teammate to go idle:

1596 

1597```bash theme={null}

1598#!/bin/bash

1599 

1600if [ ! -f "./dist/output.js" ]; then

1601 echo "Build artifact missing. Run the build before stopping." >&2

1602 exit 2

1603fi

1604 

1605exit 0

1606```

1607 

1608### ConfigChange

1609 

1610Runs when a configuration file changes during a session. Use this to audit settings changes, enforce security policies, or block unauthorized modifications to configuration files.

1611 

1612ConfigChange hooks fire for changes to settings files, managed policy settings, and skill files. The `source` field in the input tells you which type of configuration changed, and the optional `file_path` field provides the path to the changed file.

1613 

1614The matcher filters on the configuration source:

1615 

1616| Matcher | When it fires |

1617| :----------------- | :---------------------------------------- |

1618| `user_settings` | `~/.claude/settings.json` changes |

1619| `project_settings` | `.claude/settings.json` changes |

1620| `local_settings` | `.claude/settings.local.json` changes |

1621| `policy_settings` | Managed policy settings change |

1622| `skills` | A skill file in `.claude/skills/` changes |

1623 

1624This example logs all configuration changes for security auditing:

1625 

1626```json theme={null}

1627{

1628 "hooks": {

1629 "ConfigChange": [

1630 {

1631 "hooks": [

1632 {

1633 "type": "command",

1634 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/audit-config-change.sh"

1635 }

1636 ]

1637 }

1638 ]

1639 }

1640}

1641```

1642 

1643#### ConfigChange input

1644 

1645In addition to the [common input fields](#common-input-fields), ConfigChange hooks receive `source` and optionally `file_path`. The `source` field indicates which configuration type changed, and `file_path` provides the path to the specific file that was modified.

1646 

1647```json theme={null}

1648{

1649 "session_id": "abc123",

1650 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1651 "cwd": "/Users/...",

1652 "hook_event_name": "ConfigChange",

1653 "source": "project_settings",

1654 "file_path": "/Users/.../my-project/.claude/settings.json"

1655}

1656```

1657 

1658#### ConfigChange decision control

1659 

1660ConfigChange hooks can block configuration changes from taking effect. Use exit code 2 or a JSON `decision` to prevent the change. When blocked, the new settings are not applied to the running session.

1661 

1662| Field | Description |

1663| :--------- | :--------------------------------------------------------------------------------------- |

1664| `decision` | `"block"` prevents the configuration change from being applied. Omit to allow the change |

1665| `reason` | Explanation shown to the user when `decision` is `"block"` |

1666 

1667```json theme={null}

1668{

1669 "decision": "block",

1670 "reason": "Configuration changes to project settings require admin approval"

1671}

1672```

1673 

1674`policy_settings` changes cannot be blocked. Hooks still fire for `policy_settings` sources, so you can use them for audit logging, but any blocking decision is ignored. This ensures enterprise-managed settings always take effect.

1675 

1676### CwdChanged

1677 

1678Runs 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.

1679 

1680CwdChanged 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.

1681 

1682CwdChanged does not support matchers and fires on every directory change.

1683 

1684#### CwdChanged input

1685 

1686In addition to the [common input fields](#common-input-fields), CwdChanged hooks receive `old_cwd` and `new_cwd`.

1687 

1688```json theme={null}

1689{

1690 "session_id": "abc123",

1691 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

1692 "cwd": "/Users/my-project/src",

1693 "hook_event_name": "CwdChanged",

1694 "old_cwd": "/Users/my-project",

1695 "new_cwd": "/Users/my-project/src"

1696}

1697```

1698 

1699#### CwdChanged output

1700 

1701In addition to the [JSON output fields](#json-output) available to all hooks, CwdChanged hooks can return `watchPaths` to dynamically set which file paths [FileChanged](#filechanged) watches:

1702 

1703| Field | Description |

1704| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

1705| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Returning an empty array clears the dynamic list, which is typical when entering a new directory |

1706 

1707CwdChanged hooks have no decision control. They cannot block the directory change.

1708 

1709### FileChanged

1710 

1711Runs when a watched file changes on disk. The `matcher` field in your hook configuration controls which filenames to watch: it is a pipe-separated list of basenames (filenames without directory paths, for example `".envrc|.env"`). The same `matcher` value is also used to filter which hooks run when a file changes, matching against the basename of the changed file. Useful for reloading environment variables when project configuration files are modified.

1712 

1713FileChanged 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.

1714 

1715#### FileChanged input

1716 

1717In addition to the [common input fields](#common-input-fields), FileChanged hooks receive `file_path` and `event`.

1718 

1719| Field | Description |

1720| :---------- | :---------------------------------------------------------------------------------------------- |

1721| `file_path` | Absolute path to the file that changed |

1722| `event` | What happened: `"change"` (file modified), `"add"` (file created), or `"unlink"` (file deleted) |

1723 

1724```json theme={null}

1725{

1726 "session_id": "abc123",

1727 "transcript_path": "/Users/.../.claude/projects/.../transcript.jsonl",

1728 "cwd": "/Users/my-project",

1729 "hook_event_name": "FileChanged",

1730 "file_path": "/Users/my-project/.envrc",

1731 "event": "change"

1732}

1733```

1734 

1735#### FileChanged output

1736 

1737In addition to the [JSON output fields](#json-output) available to all hooks, FileChanged hooks can return `watchPaths` to dynamically update which file paths are watched:

1738 

1739| Field | Description |

1740| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

1741| `watchPaths` | Array of absolute paths. Replaces the current dynamic watch list (paths from your `matcher` configuration are always watched). Use this when your hook script discovers additional files to watch based on the changed file |

1742 

1743FileChanged hooks have no decision control. They cannot block the file change from occurring.

1744 

1745### WorktreeCreate

1746 

1747When 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.

1748 

1749Because 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.

1750 

1751The 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`.

1752 

1753This example creates an SVN working copy and prints the path for Claude Code to use. Replace the repository URL with your own:

1754 

1755```json theme={null}

1756{

1757 "hooks": {

1758 "WorktreeCreate": [

1759 {

1760 "hooks": [

1761 {

1762 "type": "command",

1763 "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'"

1764 }

1765 ]

1766 }

1767 ]

504 }1768 }

505}1769}

506```1770```

507 1771 

508### Notification Input1772The hook reads the worktree `name` from the JSON input on stdin, checks out a fresh copy into a new directory, and prints the directory path. The `echo` on the last line is what Claude Code reads as the worktree path. Redirect any other output to stderr so it doesn't interfere with the path.

1773 

1774#### WorktreeCreate input

1775 

1776In addition to the [common input fields](#common-input-fields), WorktreeCreate hooks receive the `name` field. This is a slug identifier for the new worktree, either specified by the user or auto-generated (for example, `bold-oak-a3f2`).

509 1777 

510```json theme={null}1778```json theme={null}

511{1779{

512 "session_id": "abc123",1780 "session_id": "abc123",

513 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1781 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

514 "cwd": "/Users/...",1782 "cwd": "/Users/...",

515 "permission_mode": "default",1783 "hook_event_name": "WorktreeCreate",

516 "hook_event_name": "Notification",1784 "name": "feature-auth"

517 "message": "Task completed successfully"

518}1785}

519```1786```

520 1787 

521### UserPromptSubmit Input1788#### WorktreeCreate output

1789 

1790WorktreeCreate hooks do not use the standard allow/block decision model. Instead, the hook's success or failure determines the outcome. The hook must return the absolute path to the created worktree directory:

1791 

1792* **Command hooks** (`type: "command"`): print the path on stdout.

1793* **HTTP hooks** (`type: "http"`): return `{ "hookSpecificOutput": { "hookEventName": "WorktreeCreate", "worktreePath": "/absolute/path" } }` in the response body.

1794 

1795If the hook fails or produces no path, worktree creation fails with an error.

1796 

1797### WorktreeRemove

1798 

1799The cleanup counterpart to [WorktreeCreate](#worktreecreate). This hook fires when a worktree is being removed, either when you exit a `--worktree` session and choose to remove it, or when a subagent with `isolation: "worktree"` finishes. For git-based worktrees, Claude handles cleanup automatically with `git worktree remove`. If you configured a WorktreeCreate hook for a non-git version control system, pair it with a WorktreeRemove hook to handle cleanup. Without one, the worktree directory is left on disk.

1800 

1801Claude Code passes the path returned by WorktreeCreate as `worktree_path` in the hook input. This example reads that path and removes the directory:

522 1802 

523```json theme={null}1803```json theme={null}

524{1804{

525 "session_id": "abc123",1805 "hooks": {

526 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1806 "WorktreeRemove": [

527 "cwd": "/Users/...",1807 {

528 "permission_mode": "default",1808 "hooks": [

529 "hook_event_name": "UserPromptSubmit",1809 {

530 "prompt": "Write a function to calculate the factorial of a number"1810 "type": "command",

1811 "command": "bash -c 'jq -r .worktree_path | xargs rm -rf'"

1812 }

1813 ]

1814 }

1815 ]

1816 }

531}1817}

532```1818```

533 1819 

534### Stop and SubagentStop Input1820#### WorktreeRemove input

535 1821 

536`stop_hook_active` is true when Claude Code is already continuing as a result of1822In addition to the [common input fields](#common-input-fields), WorktreeRemove hooks receive the `worktree_path` field, which is the absolute path to the worktree being removed.

537a stop hook. Check this value or process the transcript to prevent Claude Code

538from running indefinitely.

539 1823 

540```json theme={null}1824```json theme={null}

541{1825{

542 "session_id": "abc123",1826 "session_id": "abc123",

543 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1827 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

544 "permission_mode": "default",1828 "cwd": "/Users/...",

545 "hook_event_name": "Stop",1829 "hook_event_name": "WorktreeRemove",

546 "stop_hook_active": true1830 "worktree_path": "/Users/.../my-project/.claude/worktrees/feature-auth"

547}1831}

548```1832```

549 1833 

550### PreCompact Input1834WorktreeRemove hooks have no decision control. They cannot block worktree removal but can perform cleanup tasks like removing version control state or archiving changes. Hook failures are logged in debug mode only.

1835 

1836### PreCompact

1837 

1838Runs before Claude Code is about to run a compact operation.

1839 

1840The matcher value indicates whether compaction was triggered manually or automatically:

1841 

1842| Matcher | When it fires |

1843| :------- | :------------------------------------------- |

1844| `manual` | `/compact` |

1845| `auto` | Auto-compact when the context window is full |

551 1846 

552For `manual`, `custom_instructions` comes from what the user passes into1847#### PreCompact input

553`/compact`. For `auto`, `custom_instructions` is empty.1848 

1849In addition to the [common input fields](#common-input-fields), PreCompact hooks receive `trigger` and `custom_instructions`. For `manual`, `custom_instructions` contains what the user passes into `/compact`. For `auto`, `custom_instructions` is empty.

554 1850 

555```json theme={null}1851```json theme={null}

556{1852{

557 "session_id": "abc123",1853 "session_id": "abc123",

558 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1854 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

559 "permission_mode": "default",1855 "cwd": "/Users/...",

560 "hook_event_name": "PreCompact",1856 "hook_event_name": "PreCompact",

561 "trigger": "manual",1857 "trigger": "manual",

562 "custom_instructions": ""1858 "custom_instructions": ""

563}1859}

564```1860```

565 1861 

566### SessionStart Input1862### PostCompact

567 1863 

568```json theme={null}1864Runs after Claude Code completes a compact operation. Use this event to react to the new compacted state, for example to log the generated summary or update external state.

569{1865 

570 "session_id": "abc123",1866The same matcher values apply as for `PreCompact`:

571 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

572 "permission_mode": "default",

573 "hook_event_name": "SessionStart",

574 "source": "startup"

575}

576```

577 1867 

578### SessionEnd Input1868| Matcher | When it fires |

1869| :------- | :------------------------------------------------- |

1870| `manual` | After `/compact` |

1871| `auto` | After auto-compact when the context window is full |

1872 

1873#### PostCompact input

1874 

1875In addition to the [common input fields](#common-input-fields), PostCompact hooks receive `trigger` and `compact_summary`. The `compact_summary` field contains the conversation summary generated by the compact operation.

579 1876 

580```json theme={null}1877```json theme={null}

581{1878{

582 "session_id": "abc123",1879 "session_id": "abc123",

583 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1880 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

584 "cwd": "/Users/...",1881 "cwd": "/Users/...",

585 "permission_mode": "default",1882 "hook_event_name": "PostCompact",

586 "hook_event_name": "SessionEnd",1883 "trigger": "manual",

587 "reason": "exit"1884 "compact_summary": "Summary of the compacted conversation..."

588}1885}

589```1886```

590 1887 

591## Hook Output1888PostCompact hooks have no decision control. They cannot affect the compaction result but can perform follow-up tasks.

592 

593There are two ways for hooks to return output back to Claude Code. The output

594communicates whether to block and any feedback that should be shown to Claude

595and the user.

596 1889 

597### Simple: Exit Code1890### SessionEnd

598 

599Hooks communicate status through exit codes, stdout, and stderr:

600 

601* **Exit code 0**: Success. `stdout` is shown to the user in transcript mode

602 (CTRL-R), except for `UserPromptSubmit` and `SessionStart`, where stdout is

603 added to the context.

604* **Exit code 2**: Blocking error. `stderr` is fed back to Claude to process

605 automatically. See per-hook-event behavior below.

606* **Other exit codes**: Non-blocking error. `stderr` is shown to the user and

607 execution continues.

608 

609<Warning>

610 Reminder: Claude Code does not see stdout if the exit code is 0, except for

611 the `UserPromptSubmit` hook where stdout is injected as context.

612</Warning>

613 

614#### Exit Code 2 Behavior

615 1891 

616| Hook Event | Behavior |1892Runs when a Claude Code session ends. Useful for cleanup tasks, logging session

617| ------------------ | ------------------------------------------------------------------ |1893statistics, or saving session state. Supports matchers to filter by exit reason.

618| `PreToolUse` | Blocks the tool call, shows stderr to Claude |

619| `PostToolUse` | Shows stderr to Claude (tool already ran) |

620| `Notification` | N/A, shows stderr to user only |

621| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |

622| `Stop` | Blocks stoppage, shows stderr to Claude |

623| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |

624| `PreCompact` | N/A, shows stderr to user only |

625| `SessionStart` | N/A, shows stderr to user only |

626| `SessionEnd` | N/A, shows stderr to user only |

627 1894 

628### Advanced: JSON Output1895The `reason` field in the hook input indicates why the session ended:

629 1896 

630Hooks can return structured JSON in `stdout` for more sophisticated control:1897| Reason | Description |

1898| :---------------------------- | :----------------------------------------- |

1899| `clear` | Session cleared with `/clear` command |

1900| `resume` | Session switched via interactive `/resume` |

1901| `logout` | User logged out |

1902| `prompt_input_exit` | User exited while prompt input was visible |

1903| `bypass_permissions_disabled` | Bypass permissions mode was disabled |

1904| `other` | Other exit reasons |

631 1905 

632#### Common JSON Fields1906#### SessionEnd input

633 1907 

634All hook types can include these optional fields:1908In addition to the [common input fields](#common-input-fields), SessionEnd hooks receive a `reason` field indicating why the session ended. See the [reason table](#sessionend) above for all values.

635 1909 

636```json theme={null}1910```json theme={null}

637{1911{

638 "continue": true, // Whether Claude should continue after hook execution (default: true)1912 "session_id": "abc123",

639 "stopReason": "string", // Message shown when continue is false1913 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

640 1914 "cwd": "/Users/...",

641 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1915 "hook_event_name": "SessionEnd",

642 "systemMessage": "string" // Optional warning message shown to the user1916 "reason": "other"

643}1917}

644```1918```

645 1919 

646If `continue` is false, Claude stops processing after the hooks run.1920SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.

1921 

1922SessionEnd hooks have a default timeout of 1.5 seconds. This applies to session exit, `/clear`, and switching sessions via interactive `/resume`. If your hooks need more time, set the `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` environment variable to a higher value in milliseconds. Any per-hook `timeout` setting is also capped by this value.

647 1923 

648* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which1924```bash theme={null}

649 only blocks a specific tool call and provides automatic feedback to Claude.1925CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS=5000 claude

650* For `PostToolUse`, this is different from `"decision": "block"`, which1926```

651 provides automated feedback to Claude.

652* For `UserPromptSubmit`, this prevents the prompt from being processed.

653* For `Stop` and `SubagentStop`, this takes precedence over any

654 `"decision": "block"` output.

655* In all cases, `"continue" = false` takes precedence over any

656 `"decision": "block"` output.

657 1927 

658`stopReason` accompanies `continue` with a reason shown to the user, not shown1928### Elicitation

659to Claude.

660 1929 

661#### `PreToolUse` Decision Control1930Runs when an MCP server requests user input mid-task. By default, Claude Code shows an interactive dialog for the user to respond. Hooks can intercept this request and respond programmatically, skipping the dialog entirely.

662 1931 

663`PreToolUse` hooks can control whether a tool call proceeds.1932The matcher field matches against the MCP server name.

664 1933 

665* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown1934#### Elicitation input

666 to the user but not to Claude.

667* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is

668 shown to Claude.

669* `"ask"` asks the user to confirm the tool call in the UI.

670 `permissionDecisionReason` is shown to the user but not to Claude.

671 1935 

672Additionally, hooks can modify tool inputs before execution using `updatedInput`:1936In addition to the [common input fields](#common-input-fields), Elicitation hooks receive `mcp_server_name`, `message`, and optional `mode`, `url`, `elicitation_id`, and `requested_schema` fields.

673 1937 

674* `updatedInput` allows you to modify the tool's input parameters before the tool executes. This is a `Record<string, unknown>` object containing the fields you want to change or add.1938For form-mode elicitation (the most common case):

675* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.

676 1939 

677```json theme={null}1940```json theme={null}

678{1941{

679 "hookSpecificOutput": {1942 "session_id": "abc123",

680 "hookEventName": "PreToolUse",1943 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

681 "permissionDecision": "allow"1944 "cwd": "/Users/...",

682 "permissionDecisionReason": "My reason here",1945 "permission_mode": "default",

683 "updatedInput": {1946 "hook_event_name": "Elicitation",

684 "field_to_modify": "new value"1947 "mcp_server_name": "my-mcp-server",

1948 "message": "Please provide your credentials",

1949 "mode": "form",

1950 "requested_schema": {

1951 "type": "object",

1952 "properties": {

1953 "username": { "type": "string", "title": "Username" }

685 }1954 }

686 }1955 }

687}1956}

688```1957```

689 1958 

690<Note>1959For URL-mode elicitation (browser-based authentication):

691 The `decision` and `reason` fields are deprecated for PreToolUse hooks.

692 Use `hookSpecificOutput.permissionDecision` and

693 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields

694 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.

695</Note>

696 

697#### `PostToolUse` Decision Control

698 

699`PostToolUse` hooks can provide feedback to Claude after tool execution.

700 

701* `"block"` automatically prompts Claude with `reason`.

702* `undefined` does nothing. `reason` is ignored.

703* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.

704 1960 

705```json theme={null}1961```json theme={null}

706{1962{

707 "decision": "block" | undefined,1963 "session_id": "abc123",

708 "reason": "Explanation for decision",1964 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

709 "hookSpecificOutput": {1965 "cwd": "/Users/...",

710 "hookEventName": "PostToolUse",1966 "permission_mode": "default",

711 "additionalContext": "Additional information for Claude"1967 "hook_event_name": "Elicitation",

712 }1968 "mcp_server_name": "my-mcp-server",

1969 "message": "Please authenticate",

1970 "mode": "url",

1971 "url": "https://auth.example.com/login"

713}1972}

714```1973```

715 1974 

716#### `PostCustomToolCall` Output Control1975#### Elicitation output

717 

718`PostCustomToolCall` hooks can modify MCP tool outputs before they're processed further.

719 1976 

720* `"hookSpecificOutput.updatedOutput"` replaces the original tool response1977To respond programmatically without showing the dialog, return a JSON object with `hookSpecificOutput`:

721* The modified output is shown to Claude instead of the original response

722* This runs **before** `PostToolUse` hooks, so they see the modified output

723 1978 

724```json theme={null}1979```json theme={null}

725{1980{

726 "hookSpecificOutput": {1981 "hookSpecificOutput": {

727 "hookEventName": "PostCustomToolCall",1982 "hookEventName": "Elicitation",

728 "updatedOutput": {1983 "action": "accept",

729 "issue_number": 42,1984 "content": {

730 "url": "https://github.com/org/repo/issues/42",1985 "username": "alice"

731 "hook_processed": true,

732 "processed_at": "2025-01-01T00:00:00Z"

733 }1986 }

734 }1987 }

735}1988}

736```1989```

737 1990 

738**Example: Adding metadata to MCP tool responses**1991| Field | Values | Description |

1992| :-------- | :---------------------------- | :--------------------------------------------------------------- |

1993| `action` | `accept`, `decline`, `cancel` | Whether to accept, decline, or cancel the request |

1994| `content` | object | Form field values to submit. Only used when `action` is `accept` |

739 1995 

740```bash theme={null}1996Exit code 2 denies the elicitation and shows stderr to the user.

741#!/bin/bash

742# Read JSON input from stdin

743INPUT=$(cat)

744 1997 

745# Extract tool information1998### ElicitationResult

746TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')

747TOOL_RESPONSE=$(echo "$INPUT" | jq -r '.tool_response')

748 1999 

749# Only process MCP tools2000Runs after a user responds to an MCP elicitation. Hooks can observe, modify, or block the response before it is sent back to the MCP server.

750if [[ "$TOOL_NAME" != mcp__* ]]; then

751 exit 0

752fi

753 2001 

754# Add metadata to the response2002The matcher field matches against the MCP server name.

755UPDATED_OUTPUT=$(echo "$TOOL_RESPONSE" | jq '. + {"hook_processed": true, "processed_at": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"}')

756 2003 

757# Output the modified response2004#### ElicitationResult input

758jq -n --argjson output "$UPDATED_OUTPUT" '{

759 "hookSpecificOutput": {

760 "hookEventName": "PostCustomToolCall",

761 "updatedOutput": $output

762 }

763}'

764```

765 2005 

766<Warning>2006In addition to the [common input fields](#common-input-fields), ElicitationResult hooks receive `mcp_server_name`, `action`, and optional `mode`, `elicitation_id`, and `content` fields.

767 If multiple hooks provide `updatedOutput` for the same tool call, conflicts may occur since hooks run in parallel. Only configure one hook per tool to modify output.

768</Warning>

769 2007 

770#### `UserPromptSubmit` Decision Control2008```json theme={null}

2009{

2010 "session_id": "abc123",

2011 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

2012 "cwd": "/Users/...",

2013 "permission_mode": "default",

2014 "hook_event_name": "ElicitationResult",

2015 "mcp_server_name": "my-mcp-server",

2016 "action": "accept",

2017 "content": { "username": "alice" },

2018 "mode": "form",

2019 "elicitation_id": "elicit-123"

2020}

2021```

771 2022 

772`UserPromptSubmit` hooks can control whether a user prompt is processed.2023#### ElicitationResult output

773 2024 

774* `"block"` prevents the prompt from being processed. The submitted prompt is2025To override the user's response, return a JSON object with `hookSpecificOutput`:

775 erased from context. `"reason"` is shown to the user but not added to context.

776* `undefined` allows the prompt to proceed normally. `"reason"` is ignored.

777* `"hookSpecificOutput.additionalContext"` adds the string to the context if not

778 blocked.

779 2026 

780```json theme={null}2027```json theme={null}

781{2028{

782 "decision": "block" | undefined,

783 "reason": "Explanation for decision",

784 "hookSpecificOutput": {2029 "hookSpecificOutput": {

785 "hookEventName": "UserPromptSubmit",2030 "hookEventName": "ElicitationResult",

786 "additionalContext": "My additional context here"2031 "action": "decline",

2032 "content": {}

787 }2033 }

788}2034}

789```2035```

790 2036 

791#### `Stop`/`SubagentStop` Decision Control2037| Field | Values | Description |

2038| :-------- | :---------------------------- | :--------------------------------------------------------------------- |

2039| `action` | `accept`, `decline`, `cancel` | Overrides the user's action |

2040| `content` | object | Overrides form field values. Only meaningful when `action` is `accept` |

2041 

2042Exit code 2 blocks the response, changing the effective action to `decline`.

2043 

2044## Prompt-based hooks

2045 

2046In 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.

2047 

2048Events that support all four hook types (`command`, `http`, `prompt`, and `agent`):

2049 

2050* `PermissionRequest`

2051* `PostToolUse`

2052* `PostToolUseFailure`

2053* `PreToolUse`

2054* `Stop`

2055* `SubagentStop`

2056* `TaskCompleted`

2057* `TaskCreated`

2058* `UserPromptSubmit`

2059 

2060Events that support `command` and `http` hooks but not `prompt` or `agent`:

2061 

2062* `ConfigChange`

2063* `CwdChanged`

2064* `Elicitation`

2065* `ElicitationResult`

2066* `FileChanged`

2067* `InstructionsLoaded`

2068* `Notification`

2069* `PermissionDenied`

2070* `PostCompact`

2071* `PreCompact`

2072* `SessionEnd`

2073* `StopFailure`

2074* `SubagentStart`

2075* `TeammateIdle`

2076* `WorktreeCreate`

2077* `WorktreeRemove`

2078 

2079`SessionStart` supports only `command` hooks.

792 2080 

793`Stop` and `SubagentStop` hooks can control whether Claude must continue.2081### How prompt-based hooks work

794 2082 

795* `"block"` prevents Claude from stopping. You must populate `reason` for Claude2083Instead of executing a Bash command, prompt-based hooks:

796 to know how to proceed.

797* `undefined` allows Claude to stop. `reason` is ignored.

798 2084 

799```json theme={null}20851. Send the hook input and your prompt to a Claude model, Haiku by default

800{20862. The LLM responds with structured JSON containing a decision

801 "decision": "block" | undefined,20873. Claude Code processes the decision automatically

802 "reason": "Must be provided when Claude is blocked from stopping"

803}

804```

805 2088 

806#### `SessionStart` Decision Control2089### Prompt hook configuration

807 2090 

808`SessionStart` hooks allow you to load in context at the start of a session.2091Set `type` to `"prompt"` and provide a `prompt` string instead of a `command`. Use the `$ARGUMENTS` placeholder to inject the hook's JSON input data into your prompt text. Claude Code sends the combined prompt and input to a fast Claude model, which returns a JSON decision.

809 2092 

810* `"hookSpecificOutput.additionalContext"` adds the string to the context.2093This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:

811* Multiple hooks' `additionalContext` values are concatenated.

812 2094 

813```json theme={null}2095```json theme={null}

814{2096{

815 "hookSpecificOutput": {2097 "hooks": {

816 "hookEventName": "SessionStart",2098 "Stop": [

817 "additionalContext": "My additional context here"2099 {

2100 "hooks": [

2101 {

2102 "type": "prompt",

2103 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."

2104 }

2105 ]

2106 }

2107 ]

818 }2108 }

819}2109}

820```2110```

821 2111 

822#### `SessionEnd` Decision Control2112| Field | Required | Description |

823 2113| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

824`SessionEnd` hooks run when a session ends. They cannot block session termination2114| `type` | yes | Must be `"prompt"` |

825but can perform cleanup tasks.2115| `prompt` | yes | The prompt text to send to the LLM. Use `$ARGUMENTS` as a placeholder for the hook input JSON. If `$ARGUMENTS` is not present, input JSON is appended to the prompt |

826 2116| `model` | no | Model to use for evaluation. Defaults to a fast model |

827#### Exit Code Example: Bash Command Validation2117| `timeout` | no | Timeout in seconds. Default: 30 |

828 

829```python theme={null}

830#!/usr/bin/env python3

831import json

832import re

833import sys

834 

835# Define validation rules as a list of (regex pattern, message) tuples

836VALIDATION_RULES = [

837 (

838 r"\bgrep\b(?!.*\|)",

839 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",

840 ),

841 (

842 r"\bfind\s+\S+\s+-name\b",

843 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",

844 ),

845]

846 

847 2118 

848def validate_command(command: str) -> list[str]:2119### Response schema

849 issues = []

850 for pattern, message in VALIDATION_RULES:

851 if re.search(pattern, command):

852 issues.append(message)

853 return issues

854 2120 

2121The LLM must respond with JSON containing:

855 2122 

856try:2123```json theme={null}

857 input_data = json.load(sys.stdin)2124{

858except json.JSONDecodeError as e:2125 "ok": true | false,

859 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)2126 "reason": "Explanation for the decision"

860 sys.exit(1)2127}

2128```

861 2129 

862tool_name = input_data.get("tool_name", "")2130| Field | Description |

863tool_input = input_data.get("tool_input", {})2131| :------- | :--------------------------------------------------------- |

864command = tool_input.get("command", "")2132| `ok` | `true` allows the action, `false` prevents it |

2133| `reason` | Required when `ok` is `false`. Explanation shown to Claude |

865 2134 

866if tool_name != "Bash" or not command:2135### Example: Multi-criteria Stop hook

867 sys.exit(1)

868 2136 

869# Validate the command2137This `Stop` hook uses a detailed prompt to check three conditions before allowing Claude to stop. If `"ok"` is `false`, Claude continues working with the provided reason as its next instruction. `SubagentStop` hooks use the same format to evaluate whether a [subagent](/en/sub-agents) should stop:

870issues = validate_command(command)

871 2138 

872if issues:2139```json theme={null}

873 for message in issues:2140{

874 print(f"• {message}", file=sys.stderr)2141 "hooks": {

875 # Exit code 2 blocks tool call and shows stderr to Claude2142 "Stop": [

876 sys.exit(2)2143 {

2144 "hooks": [

2145 {

2146 "type": "prompt",

2147 "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.",

2148 "timeout": 30

2149 }

2150 ]

2151 }

2152 ]

2153 }

2154}

877```2155```

878 2156 

879#### JSON Output Example: UserPromptSubmit to Add Context and Validation2157## Agent-based hooks

880 2158 

881<Note>2159Agent-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.

882 For `UserPromptSubmit` hooks, you can inject context using either method:

883 2160 

884 * Exit code 0 with stdout: Claude sees the context (special case for `UserPromptSubmit`)2161### How agent hooks work

885 * JSON output: Provides more control over the behavior

886</Note>

887 2162 

888```python theme={null}2163When an agent hook fires:

889#!/usr/bin/env python3

890import json

891import sys

892import re

893import datetime

894 

895# Load input from stdin

896try:

897 input_data = json.load(sys.stdin)

898except json.JSONDecodeError as e:

899 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

900 sys.exit(1)

901 

902prompt = input_data.get("prompt", "")

903 

904# Check for sensitive patterns

905sensitive_patterns = [

906 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),

907]

908 

909for pattern, message in sensitive_patterns:

910 if re.search(pattern, prompt):

911 # Use JSON output to block with a specific reason

912 output = {

913 "decision": "block",

914 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."

915 }

916 print(json.dumps(output))

917 sys.exit(0)

918 2164 

919# Add current time to context21651. Claude Code spawns a subagent with your prompt and the hook's JSON input

920context = f"Current time: {datetime.datetime.now()}"21662. The subagent can use tools like Read, Grep, and Glob to investigate

921print(context)21673. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision

21684. Claude Code processes the decision the same way as a prompt hook

922 2169 

923"""2170Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.

924The following is also equivalent:

925print(json.dumps({

926 "hookSpecificOutput": {

927 "hookEventName": "UserPromptSubmit",

928 "additionalContext": context,

929 },

930}))

931"""

932 2171 

933# Allow the prompt to proceed with the additional context2172### Agent hook configuration

934sys.exit(0)

935```

936 2173 

937#### JSON Output Example: PreToolUse with Approval2174Set `type` to `"agent"` and provide a `prompt` string. The configuration fields are the same as [prompt hooks](#prompt-hook-configuration), with a longer default timeout:

938 2175 

939```python theme={null}2176| Field | Required | Description |

940#!/usr/bin/env python32177| :-------- | :------- | :------------------------------------------------------------------------------------------ |

941import json2178| `type` | yes | Must be `"agent"` |

942import sys2179| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

2180| `model` | no | Model to use. Defaults to a fast model |

2181| `timeout` | no | Timeout in seconds. Default: 60 |

943 2182 

944# Load input from stdin2183The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.

945try:

946 input_data = json.load(sys.stdin)

947except json.JSONDecodeError as e:

948 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

949 sys.exit(1)

950 2184 

951tool_name = input_data.get("tool_name", "")2185This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:

952tool_input = input_data.get("tool_input", {})

953 2186 

954# Example: Auto-approve file reads for documentation files2187```json theme={null}

955if tool_name == "Read":2188{

956 file_path = tool_input.get("file_path", "")2189 "hooks": {

957 if file_path.endswith((".md", ".mdx", ".txt", ".json")):2190 "Stop": [

958 # Use JSON output to auto-approve the tool call2191 {

959 output = {2192 "hooks": [

960 "decision": "approve",2193 {

961 "reason": "Documentation file auto-approved",2194 "type": "agent",

962 "suppressOutput": True # Don't show in transcript mode2195 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

2196 "timeout": 120

963 }2197 }

964 print(json.dumps(output))2198 ]

965 sys.exit(0)2199 }

966 2200 ]

967# For other cases, let the normal permission flow proceed2201 }

968sys.exit(0)2202}

969```2203```

970 2204 

971## Working with MCP Tools2205## Run hooks in the background

972 

973Claude Code hooks work seamlessly with

974[Model Context Protocol (MCP) tools](/en/docs/claude-code/mcp). When MCP servers

975provide tools, they appear with a special naming pattern that you can match in

976your hooks.

977 

978### MCP Tool Naming

979 2206 

980MCP tools follow the pattern `mcp__<server>__<tool>`, for example:2207By default, hooks block Claude's execution until they complete. For long-running tasks like deployments, test suites, or external API calls, set `"async": true` to run the hook in the background while Claude continues working. Async hooks cannot block or control Claude's behavior: response fields like `decision`, `permissionDecision`, and `continue` have no effect, because the action they would have controlled has already completed.

981 2208 

982* `mcp__memory__create_entities` - Memory server's create entities tool2209### Configure an async hook

983* `mcp__filesystem__read_file` - Filesystem server's read file tool

984* `mcp__github__search_repositories` - GitHub server's search tool

985 2210 

986### Configuring Hooks for MCP Tools2211Add `"async": true` to a command hook's configuration to run it in the background without blocking Claude. This field is only available on `type: "command"` hooks.

987 2212 

988You can target specific MCP tools or entire MCP servers:2213This hook runs a test script after every `Write` tool call. Claude continues working immediately while `run-tests.sh` executes for up to 120 seconds. When the script finishes, its output is delivered on the next conversation turn:

989 2214 

990```json theme={null}2215```json theme={null}

991{2216{

992 "hooks": {2217 "hooks": {

993 "PreToolUse": [2218 "PostToolUse": [

994 {

995 "matcher": "mcp__memory__.*",

996 "hooks": [

997 {

998 "type": "command",

999 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

1000 }

1001 ]

1002 },

1003 {2219 {

1004 "matcher": "mcp__.*__write.*",2220 "matcher": "Write",

1005 "hooks": [2221 "hooks": [

1006 {2222 {

1007 "type": "command",2223 "type": "command",

1008 "command": "/home/user/scripts/validate-mcp-write.py"2224 "command": "/path/to/run-tests.sh",

2225 "async": true,

2226 "timeout": 120

1009 }2227 }

1010 ]2228 ]

1011 }2229 }


1014}2232}

1015```2233```

1016 2234 

1017## Examples2235The `timeout` field sets the maximum time in seconds for the background process. If not specified, async hooks use the same 10-minute default as sync hooks.

1018 

1019<Tip>

1020 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/docs/claude-code/hooks-guide#more-examples) in the get started guide.

1021</Tip>

1022 2236 

1023## Security Considerations2237### How async hooks execute

1024 2238 

1025### Disclaimer2239When an async hook fires, Claude Code starts the hook process and immediately continues without waiting for it to finish. The hook receives the same JSON input via stdin as a synchronous hook.

1026 2240 

1027**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on2241After the background process exits, if the hook produced a JSON response with a `systemMessage` or `additionalContext` field, that content is delivered to Claude as context on the next conversation turn.

1028your system automatically. By using hooks, you acknowledge that:

1029 2242 

1030* You are solely responsible for the commands you configure2243Async hook completion notifications are suppressed by default. To see them, enable verbose mode with `Ctrl+O` or start Claude Code with `--verbose`.

1031* Hooks can modify, delete, or access any files your user account can access

1032* Malicious or poorly written hooks can cause data loss or system damage

1033* Anthropic provides no warranty and assumes no liability for any damages

1034 resulting from hook usage

1035* You should thoroughly test hooks in a safe environment before production use

1036 2244 

1037Always review and understand any hook commands before adding them to your2245### Example: run tests after file changes

1038configuration.

1039 2246 

1040### Security Best Practices2247This hook starts a test suite in the background whenever Claude writes a file, then reports the results back to Claude when the tests finish. Save this script to `.claude/hooks/run-tests-async.sh` in your project and make it executable with `chmod +x`:

1041 2248 

1042Here are some key practices for writing more secure hooks:2249```bash theme={null}

2250#!/bin/bash

2251# run-tests-async.sh

1043 2252 

10441. **Validate and sanitize inputs** - Never trust input data blindly2253# Read hook input from stdin

10452. **Always quote shell variables** - Use `"$VAR"` not `$VAR`2254INPUT=$(cat)

10463. **Block path traversal** - Check for `..` in file paths2255FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

10474. **Use absolute paths** - Specify full paths for scripts (use

1048 "\$CLAUDE\_PROJECT\_DIR" for the project path)

10495. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.

1050 2256 

1051### Configuration Safety2257# Only run tests for source files

2258if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then

2259 exit 0

2260fi

1052 2261 

1053Direct edits to hooks in settings files don't take effect immediately. Claude2262# Run tests and report results via systemMessage

1054Code:2263RESULT=$(npm test 2>&1)

2264EXIT_CODE=$?

1055 2265 

10561. Captures a snapshot of hooks at startup2266if [ $EXIT_CODE -eq 0 ]; then

10572. Uses this snapshot throughout the session2267 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"

10583. Warns if hooks are modified externally2268else

10594. Requires review in `/hooks` menu for changes to apply2269 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"

2270fi

2271```

1060 2272 

1061This prevents malicious hook modifications from affecting your current session.2273Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:

1062 2274 

1063## Hook Execution Details2275```json theme={null}

2276{

2277 "hooks": {

2278 "PostToolUse": [

2279 {

2280 "matcher": "Write|Edit",

2281 "hooks": [

2282 {

2283 "type": "command",

2284 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",

2285 "async": true,

2286 "timeout": 300

2287 }

2288 ]

2289 }

2290 ]

2291 }

2292}

2293```

1064 2294 

1065* **Timeout**: 60-second execution limit by default, configurable per command.2295### Limitations

1066 * A timeout for an individual command does not affect the other commands.

1067* **Parallelization**: All matching hooks run in parallel

1068* **Deduplication**: Multiple identical hook commands are deduplicated automatically

1069* **Environment**: Runs in current directory with Claude Code's environment

1070 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the

1071 absolute path to the project root directory (where Claude Code was started)

1072 * The `CLAUDE_CODE_REMOTE` environment variable indicates whether the hook is running in a remote (web) environment (`"true"`) or local CLI environment (not set or empty). Use this to run different logic based on execution context.

1073* **Input**: JSON via stdin

1074* **Output**:

1075 * PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in transcript (Ctrl-R)

1076 * Notification/SessionEnd: Logged to debug only (`--debug`)

1077 * UserPromptSubmit/SessionStart: stdout added as context for Claude

1078 2296 

1079## Debugging2297Async hooks have several constraints compared to synchronous hooks:

1080 2298 

1081### Basic Troubleshooting2299* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.

2300* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.

2301* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.

2302* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.

1082 2303 

1083If your hooks aren't working:2304## Security considerations

1084 2305 

10851. **Check configuration** - Run `/hooks` to see if your hook is registered2306### Disclaimer

10862. **Verify syntax** - Ensure your JSON settings are valid

10873. **Test commands** - Run hook commands manually first

10884. **Check permissions** - Make sure scripts are executable

10895. **Review logs** - Use `claude --debug` to see hook execution details

1090 2307 

1091Common issues:2308Command hooks run with your system user's full permissions.

1092 2309 

1093* **Quotes not escaped** - Use `\"` inside JSON strings2310<Warning>

1094* **Wrong matcher** - Check tool names match exactly (case-sensitive)2311 Command hooks execute shell commands with your full user permissions. They can modify, delete, or access any files your user account can access. Review and test all hook commands before adding them to your configuration.

1095* **Command not found** - Use full paths for scripts2312</Warning>

1096 2313 

1097### Advanced Debugging2314### Security best practices

1098 2315 

1099For complex hook issues:2316Keep these practices in mind when writing hooks:

1100 2317 

11011. **Inspect hook execution** - Use `claude --debug` to see detailed hook2318* **Validate and sanitize inputs**: never trust input data blindly

1102 execution2319* **Always quote shell variables**: use `"$VAR"` not `$VAR`

11032. **Validate JSON schemas** - Test hook input/output with external tools2320* **Block path traversal**: check for `..` in file paths

11043. **Check environment variables** - Verify Claude Code's environment is correct2321* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root

11054. **Test edge cases** - Try hooks with unusual file paths or inputs2322* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.

11065. **Monitor system resources** - Check for resource exhaustion during hook

1107 execution

11086. **Use structured logging** - Implement logging in your hook scripts

1109 2323 

1110### Debug Output Example2324## Windows PowerShell tool

1111 2325 

1112Use `claude --debug` to see hook execution details:2326On Windows, you can run individual hooks in PowerShell by setting `"shell": "powershell"` on a command hook. Hooks spawn PowerShell directly, so this works regardless of whether `CLAUDE_CODE_USE_POWERSHELL_TOOL` is set. Claude Code auto-detects `pwsh.exe` (PowerShell 7+) with a fallback to `powershell.exe` (5.1).

1113 2327 

2328```json theme={null}

2329{

2330 "hooks": {

2331 "PostToolUse": [

2332 {

2333 "matcher": "Write",

2334 "hooks": [

2335 {

2336 "type": "command",

2337 "shell": "powershell",

2338 "command": "Write-Host 'File written'"

2339 }

2340 ]

2341 }

2342 ]

2343 }

2344}

1114```2345```

2346 

2347## Debug hooks

2348 

2349Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output.

2350 

2351```text theme={null}

1115[DEBUG] Executing hooks for PostToolUse:Write2352[DEBUG] Executing hooks for PostToolUse:Write

1116[DEBUG] Getting matching hook commands for PostToolUse with query: Write

1117[DEBUG] Found 1 hook matchers in settings

1118[DEBUG] Matched 1 hooks for query "Write"

1119[DEBUG] Found 1 hook commands to execute2353[DEBUG] Found 1 hook commands to execute

1120[DEBUG] Executing hook command: <Your command> with timeout 60000ms2354[DEBUG] Executing hook command: <Your command> with timeout 600000ms

1121[DEBUG] Hook command completed with status 0: <Your stdout>2355[DEBUG] Hook command completed with status 0: <Your stdout>

1122```2356```

1123 2357 

1124Progress messages appear in transcript mode (Ctrl-R) showing:2358For 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.

1125 2359 

1126* Which hook is running2360For 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.

1127* Command being executed

1128* Success/failure status

1129* Output or error messages

hooks-guide.md +723 −197

Details

1# Get started with Claude Code hooks1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Learn how to customize and extend Claude Code's behavior by registering shell commands5# Automate workflows with hooks

4 6 

5Claude Code hooks are user-defined shell commands that execute at various points7> Run shell commands automatically when Claude Code edits files, finishes tasks, or needs input. Format code, send notifications, validate commands, and enforce project rules.

6in Claude Code's lifecycle. Hooks provide deterministic control over Claude8 

7Code's behavior, ensuring certain actions always happen rather than relying on9Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide deterministic control over Claude Code's behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools.

8the LLM to choose to run them.10 

11For decisions that require judgment rather than deterministic rules, you can also use [prompt-based hooks](#prompt-based-hooks) or [agent-based hooks](#agent-based-hooks) that use a Claude model to evaluate conditions.

12 

13For other ways to extend Claude Code, see [skills](/en/skills) for giving Claude additional instructions and executable commands, [subagents](/en/sub-agents) for running tasks in isolated contexts, and [plugins](/en/plugins) for packaging extensions to share across projects.

9 14 

10<Tip>15<Tip>

11 For reference documentation on hooks, see [Hooks reference](/en/docs/claude-code/hooks).16 This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](/en/hooks).

12</Tip>17</Tip>

13 18 

14Example use cases for hooks include:19## Set up your first hook

15 20 

16* **Notifications**: Customize how you get notified when Claude Code is awaiting21To create a hook, add a `hooks` block to a [settings file](#configure-hook-location). This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.

17 your input or permission to run something.

18* **Automatic formatting**: Run `prettier` on .ts files, `gofmt` on .go files,

19 etc. after every file edit.

20* **Logging**: Track and count all executed commands for compliance or

21 debugging.

22* **Feedback**: Provide automated feedback when Claude Code produces code that

23 does not follow your codebase conventions.

24* **Custom permissions**: Block modifications to production files or sensitive

25 directories.

26 22 

27By encoding these rules as hooks rather than prompting instructions, you turn23<Steps>

28suggestions into app-level code that executes every time it is expected to run.24 <Step title="Add the hook to your settings">

25 Open `~/.claude/settings.json` and add a `Notification` hook. The example below uses `osascript` for macOS; see [Get notified when Claude needs input](#get-notified-when-claude-needs-input) for Linux and Windows commands.

29 26 

30<Warning>27 ```json theme={null}

31 You must consider the security implication of hooks as you add them, because hooks run automatically during the agent loop with your current environment's credentials.28 {

32 For example, malicious hooks code can exfiltrate your data. Always review your hooks implementation before registering them.29 "hooks": {

30 "Notification": [

31 {

32 "matcher": "",

33 "hooks": [

34 {

35 "type": "command",

36 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

37 }

38 ]

39 }

40 ]

41 }

42 }

43 ```

33 44 

34 For full security best practices, see [Security Considerations](/en/docs/claude-code/hooks#security-considerations) in the hooks reference documentation.45 If your settings file already has a `hooks` key, merge the `Notification` entry into it rather than replacing the whole object. You can also ask Claude to write the hook for you by describing what you want in the CLI.

35</Warning>46 </Step>

36 47 

37## Hook Events Overview48 <Step title="Verify the configuration">

49 Type `/hooks` to open the hooks browser. You'll see a list of all available hook events, with a count next to each event that has hooks configured. Select `Notification` to confirm your new hook appears in the list. Selecting the hook shows its details: the event, matcher, type, source file, and command.

50 </Step>

38 51 

39Claude Code provides several hook events that run at different points in the52 <Step title="Test the hook">

40workflow:53 Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.

54 </Step>

55</Steps>

41 56 

42* **PreToolUse**: Runs before tool calls (can block them)57<Tip>

43* **PostToolUse**: Runs after tool calls complete58 The `/hooks` menu is read-only. To add, modify, or remove hooks, edit your settings JSON directly or ask Claude to make the change.

44* **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it59</Tip>

45* **Notification**: Runs when Claude Code sends notifications

46* **Stop**: Runs when Claude Code finishes responding

47* **SubagentStop**: Runs when subagent tasks complete

48* **PreCompact**: Runs before Claude Code is about to run a compact operation

49* **SessionStart**: Runs when Claude Code starts a new session or resumes an existing session

50* **SessionEnd**: Runs when Claude Code session ends

51 60 

52Each event receives different data and can control Claude's behavior in61## What you can automate

53different ways.

54 62 

55## Quickstart63Hooks let you run code at key points in Claude Code's lifecycle: format files after edits, block commands before they execute, send notifications when Claude needs input, inject context at session start, and more. For the full list of hook events, see the [Hooks reference](/en/hooks#hook-lifecycle).

56 64 

57In this quickstart, you'll add a hook that logs the shell commands that Claude65Each example includes a ready-to-use configuration block that you add to a [settings file](#configure-hook-location). The most common patterns:

58Code runs.

59 66 

60### Prerequisites67* [Get notified when Claude needs input](#get-notified-when-claude-needs-input)

68* [Auto-format code after edits](#auto-format-code-after-edits)

69* [Block edits to protected files](#block-edits-to-protected-files)

70* [Re-inject context after compaction](#re-inject-context-after-compaction)

71* [Audit configuration changes](#audit-configuration-changes)

72* [Reload environment when directory or files change](#reload-environment-when-directory-or-files-change)

73* [Auto-approve specific permission prompts](#auto-approve-specific-permission-prompts)

61 74 

62Install `jq` for JSON processing in the command line.75### Get notified when Claude needs input

63 76 

64### Step 1: Open hooks configuration77Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal.

65 78 

66Run the `/hooks` [slash command](/en/docs/claude-code/slash-commands) and select79This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform's native notification command. Add this to `~/.claude/settings.json`:

67the `PreToolUse` hook event.

68 80 

69`PreToolUse` hooks run before tool calls and can block them while providing81<Tabs>

70Claude feedback on what to do differently.82 <Tab title="macOS">

83 ```json theme={null}

84 {

85 "hooks": {

86 "Notification": [

87 {

88 "matcher": "",

89 "hooks": [

90 {

91 "type": "command",

92 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

93 }

94 ]

95 }

96 ]

97 }

98 }

99 ```

71 100 

72### Step 2: Add a matcher101 <Accordion title="If no notification appears">

102 `osascript` routes notifications through the built-in Script Editor app. If Script Editor doesn't have notification permission, the command fails silently, and macOS won't prompt you to grant it. Run this in Terminal once to make Script Editor appear in your notification settings:

73 103 

74Select `+ Add new matcher…` to run your hook only on Bash tool calls.104 ```bash theme={null}

105 osascript -e 'display notification "test"'

106 ```

75 107 

76Type `Bash` for the matcher.108 Nothing will appear yet. Open **System Settings > Notifications**, find **Script Editor** in the list, and turn on **Allow Notifications**. Run the command again to confirm the test notification appears.

109 </Accordion>

110 </Tab>

77 111 

78<Note>You can use `*` to match all tools.</Note>112 <Tab title="Linux">

113 ```json theme={null}

114 {

115 "hooks": {

116 "Notification": [

117 {

118 "matcher": "",

119 "hooks": [

120 {

121 "type": "command",

122 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

123 }

124 ]

125 }

126 ]

127 }

128 }

129 ```

130 </Tab>

131 

132 <Tab title="Windows (PowerShell)">

133 ```json theme={null}

134 {

135 "hooks": {

136 "Notification": [

137 {

138 "matcher": "",

139 "hooks": [

140 {

141 "type": "command",

142 "command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""

143 }

144 ]

145 }

146 ]

147 }

148 }

149 ```

150 </Tab>

151</Tabs>

79 152 

80### Step 3: Add the hook153### Auto-format code after edits

81 154 

82Select `+ Add new hook…` and enter this command:155Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

83 156 

84```bash theme={null}157This hook uses the `PostToolUse` event with an `Edit|Write` matcher, so it runs only after file-editing tools. The command extracts the edited file path with [`jq`](https://jqlang.github.io/jq/) and passes it to Prettier. Add this to `.claude/settings.json` in your project root:

85jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt158 

159```json theme={null}

160{

161 "hooks": {

162 "PostToolUse": [

163 {

164 "matcher": "Edit|Write",

165 "hooks": [

166 {

167 "type": "command",

168 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"

169 }

170 ]

171 }

172 ]

173 }

174}

86```175```

87 176 

88### Step 4: Save your configuration177<Note>

178 The Bash examples on this page use `jq` for JSON parsing. Install it with `brew install jq` (macOS), `apt-get install jq` (Debian/Ubuntu), or see [`jq` downloads](https://jqlang.github.io/jq/download/).

179</Note>

180 

181### Block edits to protected files

182 

183Prevent Claude from modifying sensitive files like `.env`, `package-lock.json`, or anything in `.git/`. Claude receives feedback explaining why the edit was blocked, so it can adjust its approach.

184 

185This example uses a separate script file that the hook calls. The script checks the target file path against a list of protected patterns and exits with code 2 to block the edit.

186 

187<Steps>

188 <Step title="Create the hook script">

189 Save this to `.claude/hooks/protect-files.sh`:

190 

191 ```bash theme={null}

192 #!/bin/bash

193 # protect-files.sh

194 

195 INPUT=$(cat)

196 FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

89 197 

90For storage location, select `User settings` since you're logging to your home198 PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

91directory. This hook will then apply to all projects, not just your current

92project.

93 199 

94Then press Esc until you return to the REPL. Your hook is now registered!200 for pattern in "${PROTECTED_PATTERNS[@]}"; do

201 if [[ "$FILE_PATH" == *"$pattern"* ]]; then

202 echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2

203 exit 2

204 fi

205 done

95 206 

96### Step 5: Verify your hook207 exit 0

208 ```

209 </Step>

97 210 

98Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:211 <Step title="Make the script executable (macOS/Linux)">

212 Hook scripts must be executable for Claude Code to run them:

213 

214 ```bash theme={null}

215 chmod +x .claude/hooks/protect-files.sh

216 ```

217 </Step>

218 

219 <Step title="Register the hook">

220 Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call:

221 

222 ```json theme={null}

223 {

224 "hooks": {

225 "PreToolUse": [

226 {

227 "matcher": "Edit|Write",

228 "hooks": [

229 {

230 "type": "command",

231 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"

232 }

233 ]

234 }

235 ]

236 }

237 }

238 ```

239 </Step>

240</Steps>

241 

242### Re-inject context after compaction

243 

244When Claude's context window fills up, compaction summarizes the conversation to free space. This can lose important details. Use a `SessionStart` hook with a `compact` matcher to re-inject critical context after every compaction.

245 

246Any text your command writes to stdout is added to Claude's context. This example reminds Claude of project conventions and recent work. Add this to `.claude/settings.json` in your project root:

99 247 

100```json theme={null}248```json theme={null}

101{249{

102 "hooks": {250 "hooks": {

103 "PreToolUse": [251 "SessionStart": [

104 {252 {

105 "matcher": "Bash",253 "matcher": "compact",

106 "hooks": [254 "hooks": [

107 {255 {

108 "type": "command",256 "type": "command",

109 "command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"257 "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"

110 }258 }

111 ]259 ]

112 }260 }


115}263}

116```264```

117 265 

118### Step 6: Test your hook266You can replace the `echo` with any command that produces dynamic output, like `git log --oneline -5` to show recent commits. For injecting context on every session start, consider using [CLAUDE.md](/en/memory) instead. For environment variables, see [`CLAUDE_ENV_FILE`](/en/hooks#persist-environment-variables) in the reference.

119 267 

120Ask Claude to run a simple command like `ls` and check your log file:268### Audit configuration changes

121 269 

122```bash theme={null}270Track when settings or skills files change during a session. The `ConfigChange` event fires when an external process or editor modifies a configuration file, so you can log changes for compliance or block unauthorized modifications.

123cat ~/.claude/bash-command-log.txt271 

272This example appends each change to an audit log. Add this to `~/.claude/settings.json`:

273 

274```json theme={null}

275{

276 "hooks": {

277 "ConfigChange": [

278 {

279 "matcher": "",

280 "hooks": [

281 {

282 "type": "command",

283 "command": "jq -c '{timestamp: now | todate, source: .source, file: .file_path}' >> ~/claude-config-audit.log"

284 }

285 ]

286 }

287 ]

288 }

289}

124```290```

125 291 

126You should see entries like:292The matcher filters by configuration type: `user_settings`, `project_settings`, `local_settings`, `policy_settings`, or `skills`. To block a change from taking effect, exit with code 2 or return `{"decision": "block"}`. See the [ConfigChange reference](/en/hooks#configchange) for the full input schema.

293 

294### Reload environment when directory or files change

295 

296Some 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.

127 297 

298A `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`:

299 

300```json theme={null}

301{

302 "hooks": {

303 "CwdChanged": [

304 {

305 "hooks": [

306 {

307 "type": "command",

308 "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""

309 }

310 ]

311 }

312 ]

313 }

314}

128```315```

129ls - Lists files and directories316 

317To react to specific files instead of every directory change, use `FileChanged` with a `matcher` listing the filenames to watch (pipe-separated). The `matcher` both configures which files to watch and filters which hooks run. This example watches `.envrc` and `.env` for changes in the current directory:

318 

319```json theme={null}

320{

321 "hooks": {

322 "FileChanged": [

323 {

324 "matcher": ".envrc|.env",

325 "hooks": [

326 {

327 "type": "command",

328 "command": "direnv export bash >> \"$CLAUDE_ENV_FILE\""

329 }

330 ]

331 }

332 ]

333 }

334}

130```335```

131 336 

132## More Examples337See the [CwdChanged](/en/hooks#cwdchanged) and [FileChanged](/en/hooks#filechanged) reference entries for input schemas, `watchPaths` output, and `CLAUDE_ENV_FILE` details.

133 338 

134<Note>339### Auto-approve specific permission prompts

135 For a complete example implementation, see the [bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py) in our public codebase.340 

136</Note>341Skip the approval dialog for tool calls you always allow. This example auto-approves `ExitPlanMode`, the tool Claude calls when it finishes presenting a plan and asks to proceed, so you aren't prompted every time a plan is ready.

137 342 

138### Code Formatting Hook343Unlike the exit-code examples above, auto-approval requires your hook to write a JSON decision to stdout. A `PermissionRequest` hook fires when Claude Code is about to show a permission dialog, and returning `"behavior": "allow"` answers it on your behalf.

139 344 

140Automatically format TypeScript files after editing:345The matcher scopes the hook to `ExitPlanMode` only, so no other prompts are affected. Add this to `~/.claude/settings.json`:

141 346 

142```json theme={null}347```json theme={null}

143{348{

144 "hooks": {349 "hooks": {

145 "PostToolUse": [350 "PermissionRequest": [

146 {351 {

147 "matcher": "Edit|Write",352 "matcher": "ExitPlanMode",

148 "hooks": [353 "hooks": [

149 {354 {

150 "type": "command",355 "type": "command",

151 "command": "jq -r '.tool_input.file_path' | { read file_path; if echo \"$file_path\" | grep -q '\\.ts$'; then npx prettier --write \"$file_path\"; fi; }"356 "command": "echo '{\"hookSpecificOutput\": {\"hookEventName\": \"PermissionRequest\", \"decision\": {\"behavior\": \"allow\"}}}'"

152 }357 }

153 ]358 ]

154 }359 }


157}362}

158```363```

159 364 

160### Markdown Formatting Hook365When the hook approves, Claude Code exits plan mode and restores whatever permission mode was active before you entered plan mode. The transcript shows "Allowed by PermissionRequest hook" where the dialog would have appeared. The hook path always keeps the current conversation: it cannot clear context and start a fresh implementation session the way the dialog can.

366 

367To 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.

368 

369To switch the session to `acceptEdits`, your hook writes this JSON to stdout:

370 

371```json theme={null}

372{

373 "hookSpecificOutput": {

374 "hookEventName": "PermissionRequest",

375 "decision": {

376 "behavior": "allow",

377 "updatedPermissions": [

378 { "type": "setMode", "mode": "acceptEdits", "destination": "session" }

379 ]

380 }

381 }

382}

383```

384 

385Keep the matcher as narrow as possible. Matching on `.*` or leaving the matcher empty would auto-approve every permission prompt, including file writes and shell commands. See the [PermissionRequest reference](/en/hooks#permissionrequest-decision-control) for the full set of decision fields.

386 

387## How hooks work

388 

389Hook 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:

390 

391| Event | When it fires |

392| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

393| `SessionStart` | When a session begins or resumes |

394| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

395| `PreToolUse` | Before a tool call executes. Can block it |

396| `PermissionRequest` | When a permission dialog appears |

397| `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 |

398| `PostToolUse` | After a tool call succeeds |

399| `PostToolUseFailure` | After a tool call fails |

400| `Notification` | When Claude Code sends a notification |

401| `SubagentStart` | When a subagent is spawned |

402| `SubagentStop` | When a subagent finishes |

403| `TaskCreated` | When a task is being created via `TaskCreate` |

404| `TaskCompleted` | When a task is being marked as completed |

405| `Stop` | When Claude finishes responding |

406| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |

407| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

408| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

409| `ConfigChange` | When a configuration file changes during a session |

410| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |

411| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |

412| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

413| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

414| `PreCompact` | Before context compaction |

415| `PostCompact` | After context compaction completes |

416| `Elicitation` | When an MCP server requests user input during a tool call |

417| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

418| `SessionEnd` | When a session terminates |

419 

420When 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.

421 

422Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Three other types are available:

423 

424* `"type": "http"`: POST event data to a URL. See [HTTP hooks](#http-hooks).

425* `"type": "prompt"`: single-turn LLM evaluation. See [Prompt-based hooks](#prompt-based-hooks).

426* `"type": "agent"`: multi-turn verification with tool access. See [Agent-based hooks](#agent-based-hooks).

427 

428### Read input and return output

429 

430Hooks communicate with Claude Code through stdin, stdout, stderr, and exit codes. When an event fires, Claude Code passes event-specific data as JSON to your script's stdin. Your script reads that data, does its work, and tells Claude Code what to do next via the exit code.

431 

432#### Hook input

433 

434Every event includes common fields like `session_id` and `cwd`, but each event type adds different data. For example, when Claude runs a Bash command, a `PreToolUse` hook receives something like this on stdin:

161 435 

162Automatically fix missing language tags and formatting issues in markdown files:436```json theme={null}

437{

438 "session_id": "abc123", // unique ID for this session

439 "cwd": "/Users/sarah/myproject", // working directory when the event fired

440 "hook_event_name": "PreToolUse", // which event triggered this hook

441 "tool_name": "Bash", // the tool Claude is about to use

442 "tool_input": { // the arguments Claude passed to the tool

443 "command": "npm test" // for Bash, this is the shell command

444 }

445}

446```

447 

448Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, clear, compact), and so on. See [Common input fields](/en/hooks#common-input-fields) in the reference for shared fields, and each event's section for event-specific schemas.

449 

450#### Hook output

451 

452Your script tells Claude Code what to do next by writing to stdout or stderr and exiting with a specific code. For example, a `PreToolUse` hook that wants to block a command:

453 

454```bash theme={null}

455#!/bin/bash

456INPUT=$(cat)

457COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')

458 

459if echo "$COMMAND" | grep -q "drop table"; then

460 echo "Blocked: dropping tables is not allowed" >&2 # stderr becomes Claude's feedback

461 exit 2 # exit 2 = block the action

462fi

463 

464exit 0 # exit 0 = let it proceed

465```

466 

467The exit code determines what happens next:

468 

469* **Exit 0**: the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude's context.

470* **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.

471* **Any other exit code**: the action proceeds. Stderr is logged but not shown to Claude. Toggle verbose mode with `Ctrl+O` to see these messages in the transcript.

472 

473#### Structured JSON output

474 

475Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead.

476 

477<Note>

478 Use exit 2 to block with a stderr message, or exit 0 with JSON for structured control. Don't mix them: Claude Code ignores JSON when you exit 2.

479</Note>

480 

481For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:

482 

483```json theme={null}

484{

485 "hookSpecificOutput": {

486 "hookEventName": "PreToolUse",

487 "permissionDecision": "deny",

488 "permissionDecisionReason": "Use rg instead of grep for better performance"

489 }

490}

491```

492 

493With `"deny"`, Claude Code cancels the tool call and feeds `permissionDecisionReason` back to Claude. These `permissionDecision` values are specific to `PreToolUse`:

494 

495* `"allow"`: skip the interactive permission prompt. Deny and ask rules, including enterprise managed deny lists, still apply

496* `"deny"`: cancel the tool call and send the reason to Claude

497* `"ask"`: show the permission prompt to the user as normal

498 

499A fourth value, `"defer"`, is available in [non-interactive mode](/en/headless) with the `-p` flag. It exits the process with the tool call preserved so an Agent SDK wrapper can collect input and resume. See [Defer a tool call for later](/en/hooks#defer-a-tool-call-for-later) in the reference.

500 

501Returning `"allow"` skips the interactive prompt but does not override [permission rules](/en/permissions#manage-permissions). If a deny rule matches the tool call, the call is blocked even when your hook returns `"allow"`. If an ask rule matches, the user is still prompted. This means deny rules from any settings scope, including [managed settings](/en/settings#settings-files), always take precedence over hook approvals.

502 

503Other events use different decision patterns. For example, `PostToolUse` and `Stop` hooks use a top-level `decision: "block"` field, while `PermissionRequest` uses `hookSpecificOutput.decision.behavior`. See the [summary table](/en/hooks#decision-control) in the reference for a full breakdown by event.

504 

505For `UserPromptSubmit` hooks, use `additionalContext` instead to inject text into Claude's context. Prompt-based hooks (`type: "prompt"`) handle output differently: see [Prompt-based hooks](#prompt-based-hooks).

506 

507### Filter hooks with matchers

508 

509Without a matcher, a hook fires on every occurrence of its event. Matchers let you narrow that down. For example, if you want to run a formatter only after file edits (not after every tool call), add a matcher to your `PostToolUse` hook:

163 510 

164```json theme={null}511```json theme={null}

165{512{


167 "PostToolUse": [514 "PostToolUse": [

168 {515 {

169 "matcher": "Edit|Write",516 "matcher": "Edit|Write",

517 "hooks": [

518 { "type": "command", "command": "prettier --write ..." }

519 ]

520 }

521 ]

522 }

523}

524```

525 

526The `"Edit|Write"` matcher is a regex pattern that matches the tool name. The hook only fires when Claude uses the `Edit` or `Write` tool, not when it uses `Bash`, `Read`, or any other tool.

527 

528Each event type matches on a specific field. Matchers support exact strings and regex patterns:

529 

530| Event | What the matcher filters | Example matcher values |

531| :--------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |

532| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

533| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

534| `SessionEnd` | why the session ended | `clear`, `resume`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

535| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

536| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

537| `PreCompact`, `PostCompact` | what triggered compaction | `manual`, `auto` |

538| `SubagentStop` | agent type | same values as `SubagentStart` |

539| `ConfigChange` | configuration source | `user_settings`, `project_settings`, `local_settings`, `policy_settings`, `skills` |

540| `StopFailure` | error type | `rate_limit`, `authentication_failed`, `billing_error`, `invalid_request`, `server_error`, `max_output_tokens`, `unknown` |

541| `InstructionsLoaded` | load reason | `session_start`, `nested_traversal`, `path_glob_match`, `include`, `compact` |

542| `Elicitation` | MCP server name | your configured MCP server names |

543| `ElicitationResult` | MCP server name | same values as `Elicitation` |

544| `FileChanged` | filename (basename of the changed file) | `.envrc`, `.env`, any filename you want to watch |

545| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged` | no matcher support | always fires on every occurrence |

546 

547A few more examples showing matchers on different event types:

548 

549<Tabs>

550 <Tab title="Log every Bash command">

551 Match only `Bash` tool calls and log each command to a file. The `PostToolUse` event fires after the command completes, so `tool_input.command` contains what ran. The hook receives the event data as JSON on stdin, and `jq -r '.tool_input.command'` extracts just the command string, which `>>` appends to the log file:

552 

553 ```json theme={null}

554 {

555 "hooks": {

556 "PostToolUse": [

557 {

558 "matcher": "Bash",

559 "hooks": [

560 {

561 "type": "command",

562 "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"

563 }

564 ]

565 }

566 ]

567 }

568 }

569 ```

570 </Tab>

571 

572 <Tab title="Match MCP tools">

573 MCP tools use a different naming convention than built-in tools: `mcp__<server>__<tool>`, where `<server>` is the MCP server name and `<tool>` is the tool it provides. For example, `mcp__github__search_repositories` or `mcp__filesystem__read_file`. Use a regex matcher to target all tools from a specific server, or match across servers with a pattern like `mcp__.*__write.*`. See [Match MCP tools](/en/hooks#match-mcp-tools) in the reference for the full list of examples.

574 

575 The command below extracts the tool name from the hook's JSON input with `jq` and writes it to stderr, where it shows up in verbose mode (`Ctrl+O`):

576 

577 ```json theme={null}

578 {

579 "hooks": {

580 "PreToolUse": [

581 {

582 "matcher": "mcp__github__.*",

170 "hooks": [583 "hooks": [

171 {584 {

172 "type": "command",585 "type": "command",

173 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"586 "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2"

587 }

588 ]

589 }

590 ]

591 }

592 }

593 ```

594 </Tab>

595 

596 <Tab title="Clean up on session end">

597 The `SessionEnd` event supports matchers on the reason the session ended. This hook only fires on `clear` (when you run `/clear`), not on normal exits:

598 

599 ```json theme={null}

600 {

601 "hooks": {

602 "SessionEnd": [

603 {

604 "matcher": "clear",

605 "hooks": [

606 {

607 "type": "command",

608 "command": "rm -f /tmp/claude-scratch-*.txt"

609 }

610 ]

611 }

612 ]

613 }

614 }

615 ```

616 </Tab>

617</Tabs>

618 

619For full matcher syntax, see the [Hooks reference](/en/hooks#configuration).

620 

621#### Filter by tool name and arguments with the `if` field

622 

623<Note>

624 The `if` field requires Claude Code v2.1.85 or later. Earlier versions ignore it and run the hook on every matched call.

625</Note>

626 

627The `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.

628 

629For example, to run a hook only when Claude uses `git` commands rather than all Bash commands:

630 

631```json theme={null}

632{

633 "hooks": {

634 "PreToolUse": [

635 {

636 "matcher": "Bash",

637 "hooks": [

638 {

639 "type": "command",

640 "if": "Bash(git *)",

641 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-git-policy.sh"

174 }642 }

175 ]643 ]

176 }644 }


179}647}

180```648```

181 649 

182Create `.claude/hooks/markdown_formatter.py` with this content:650The 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.

183 

184````python theme={null}

185#!/usr/bin/env python3

186"""

187Markdown formatter for Claude Code output.

188Fixes missing language tags and spacing issues while preserving code content.

189"""

190import json

191import sys

192import re

193import os

194 

195def detect_language(code):

196 """Best-effort language detection from code content."""

197 s = code.strip()

198

199 # JSON detection

200 if re.search(r'^\s*[{\[]', s):

201 try:

202 json.loads(s)

203 return 'json'

204 except:

205 pass

206

207 # Python detection

208 if re.search(r'^\s*def\s+\w+\s*\(', s, re.M) or \

209 re.search(r'^\s*(import|from)\s+\w+', s, re.M):

210 return 'python'

211

212 # JavaScript detection

213 if re.search(r'\b(function\s+\w+\s*\(|const\s+\w+\s*=)', s) or \

214 re.search(r'=>|console\.(log|error)', s):

215 return 'javascript'

216

217 # Bash detection

218 if re.search(r'^#!.*\b(bash|sh)\b', s, re.M) or \

219 re.search(r'\b(if|then|fi|for|in|do|done)\b', s):

220 return 'bash'

221

222 # SQL detection

223 if re.search(r'\b(SELECT|INSERT|UPDATE|DELETE|CREATE)\s+', s, re.I):

224 return 'sql'

225

226 return 'text'

227 

228def format_markdown(content):

229 """Format markdown content with language detection."""

230 # Fix unlabeled code fences

231 def add_lang_to_fence(match):

232 indent, info, body, closing = match.groups()

233 if not info.strip():

234 lang = detect_language(body)

235 return f"{indent}```{lang}\n{body}{closing}\n"

236 return match.group(0)

237

238 fence_pattern = r'(?ms)^([ \t]{0,3})```([^\n]*)\n(.*?)(\n\1```)\s*$'

239 content = re.sub(fence_pattern, add_lang_to_fence, content)

240

241 # Fix excessive blank lines (only outside code fences)

242 content = re.sub(r'\n{3,}', '\n\n', content)

243

244 return content.rstrip() + '\n'

245 

246# Main execution

247try:

248 input_data = json.load(sys.stdin)

249 file_path = input_data.get('tool_input', {}).get('file_path', '')

250

251 if not file_path.endswith(('.md', '.mdx')):

252 sys.exit(0) # Not a markdown file

253

254 if os.path.exists(file_path):

255 with open(file_path, 'r', encoding='utf-8') as f:

256 content = f.read()

257

258 formatted = format_markdown(content)

259

260 if formatted != content:

261 with open(file_path, 'w', encoding='utf-8') as f:

262 f.write(formatted)

263 print(f"✓ Fixed markdown formatting in {file_path}")

264

265except Exception as e:

266 print(f"Error formatting markdown: {e}", file=sys.stderr)

267 sys.exit(1)

268````

269 

270Make the script executable:

271 651 

272```bash theme={null}652`if` only works on tool events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, and `PermissionDenied`. Adding it to any other event prevents the hook from running.

273chmod +x .claude/hooks/markdown_formatter.py653 

654### Configure hook location

655 

656Where you add a hook determines its scope:

657 

658| Location | Scope | Shareable |

659| :--------------------------------------------------------- | :--------------------------------- | :--------------------------------- |

660| `~/.claude/settings.json` | All your projects | No, local to your machine |

661| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

662| `.claude/settings.local.json` | Single project | No, gitignored |

663| Managed policy settings | Organization-wide | Yes, admin-controlled |

664| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

665| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file |

666 

667Run [`/hooks`](/en/hooks#the-hooks-menu) in Claude Code to browse all configured hooks grouped by event. To disable all hooks at once, set `"disableAllHooks": true` in your settings file.

668 

669If you edit settings files directly while Claude Code is running, the file watcher normally picks up hook changes automatically.

670 

671## Prompt-based hooks

672 

673For decisions that require judgment rather than deterministic rules, use `type: "prompt"` hooks. Instead of running a shell command, Claude Code sends your prompt and the hook's input data to a Claude model (Haiku by default) to make the decision. You can specify a different model with the `model` field if you need more capability.

674 

675The model's only job is to return a yes/no decision as JSON:

676 

677* `"ok": true`: the action proceeds

678* `"ok": false`: the action is blocked. The model's `"reason"` is fed back to Claude so it can adjust.

679 

680This 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:

681 

682```json theme={null}

683{

684 "hooks": {

685 "Stop": [

686 {

687 "hooks": [

688 {

689 "type": "prompt",

690 "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."

691 }

692 ]

693 }

694 ]

695 }

696}

274```697```

275 698 

276This hook automatically:699For full configuration options, see [Prompt-based hooks](/en/hooks#prompt-based-hooks) in the reference.

277 700 

278* Detects programming languages in unlabeled code blocks701## Agent-based hooks

279* Adds appropriate language tags for syntax highlighting

280* Fixes excessive blank lines while preserving code content

281* Only processes markdown files (`.md`, `.mdx`)

282 702 

283### Custom Notification Hook703When 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.

284 704 

285Get desktop notifications when Claude needs input:705Agent 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.

706 

707This example verifies that tests pass before allowing Claude to stop:

286 708 

287```json theme={null}709```json theme={null}

288{710{

289 "hooks": {711 "hooks": {

290 "Notification": [712 "Stop": [

291 {713 {

292 "matcher": "",

293 "hooks": [714 "hooks": [

294 {715 {

295 "type": "command",716 "type": "agent",

296 "command": "notify-send 'Claude Code' 'Awaiting your input'"717 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

718 "timeout": 120

297 }719 }

298 ]720 ]

299 }721 }


302}724}

303```725```

304 726 

305### File Protection Hook727Use prompt hooks when the hook input data alone is enough to make a decision. Use agent hooks when you need to verify something against the actual state of the codebase.

728 

729For full configuration options, see [Agent-based hooks](/en/hooks#agent-based-hooks) in the reference.

306 730 

307Block edits to sensitive files:731## HTTP hooks

732 

733Use `type: "http"` hooks to POST event data to an HTTP endpoint instead of running a shell command. The endpoint receives the same JSON that a command hook would receive on stdin, and returns results through the HTTP response body using the same JSON format.

734 

735HTTP hooks are useful when you want a web server, cloud function, or external service to handle hook logic: for example, a shared audit service that logs tool use events across a team.

736 

737This example posts every tool use to a local logging service:

308 738 

309```json theme={null}739```json theme={null}

310{740{

311 "hooks": {741 "hooks": {

312 "PreToolUse": [742 "PostToolUse": [

313 {743 {

314 "matcher": "Edit|Write",

315 "hooks": [744 "hooks": [

316 {745 {

317 "type": "command",746 "type": "http",

318 "command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""747 "url": "http://localhost:8080/hooks/tool-use",

748 "headers": {

749 "Authorization": "Bearer $MY_TOKEN"

750 },

751 "allowedEnvVars": ["MY_TOKEN"]

319 }752 }

320 ]753 ]

321 }754 }


324}757}

325```758```

326 759 

760The endpoint should return a JSON response body using the same [output format](/en/hooks#json-output) as command hooks. To block a tool call, return a 2xx response with the appropriate `hookSpecificOutput` fields. HTTP status codes alone cannot block actions.

761 

762Header values support environment variable interpolation using `$VAR_NAME` or `${VAR_NAME}` syntax. Only variables listed in the `allowedEnvVars` array are resolved; all other `$VAR` references remain empty.

763 

764For full configuration options and response handling, see [HTTP hooks](/en/hooks#http-hook-fields) in the reference.

765 

766## Limitations and troubleshooting

767 

768### Limitations

769 

770* Command hooks communicate through stdout, stderr, and exit codes only. They cannot trigger `/` commands or tool calls. Text returned via `additionalContext` is injected as a system reminder that Claude reads as plain text. HTTP hooks communicate through the response body instead.

771* Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).

772* `PostToolUse` hooks cannot undo actions since the tool has already executed.

773* `PermissionRequest` hooks do not fire in [non-interactive mode](/en/headless) (`-p`). Use `PreToolUse` hooks for automated permission decisions.

774* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts. API errors fire [StopFailure](/en/hooks#stopfailure) instead.

775* When multiple PreToolUse hooks return [`updatedInput`](/en/hooks#pretooluse) to rewrite a tool's arguments, the last one to finish wins. Since hooks run in parallel, the order is non-deterministic. Avoid having more than one hook modify the same tool's input.

776 

777### Hooks and permission modes

778 

779PreToolUse hooks fire before any permission-mode check. A hook that returns `permissionDecision: "deny"` blocks the tool even in `bypassPermissions` mode or with `--dangerously-skip-permissions`. This lets you enforce policy that users cannot bypass by changing their permission mode.

780 

781The reverse is not true: a hook returning `"allow"` does not bypass deny rules from settings. Hooks can tighten restrictions but not loosen them past what permission rules allow.

782 

783### Hook not firing

784 

785The hook is configured but never executes.

786 

787* Run `/hooks` and confirm the hook appears under the correct event

788* Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)

789* Verify you're triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)

790* If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead

791 

792### Hook error in output

793 

794You see a message like "PreToolUse hook error: ..." in the transcript.

795 

796* Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON:

797 ```bash theme={null}

798 echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh

799 echo $? # Check the exit code

800 ```

801* If you see "command not found", use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts

802* If you see "jq: command not found", install `jq` or use Python/Node.js for JSON parsing

803* If the script isn't running at all, make it executable: `chmod +x ./my-hook.sh`

804 

805### `/hooks` shows no hooks configured

806 

807You edited a settings file but the hooks don't appear in the menu.

808 

809* File edits are normally picked up automatically. If they haven't appeared after a few seconds, the file watcher may have missed the change: restart your session to force a reload.

810* Verify your JSON is valid (trailing commas and comments are not allowed)

811* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks

812 

813### Stop hook runs forever

814 

815Claude keeps working in an infinite loop instead of stopping.

816 

817Your Stop hook script needs to check whether it already triggered a continuation. Parse the `stop_hook_active` field from the JSON input and exit early if it's `true`:

818 

819```bash theme={null}

820#!/bin/bash

821INPUT=$(cat)

822if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then

823 exit 0 # Allow Claude to stop

824fi

825# ... rest of your hook logic

826```

827 

828### JSON validation failed

829 

830Claude Code shows a JSON parsing error even though your hook script outputs valid JSON.

831 

832When Claude Code runs a hook, it spawns a shell that sources your profile (`~/.zshrc` or `~/.bashrc`). If your profile contains unconditional `echo` statements, that output gets prepended to your hook's JSON:

833 

834```text theme={null}

835Shell ready on arm64

836{"decision": "block", "reason": "Not allowed"}

837```

838 

839Claude Code tries to parse this as JSON and fails. To fix this, wrap echo statements in your shell profile so they only run in interactive shells:

840 

841```bash theme={null}

842# In ~/.zshrc or ~/.bashrc

843if [[ $- == *i* ]]; then

844 echo "Shell ready"

845fi

846```

847 

848The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.

849 

850### Debug techniques

851 

852Toggle verbose mode with `Ctrl+O` to see hook output in the transcript, or run `claude --debug` for full execution details including which hooks matched and their exit codes.

853 

327## Learn more854## Learn more

328 855 

329* For reference documentation on hooks, see [Hooks reference](/en/docs/claude-code/hooks).856* [Hooks reference](/en/hooks): full event schemas, JSON output format, async hooks, and MCP tool hooks

330* For comprehensive security best practices and safety guidelines, see [Security Considerations](/en/docs/claude-code/hooks#security-considerations) in the hooks reference documentation.857* [Security considerations](/en/hooks#security-considerations): review before deploying hooks in shared or production environments

331* For troubleshooting steps and debugging techniques, see [Debugging](/en/docs/claude-code/hooks#debugging) in the hooks reference858* [Bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py): complete reference implementation

332 documentation.

how-claude-code-works.md +263 −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# How Claude Code works

6 

7> Understand the agentic loop, built-in tools, and how Claude Code interacts with your project.

8 

9Claude Code is an agentic assistant that runs in your terminal. While it excels at coding, it can help with anything you can do from the command line: writing docs, running builds, searching files, researching topics, and more.

10 

11This guide covers the core architecture, built-in capabilities, and [tips for working effectively](#work-effectively-with-claude-code). For step-by-step walkthroughs, see [Common workflows](/en/common-workflows). For extensibility features like skills, MCP, and hooks, see [Extend Claude Code](/en/features-overview).

12 

13## The agentic loop

14 

15When you give Claude a task, it works through three phases: **gather context**, **take action**, and **verify results**. These phases blend together. Claude uses tools throughout, whether searching files to understand your code, editing to make changes, or running tests to check its work.

16 

17<img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/agentic-loop.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=5f1827dec8539f38adee90ead3a85a38" alt="The agentic loop: Your prompt leads to Claude gathering context, taking action, verifying results, and repeating until task complete. You can interrupt at any point." width="720" height="280" data-path="images/agentic-loop.svg" />

18 

19The loop adapts to what you ask. A question about your codebase might only need context gathering. A bug fix cycles through all three phases repeatedly. A refactor might involve extensive verification. Claude decides what each step requires based on what it learned from the previous step, chaining dozens of actions together and course-correcting along the way.

20 

21You're part of this loop too. You can interrupt at any point to steer Claude in a different direction, provide additional context, or ask it to try a different approach. Claude works autonomously but stays responsive to your input.

22 

23The agentic loop is powered by two components: [models](#models) that reason and [tools](#tools) that act. Claude Code serves as the **agentic harness** around Claude: it provides the tools, context management, and execution environment that turn a language model into a capable coding agent.

24 

25### Models

26 

27Claude Code uses Claude models to understand your code and reason about tasks. Claude can read code in any language, understand how components connect, and figure out what needs to change to accomplish your goal. For complex tasks, it breaks work into steps, executes them, and adjusts based on what it learns.

28 

29[Multiple models](/en/model-config) are available with different tradeoffs. Sonnet handles most coding tasks well. Opus provides stronger reasoning for complex architectural decisions. Switch with `/model` during a session or start with `claude --model <name>`.

30 

31When this guide says "Claude chooses" or "Claude decides," it's the model doing the reasoning.

32 

33### Tools

34 

35Tools are what make Claude Code agentic. Without tools, Claude can only respond with text. With tools, Claude can act: read your code, edit files, run commands, search the web, and interact with external services. Each tool use returns information that feeds back into the loop, informing Claude's next decision.

36 

37The built-in tools generally fall into five categories, each representing a different kind of agency.

38 

39| Category | What Claude can do |

40| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |

41| **File operations** | Read files, edit code, create new files, rename and reorganize |

42| **Search** | Find files by pattern, search content with regex, explore codebases |

43| **Execution** | Run shell commands, start servers, run tests, use git |

44| **Web** | Search the web, fetch documentation, look up error messages |

45| **Code intelligence** | See type errors and warnings after edits, jump to definitions, find references (requires [code intelligence plugins](/en/discover-plugins#code-intelligence)) |

46 

47These are the primary capabilities. Claude also has tools for spawning subagents, asking you questions, and other orchestration tasks. See [Tools available to Claude](/en/tools-reference) for the complete list.

48 

49Claude chooses which tools to use based on your prompt and what it learns along the way. When you say "fix the failing tests," Claude might:

50 

511. Run the test suite to see what's failing

522. Read the error output

533. Search for the relevant source files

544. Read those files to understand the code

555. Edit the files to fix the issue

566. Run the tests again to verify

57 

58Each tool use gives Claude new information that informs the next step. This is the agentic loop in action.

59 

60**Extending the base capabilities:** The built-in tools are the foundation. You can extend what Claude knows with [skills](/en/skills), connect to external services with [MCP](/en/mcp), automate workflows with [hooks](/en/hooks), and offload tasks to [subagents](/en/sub-agents). These extensions form a layer on top of the core agentic loop. See [Extend Claude Code](/en/features-overview) for guidance on choosing the right extension for your needs.

61 

62## What Claude can access

63 

64This guide focuses on the terminal. Claude Code also runs in [VS Code](/en/vs-code), [JetBrains IDEs](/en/jetbrains), and other environments.

65 

66When you run `claude` in a directory, Claude Code gains access to:

67 

68* **Your project.** Files in your directory and subdirectories, plus files elsewhere with your permission.

69* **Your terminal.** Any command you could run: build tools, git, package managers, system utilities, scripts. If you can do it from the command line, Claude can too.

70* **Your git state.** Current branch, uncommitted changes, and recent commit history.

71* **Your [CLAUDE.md](/en/memory).** A markdown file where you store project-specific instructions, conventions, and context that Claude should know every session.

72* **[Auto memory](/en/memory#auto-memory).** Learnings Claude saves automatically as you work, like project patterns and your preferences. The first 200 lines or 25KB of MEMORY.md, whichever comes first, load at the start of each session.

73* **Extensions you configure.** [MCP servers](/en/mcp) for external services, [skills](/en/skills) for workflows, [subagents](/en/sub-agents) for delegated work, and [Claude in Chrome](/en/chrome) for browser interaction.

74 

75Because Claude sees your whole project, it can work across it. When you ask Claude to "fix the authentication bug," it searches for relevant files, reads multiple files to understand context, makes coordinated edits across them, runs tests to verify the fix, and commits the changes if you ask. This is different from inline code assistants that only see the current file.

76 

77## Environments and interfaces

78 

79The agentic loop, tools, and capabilities described above are the same everywhere you use Claude Code. What changes is where the code executes and how you interact with it.

80 

81### Execution environments

82 

83Claude Code runs in three environments, each with different tradeoffs for where your code executes.

84 

85| Environment | Where code runs | Use case |

86| ------------------ | --------------------------------------- | ---------------------------------------------------------- |

87| **Local** | Your machine | Default. Full access to your files, tools, and environment |

88| **Cloud** | Anthropic-managed VMs | Offload tasks, work on repos you don't have locally |

89| **Remote Control** | Your machine, controlled from a browser | Use the web UI while keeping everything local |

90 

91### Interfaces

92 

93You can access Claude Code through the terminal, the [desktop app](/en/desktop), [IDE extensions](/en/vs-code), [claude.ai/code](https://claude.ai/code), [Remote Control](/en/remote-control), [Slack](/en/slack), and [CI/CD pipelines](/en/github-actions). The interface determines how you see and interact with Claude, but the underlying agentic loop is identical. See [Use Claude Code everywhere](/en/overview#use-claude-code-everywhere) for the full list.

94 

95## Work with sessions

96 

97Claude Code saves your conversation locally as you work. Each message, tool use, and result is stored, which enables [rewinding](#undo-changes-with-checkpoints), [resuming, and forking](#resume-or-fork-sessions) sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed.

98 

99**Sessions are independent.** Each new session starts with a fresh context window, without the conversation history from previous sessions. Claude can persist learnings across sessions using [auto memory](/en/memory#auto-memory), and you can add your own persistent instructions in [CLAUDE.md](/en/memory).

100 

101### Work across branches

102 

103Each Claude Code conversation is a session tied to your current directory. When you resume, you only see sessions from that directory.

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.

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.

108 

109### Resume or fork sessions

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.

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" />

114 

115To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:

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 

125### The context window

126 

127Claude's context window holds your conversation history, file contents, command outputs, [CLAUDE.md](/en/memory), [auto memory](/en/memory#auto-memory), loaded skills, and system instructions. As you work, context fills up. Claude compacts automatically, but instructions from early in the conversation can get lost. Put persistent rules in CLAUDE.md, and run `/context` to see what's using space.

128 

129For an interactive walkthrough of what loads and when, see [Explore the context window](/en/context-window).

130 

131#### When context fills up

132 

133Claude Code manages context automatically as you approach the limit. It clears older tool outputs first, then summarizes the conversation if needed. Your requests and key code snippets are preserved; detailed instructions from early in the conversation may be lost. Put persistent rules in CLAUDE.md rather than relying on conversation history.

134 

135To control what's preserved during compaction, add a "Compact Instructions" section to CLAUDE.md or run `/compact` with a focus (like `/compact focus on the API changes`).

136 

137Run `/context` to see what's using space. MCP tool definitions are deferred by default and loaded on demand via [tool search](/en/mcp#scale-with-mcp-tool-search), so only tool names consume context until Claude uses a specific tool. Run `/mcp` to check per-server costs.

138 

139#### Manage context with skills and subagents

140 

141Beyond compaction, you can use other features to control what loads into context.

142 

143[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.

144 

145[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.

146 

147See [context costs](/en/features-overview#understand-context-costs) for what each feature costs, and [reduce token usage](/en/costs#reduce-token-usage) for tips on managing context.

148 

149## Stay safe with checkpoints and permissions

150 

151Claude has two safety mechanisms: checkpoints let you undo file changes, and permissions control what Claude can do without asking.

152 

153### Undo changes with checkpoints

154 

155**Every file edit is reversible.** Before Claude edits any file, it snapshots the current contents. If something goes wrong, press `Esc` twice to rewind to a previous state, or ask Claude to undo.

156 

157Checkpoints are local to your session, separate from git. They only cover file changes. Actions that affect remote systems (databases, APIs, deployments) can't be checkpointed, which is why Claude asks before running commands with external side effects.

158 

159### Control what Claude can do

160 

161Press `Shift+Tab` to cycle through permission modes:

162 

163* **Default**: Claude asks before file edits and shell commands

164* **Auto-accept edits**: Claude edits files without asking, still asks for commands

165* **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution

166* **Auto mode**: Claude evaluates all actions with background safety checks. Currently a research preview

167 

168You can also allow specific commands in `.claude/settings.json` so Claude doesn't ask each time. This is useful for trusted commands like `npm test` or `git status`. Settings can be scoped from organization-wide policies down to personal preferences. See [Permissions](/en/permissions) for details.

169 

170***

171 

172## Work effectively with Claude Code

173 

174These tips help you get better results from Claude Code.

175 

176### Ask Claude Code for help

177 

178Claude Code can teach you how to use it. Ask questions like "how do I set up hooks?" or "what's the best way to structure my CLAUDE.md?" and Claude will explain.

179 

180Built-in commands also guide you through setup:

181 

182* `/init` walks you through creating a CLAUDE.md for your project

183* `/agents` helps you configure custom subagents

184* `/doctor` diagnoses common issues with your installation

185 

186### It's a conversation

187 

188Claude Code is conversational. You don't need perfect prompts. Start with what you want, then refine:

189 

190```text theme={null}

191Fix the login bug

192```

193 

194\[Claude investigates, tries something]

195 

196```text theme={null}

197That's not quite right. The issue is in the session handling.

198```

199 

200\[Claude adjusts approach]

201 

202When the first attempt isn't right, you don't start over. You iterate.

203 

204#### Interrupt and steer

205 

206You can interrupt Claude at any point. If it's going down the wrong path, just type your correction and press Enter. Claude will stop what it's doing and adjust its approach based on your input. You don't have to wait for it to finish or start over.

207 

208### Be specific upfront

209 

210The more precise your initial prompt, the fewer corrections you'll need. Reference specific files, mention constraints, and point to example patterns.

211 

212```text theme={null}

213The checkout flow is broken for users with expired cards.

214Check src/payments/ for the issue, especially token refresh.

215Write a failing test first, then fix it.

216```

217 

218Vague prompts work, but you'll spend more time steering. Specific prompts like the one above often succeed on the first attempt.

219 

220### Give Claude something to verify against

221 

222Claude performs better when it can check its own work. Include test cases, paste screenshots of expected UI, or define the output you want.

223 

224```text theme={null}

225Implement validateEmail. Test cases: 'user@example.com' → true,

226'invalid' → false, 'user@.com' → false. Run the tests after.

227```

228 

229For visual work, paste a screenshot of the design and ask Claude to compare its implementation against it.

230 

231### Explore before implementing

232 

233For complex problems, separate research from coding. Use plan mode (`Shift+Tab` twice) to analyze the codebase first:

234 

235```text theme={null}

236Read src/auth/ and understand how we handle sessions.

237Then create a plan for adding OAuth support.

238```

239 

240Review the plan, refine it through conversation, then let Claude implement. This two-phase approach produces better results than jumping straight to code.

241 

242### Delegate, don't dictate

243 

244Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details:

245 

246```text theme={null}

247The checkout flow is broken for users with expired cards.

248The relevant code is in src/payments/. Can you investigate and fix it?

249```

250 

251You don't need to specify which files to read or what commands to run. Claude figures that out.

252 

253## What's next

254 

255<CardGroup cols={2}>

256 <Card title="Extend with features" icon="puzzle-piece" href="/en/features-overview">

257 Add Skills, MCP connections, and custom commands

258 </Card>

259 

260 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">

261 Step-by-step guides for typical tasks

262 </Card>

263</CardGroup>

iam.md +0 −200 deleted

File DeletedView Diff

1# Identity and Access Management

2 

3> Learn how to configure user authentication, authorization, and access controls for Claude Code in your organization.

4 

5## Authentication methods

6 

7Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of three ways:

8 

9* Claude API via the Claude Console

10* Amazon Bedrock

11* Google Vertex AI

12 

13### Claude API authentication

14 

15**To set up Claude Code access for your team via Claude API:**

16 

171. Use your existing Claude Console account or create a new Claude Console account

182. You can add users through either method below:

19 * Bulk invite users from within the Console (Console -> Settings -> Members -> Invite)

20 * [Set up SSO](https://support.claude.com/en/articles/10280258-setting-up-single-sign-on-on-the-api-console)

213. When inviting users, they need one of the following roles:

22 * "Claude Code" role means users can only create Claude Code API keys

23 * "Developer" role means users can create any kind of API key

244. Each invited user needs to complete these steps:

25 * Accept the Console invite

26 * [Check system requirements](/en/docs/claude-code/setup#system-requirements)

27 * [Install Claude Code](/en/docs/claude-code/setup#installation)

28 * Login with Console account credentials

29 

30### Cloud provider authentication

31 

32**To set up Claude Code access for your team via Bedrock or Vertex:**

33 

341. Follow the [Bedrock docs](/en/docs/claude-code/amazon-bedrock) or [Vertex docs](/en/docs/claude-code/google-vertex-ai)

352. Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/en/docs/claude-code/settings).

363. Users can [install Claude Code](/en/docs/claude-code/setup#installation)

37 

38## Access control and permissions

39 

40We support fine-grained permissions so that you're able to specify exactly what the agent is allowed to do (e.g. run tests, run linter) and what it is not allowed to do (e.g. update cloud infrastructure). These permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.

41 

42### Permission system

43 

44Claude Code uses a tiered permission system to balance power and safety:

45 

46| Tool Type | Example | Approval Required | "Yes, don't ask again" Behavior |

47| :---------------- | :------------------- | :---------------- | :-------------------------------------------- |

48| Read-only | File reads, LS, Grep | No | N/A |

49| Bash Commands | Shell execution | Yes | Permanently per project directory and command |

50| File Modification | Edit/write files | Yes | Until session end |

51 

52### Configuring permissions

53 

54You can view & manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.

55 

56* **Allow** rules will allow Claude Code to use the specified tool without further manual approval.

57* **Ask** rules will ask the user for confirmation whenever Claude Code tries to use the specified tool. Ask rules take precedence over allow rules.

58* **Deny** rules will prevent Claude Code from using the specified tool. Deny rules take precedence over allow and ask rules.

59* **Additional directories** extend Claude's file access to directories beyond the initial working directory.

60* **Default mode** controls Claude's permission behavior when encountering new requests.

61 

62Permission rules use the format: `Tool` or `Tool(optional-specifier)`

63 

64A rule that is just the tool name matches any use of that tool. For example, adding `Bash` to the list of allow rules would allow Claude Code to use the Bash tool without requiring user approval.

65 

66#### Permission modes

67 

68Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/docs/claude-code/settings#settings-files):

69 

70| Mode | Description |

71| :------------------ | :--------------------------------------------------------------------------- |

72| `default` | Standard behavior - prompts for permission on first use of each tool |

73| `acceptEdits` | Automatically accepts file edit permissions for the session |

74| `plan` | Plan Mode - Claude can analyze but not modify files or execute commands |

75| `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) |

76 

77#### Working directories

78 

79By default, Claude has access to files in the directory where it was launched. You can extend this access:

80 

81* **During startup**: Use `--add-dir <path>` CLI argument

82* **During session**: Use `/add-dir` slash command

83* **Persistent configuration**: Add to `additionalDirectories` in [settings files](/en/docs/claude-code/settings#settings-files)

84 

85Files in additional directories follow the same permission rules as the original working directory - they become readable without prompts, and file editing permissions follow the current permission mode.

86 

87#### Tool-specific permission rules

88 

89Some tools support more fine-grained permission controls:

90 

91**Bash**

92 

93* `Bash(npm run build)` Matches the exact Bash command `npm run build`

94* `Bash(npm run test:*)` Matches Bash commands starting with `npm run test`

95* `Bash(curl http://site.com/:*)` Matches curl commands that start with exactly `curl http://site.com/`

96 

97<Tip>

98 Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd:*)` won't give it permission to run the command `safe-cmd && other-cmd`

99</Tip>

100 

101<Warning>

102 Important limitations of Bash permission patterns:

103 

104 1. This tool uses **prefix matches**, not regex or glob patterns

105 2. The wildcard `:*` only works at the end of a pattern to match any continuation

106 3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in many ways:

107 * Options before URL: `curl -X GET http://github.com/...` won't match

108 * Different protocol: `curl https://github.com/...` won't match

109 * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)

110 * Variables: `URL=http://github.com && curl $URL` won't match

111 * Extra spaces: `curl http://github.com` won't match

112 

113 For more reliable URL filtering, consider:

114 

115 * Using the WebFetch tool with `WebFetch(domain:github.com)` permission

116 * Instructing Claude Code about your allowed curl patterns via CLAUDE.md

117 * Using hooks for custom permission validation

118</Warning>

119 

120**Read & Edit**

121 

122`Edit` rules apply to all built-in tools that edit files. Claude will make a best-effort attempt to apply `Read` rules to all built-in tools that read files like Grep, Glob, and LS.

123 

124Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

125 

126| Pattern | Meaning | Example | Matches |

127| ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- |

128| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

129| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

130| `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `<settings file path>/src/**/*.ts` |

131| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

132 

133<Warning>

134 A pattern like `/Users/alice/file` is NOT an absolute path - it's relative to your settings file! Use `//Users/alice/file` for absolute paths.

135</Warning>

136 

137* `Edit(/docs/**)` - Edits in `<project>/docs/` (NOT `/docs/`!)

138* `Read(~/.zshrc)` - Reads your home directory's `.zshrc`

139* `Edit(//tmp/scratch.txt)` - Edits the absolute path `/tmp/scratch.txt`

140* `Read(src/**)` - Reads from `<current-directory>/src/`

141 

142**WebFetch**

143 

144* `WebFetch(domain:example.com)` Matches fetch requests to example.com

145 

146**MCP**

147 

148* `mcp__puppeteer` Matches any tool provided by the `puppeteer` server (name configured in Claude Code)

149* `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server

150 

151<Warning>

152 Unlike other permission types, MCP permissions do NOT support wildcards (`*`).

153 

154 To approve all tools from an MCP server:

155 

156 * ✅ Use: `mcp__github` (approves ALL GitHub tools)

157 * ❌ Don't use: `mcp__github__*` (wildcards are not supported)

158 

159 To approve specific tools only, list each one:

160 

161 * ✅ Use: `mcp__github__get_issue`

162 * ✅ Use: `mcp__github__list_issues`

163</Warning>

164 

165### Additional permission control with hooks

166 

167[Claude Code hooks](/en/docs/claude-code/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system runs, and the hook output can determine whether to approve or deny the tool call in place of the permission system.

168 

169### Enterprise managed policy settings

170 

171For enterprise deployments of Claude Code, we support enterprise managed policy settings that take precedence over user and project settings. This allows system administrators to enforce security policies that users cannot override.

172 

173System administrators can deploy policies to:

174 

175* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`

176* Linux and WSL: `/etc/claude-code/managed-settings.json`

177* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`

178 

179These policy files follow the same format as regular [settings files](/en/docs/claude-code/settings#settings-files) but cannot be overridden by user or project settings. This ensures consistent security policies across your organization.

180 

181### Settings precedence

182 

183When multiple settings sources exist, they are applied in the following order (highest to lowest precedence):

184 

1851. Enterprise policies

1862. Command line arguments

1873. Local project settings (`.claude/settings.local.json`)

1884. Shared project settings (`.claude/settings.json`)

1895. User settings (`~/.claude/settings.json`)

190 

191This hierarchy ensures that organizational policies are always enforced while still allowing flexibility at the project and user levels where appropriate.

192 

193## Credential management

194 

195Claude Code securely manages your authentication credentials:

196 

197* **Storage location**: On macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain.

198* **Supported authentication types**: Claude.ai credentials, Claude API credentials, Bedrock Auth, and Vertex Auth.

199* **Custom credential scripts**: The [`apiKeyHelper`](/en/docs/claude-code/settings#available-settings) setting can be configured to run a shell script that returns an API key.

200* **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.

interactive-mode.md +183 −27

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Interactive mode5# Interactive mode

2 6 

3> Complete reference for keyboard shortcuts, input modes, and interactive features in Claude Code sessions.7> Complete reference for keyboard shortcuts, input modes, and interactive features in Claude Code sessions.


6 10 

7<Note>11<Note>

8 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 

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:

15 

16 * **iTerm2**: settings → Profiles → Keys → set Left/Right Option key to "Esc+"

17 * **Terminal.app**: settings → Profiles → Keyboard → check "Use Option as Meta Key"

18 * **VS Code**: set `"terminal.integrated.macOptionIsMeta": true` in VS Code settings

19 

20 See [Terminal configuration](/en/terminal-config) for details.

9</Note>21</Note>

10 22 

11### General controls23### General controls

12 24 

13| Shortcut | Description | Context |25| Shortcut | Description | Context |

14| :------------------------------------------- | :----------------------------------------------------------------------- | :---------------------------------------------------------- |26| :------------------------------------------------ | :------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

15| `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 |

16| `Ctrl+D` | Exit Claude Code session | EOF signal |29| `Ctrl+D` | Exit Claude Code session | EOF signal |

17| `Ctrl+L` | Clear terminal screen | Keeps conversation history |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 |

18| `Ctrl+O` | Toggle verbose output | Shows detailed tool usage and execution |31| `Ctrl+L` | Redraw the screen | Repaints the current UI without clearing conversation history |

32| `Ctrl+O` | Toggle verbose output | Shows detailed tool usage and execution. Also expands MCP read and search calls, which collapse to a single line like "Queried slack" by default |

19| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |33| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |

20| `Ctrl+V` (macOS/Linux) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file |34| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | 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 |

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 |

21| `Up/Down arrows` | Navigate command history | Recall previous inputs |38| `Up/Down arrows` | Navigate command history | Recall previous inputs |

22| `Esc` + `Esc` | Rewind the code/conversation | Restore the code and/or conversation to a previous point |39| `Esc` + `Esc` | Rewind or summarize | Restore code and/or conversation to a previous point, or summarize from a selected message |

23| `Tab` | Toggle [extended thinking](/en/docs/build-with-claude/extended-thinking) | Switch between Thinking on and Thinking off |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). |

24| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode |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 |

43| `Option+O` (macOS) or `Alt+O` (Windows/Linux) | Toggle fast mode | Enable or disable [fast mode](/en/fast-mode) |

44 

45### Text editing

46 

47| Shortcut | Description | Context |

48| :----------------------- | :------------------------------- | :------------------------------------------------------------------------------------------------------------ |

49| `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 |

51| `Ctrl+Y` | Paste deleted text | Paste text deleted with `Ctrl+K` or `Ctrl+U` |

52| `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 |

54| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

55 

56### Theme and display

57 

58| Shortcut | Description | Context |

59| :------- | :----------------------------------------- | :----------------------------------------------------------------------------------------------------------- |

60| `Ctrl+T` | Toggle syntax highlighting for code blocks | Only works inside the `/theme` picker menu. Controls whether code in Claude's responses uses syntax coloring |

25 61 

26### Multiline input62### Multiline input

27 63 

28| Method | Shortcut | Context |64| Method | Shortcut | Context |

29| :--------------- | :------------- | :-------------------------------- |65| :--------------- | :------------- | :------------------------------------------------------ |

30| Quick escape | `\` + `Enter` | Works in all terminals |66| Quick escape | `\` + `Enter` | Works in all terminals |

31| macOS default | `Option+Enter` | Default on macOS |67| macOS default | `Option+Enter` | Default on macOS |

32| Terminal setup | `Shift+Enter` | After `/terminal-setup` |68| Shift+Enter | `Shift+Enter` | Works out of the box in iTerm2, WezTerm, Ghostty, Kitty |

33| Control sequence | `Ctrl+J` | Line feed character for multiline |69| Control sequence | `Ctrl+J` | Line feed character for multiline |

34| Paste mode | Paste directly | For code blocks, logs |70| Paste mode | Paste directly | For code blocks, logs |

35 71 

36<Tip>72<Tip>

37 Configure your preferred line break behavior in terminal settings. Run `/terminal-setup` to install Shift+Enter binding for iTerm2 and VS Code terminals.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.

38</Tip>74</Tip>

39 75 

40### Quick commands76### Quick commands

41 77 

42| Shortcut | Description | Notes |78| Shortcut | Description | Notes |

43| :----------- | :--------------------------------- | :------------------------------------------------------------ |79| :----------- | :---------------- | :------------------------------------------------------------------- |

44| `#` at start | Memory shortcut - add to CLAUDE.md | Prompts for file selection |80| `/` at start | Command or skill | See [built-in commands](#built-in-commands) and [skills](/en/skills) |

45| `/` at start | Slash command | See [slash commands](/en/docs/claude-code/slash-commands) |

46| `!` at start | Bash mode | Run commands directly and add execution output to the session |81| `!` at start | Bash mode | Run commands directly and add execution output to the session |

47| `@` | File path mention | Trigger file path autocomplete |82| `@` | File path mention | Trigger file path autocomplete |

48 83 

84### Transcript viewer

85 

86When the transcript viewer is open (toggled with `Ctrl+O`), these shortcuts are available. `Ctrl+E` can be rebound via [`transcript:toggleShowAll`](/en/keybindings).

87 

88| Shortcut | Description |

89| :------------------- | :-------------------------------------------------------------------------------------- |

90| `Ctrl+E` | Toggle show all content |

91| `q`, `Ctrl+C`, `Esc` | Exit transcript view. All three can be rebound via [`transcript:exit`](/en/keybindings) |

92 

93### Voice input

94 

95| Shortcut | Description | Notes |

96| :----------- | :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |

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) |

98 

99## Built-in commands

100 

101Type `/` in Claude Code to see all available commands, or type `/` followed by any letters to filter. The `/` menu shows both built-in commands and [bundled skills](/en/skills#bundled-skills) like `/simplify`. Not all commands are visible to every user since some depend on your platform or plan.

102 

103See the [commands reference](/en/commands) for the full list of built-in commands. To create your own commands, see [skills](/en/skills).

104 

49## Vim editor mode105## Vim editor mode

50 106 

51Enable vim-style editing with `/vim` command or configure permanently via `/config`.107Enable vim-style editing with `/vim` command or configure permanently via `/config`.


65### Navigation (NORMAL mode)121### Navigation (NORMAL mode)

66 122 

67| Command | Action |123| Command | Action |

68| :-------------- | :------------------------ |124| :-------------- | :-------------------------------------------------- |

69| `h`/`j`/`k`/`l` | Move left/down/up/right |125| `h`/`j`/`k`/`l` | Move left/down/up/right |

70| `w` | Next word |126| `w` | Next word |

71| `e` | End of word |127| `e` | End of word |


75| `^` | First non-blank character |131| `^` | First non-blank character |

76| `gg` | Beginning of input |132| `gg` | Beginning of input |

77| `G` | End of input |133| `G` | End of input |

134| `f{char}` | Jump to next occurrence of character |

135| `F{char}` | Jump to previous occurrence of character |

136| `t{char}` | Jump to just before next occurrence of character |

137| `T{char}` | Jump to just after previous occurrence of character |

138| `;` | Repeat last f/F/t/T motion |

139| `,` | Repeat last f/F/t/T motion in reverse |

140 

141<Note>

142 In vim normal mode, if the cursor is at the beginning or end of input and cannot move further, the arrow keys navigate command history instead.

143</Note>

78 144 

79### Editing (NORMAL mode)145### Editing (NORMAL mode)

80 146 


87| `cc` | Change line |153| `cc` | Change line |

88| `C` | Change to end of line |154| `C` | Change to end of line |

89| `cw`/`ce`/`cb` | Change word/to end/back |155| `cw`/`ce`/`cb` | Change word/to end/back |

156| `yy`/`Y` | Yank (copy) line |

157| `yw`/`ye`/`yb` | Yank word/to end/back |

158| `p` | Paste after cursor |

159| `P` | Paste before cursor |

160| `>>` | Indent line |

161| `<<` | Dedent line |

162| `J` | Join lines |

90| `.` | Repeat last change |163| `.` | Repeat last change |

91 164 

165### Text objects (NORMAL mode)

166 

167Text objects work with operators like `d`, `c`, and `y`:

168 

169| Command | Action |

170| :-------- | :--------------------------------------- |

171| `iw`/`aw` | Inner/around word |

172| `iW`/`aW` | Inner/around WORD (whitespace-delimited) |

173| `i"`/`a"` | Inner/around double quotes |

174| `i'`/`a'` | Inner/around single quotes |

175| `i(`/`a(` | Inner/around parentheses |

176| `i[`/`a[` | Inner/around brackets |

177| `i{`/`a{` | Inner/around braces |

178 

92## Command history179## Command history

93 180 

94Claude Code maintains command history for the current session:181Claude Code maintains command history for the current session:

95 182 

96* History is stored per working directory183* Input history is stored per working directory

97* Cleared with `/clear` command184* Input history resets when you run `/clear` to start a new session. The previous session's conversation is preserved and can be resumed.

98* Use Up/Down arrows to navigate (see keyboard shortcuts above)185* Use Up/Down arrows to navigate (see keyboard shortcuts above)

99* **Note**: History expansion (`!`) is disabled by default186* **Note**: history expansion (`!`) is disabled by default

100 187 

101### Reverse search with Ctrl+R188### Reverse search with Ctrl+R

102 189 

103Press `Ctrl+R` to interactively search through your command history:190Press `Ctrl+R` to interactively search through your command history:

104 191 

1051. **Start search**: Press `Ctrl+R` to activate reverse history search1921. **Start search**: press `Ctrl+R` to activate reverse history search

1062. **Type query**: Enter text to search for in previous commands - the search term will be highlighted in matching results1932. **Type query**: enter text to search for in previous commands. The search term is highlighted in matching results

1073. **Navigate matches**: Press `Ctrl+R` again to cycle through older matches1943. **Navigate matches**: press `Ctrl+R` again to cycle through older matches

1084. **Accept match**:1954. **Accept match**:

109 * Press `Tab` or `Esc` to accept the current match and continue editing196 * Press `Tab` or `Esc` to accept the current match and continue editing

110 * Press `Enter` to accept and execute the command immediately197 * Press `Enter` to accept and execute the command immediately


112 * Press `Ctrl+C` to cancel and restore your original input199 * Press `Ctrl+C` to cancel and restore your original input

113 * Press `Backspace` on empty search to cancel200 * Press `Backspace` on empty search to cancel

114 201 

115The search displays matching commands with the search term highlighted, making it easy to find and reuse previous inputs.202The search displays matching commands with the search term highlighted, so you can find and reuse previous inputs.

116 203 

117## Background bash commands204## Background bash commands

118 205 


129 216 

130**Key features:**217**Key features:**

131 218 

132* Output is buffered and Claude can retrieve it using the BashOutput tool219* Output is written to a file and Claude can retrieve it using the Read tool

133* Background tasks have unique IDs for tracking and output retrieval220* Background tasks have unique IDs for tracking and output retrieval

134* Background tasks are automatically cleaned up when Claude Code exits221* Background tasks are automatically cleaned up when Claude Code exits

222* Background tasks are automatically terminated if output exceeds 5GB, with a note in stderr explaining why

223 

224To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars) for details.

135 225 

136**Common backgrounded commands:**226**Common backgrounded commands:**

137 227 


157* Shows real-time progress and output247* Shows real-time progress and output

158* Supports the same `Ctrl+B` backgrounding for long-running commands248* Supports the same `Ctrl+B` backgrounding for long-running commands

159* Does not require Claude to interpret or approve the command249* 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 project

251* 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 `!` behavior

160 253 

161This is useful for quick shell operations while maintaining conversation context.254This is useful for quick shell operations while maintaining conversation context.

162 255 

256## Prompt suggestions

257 

258When you first open a session, a grayed-out example command appears in the prompt input to help you get started. Claude Code picks this from your project's git history, so it reflects files you've been working on recently.

259 

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.

261 

262* Press **Tab** or **Right arrow** to accept the suggestion, or press **Enter** to accept and submit

263* Start typing to dismiss it

264 

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.

266 

267Suggestions are automatically skipped after the first turn of a conversation, in non-interactive mode, and in plan mode.

268 

269To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:

270 

271```bash theme={null}

272export CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false

273```

274 

275## Side questions with /btw

276 

277Use `/btw` to ask a quick question about your current work without adding to the conversation history. This is useful when you want a fast answer but don't want to clutter the main context or derail Claude from a long-running task.

278 

279```

280/btw what was the name of that config file again?

281```

282 

283Side questions have full visibility into the current conversation, so you can ask about code Claude has already read, decisions it made earlier, or anything else from the session. The question and answer are ephemeral: they appear in a dismissible overlay and never enter the conversation history.

284 

285* **Available while Claude is working**: you can run `/btw` even while Claude is processing a response. The side question runs independently and does not interrupt the main turn.

286* **No tool access**: side questions answer only from what is already in context. Claude cannot read files, run commands, or search when answering a side question.

287* **Single response**: there are no follow-up turns. If you need a back-and-forth, use a normal prompt instead.

288* **Low cost**: the side question reuses the parent conversation's prompt cache, so the additional cost is minimal.

289 

290Press **Space**, **Enter**, or **Escape** to dismiss the answer and return to the prompt.

291 

292`/btw` is the inverse of a [subagent](/en/sub-agents): it sees your full conversation but has no tools, while a subagent has full tools but starts with an empty context. Use `/btw` to ask about what Claude already knows from this session; use a subagent to go find out something new.

293 

294## Task list

295 

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.

297 

298* Press `Ctrl+T` to toggle the task list view. The display shows up to 10 tasks at a time

299* 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 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`

302 

303## PR review status

304 

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:

306 

307* Green: approved

308* Yellow: pending review

309* Red: changes requested

310* Gray: draft

311* Purple: merged

312 

313`Cmd+click` (Mac) or `Ctrl+click` (Windows/Linux) the link to open the pull request in your browser. The status updates automatically every 60 seconds.

314 

315<Note>

316 PR status requires the `gh` CLI to be installed and authenticated (`gh auth login`).

317</Note>

318 

163## See also319## See also

164 320 

165* [Slash commands](/en/docs/claude-code/slash-commands) - Interactive session commands321* [Skills](/en/skills) - Custom prompts and workflows

166* [Checkpointing](/en/docs/claude-code/checkpointing) - Rewind Claude's edits and restore previous states322* [Checkpointing](/en/checkpointing) - Rewind Claude's edits and restore previous states

167* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line flags and options323* [CLI reference](/en/cli-reference) - Command-line flags and options

168* [Settings](/en/docs/claude-code/settings) - Configuration options324* [Settings](/en/settings) - Configuration options

169* [Memory management](/en/docs/claude-code/memory) - Managing CLAUDE.md files325* [Memory management](/en/memory) - Managing CLAUDE.md files

jetbrains.md +15 −10

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# JetBrains IDEs5# JetBrains IDEs

2 6 

3> Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more7> Use Claude Code with JetBrains IDEs including IntelliJ, PyCharm, WebStorm, and more


20* **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

21* **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

22* **Selection context**: The current selection/tab in the IDE is automatically shared with Claude Code26* **Selection context**: The current selection/tab in the IDE is automatically shared with Claude Code

23* **File reference shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references (e.g., @File#L1-99)27* **File reference shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references (for example, @File#L1-99)

24* **Diagnostic sharing**: Diagnostic errors (lint, syntax, etc.) from the IDE are automatically shared with Claude as you work28* **Diagnostic sharing**: Diagnostic errors (lint, syntax, etc.) from the IDE are automatically shared with Claude as you work

25 29 

26## Installation30## Installation


29 33 

30Find 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.

31 35 

32### Auto-Installation36If you haven't installed Claude Code yet, see [our quickstart guide](/en/quickstart) for installation instructions.

33 

34The plugin may also be auto-installed when you run `claude` in the integrated terminal. The IDE must be restarted completely to take effect.

35 37 

36<Note>38<Note>

37 After installing the plugin, you must restart your IDE completely for it to take effect. You may need to restart multiple times.39 After installing the plugin, you may need to restart your IDE completely for it to take effect.

38</Note>40</Note>

39 41 

40## Usage42## Usage


49 51 

50```bash theme={null}52```bash theme={null}

51claude53claude

52> /ide54```

55 

56```text theme={null}

57/ide

53```58```

54 59 

55If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root.60If you want Claude to have access to the same files as your IDE, start Claude Code from the same directory as your IDE project root.


70 75 

71#### General Settings76#### General Settings

72 77 

73* **Claude command**: Specify a custom command to run Claude (e.g., `claude`, `/usr/local/bin/claude`, or `npx @anthropic/claude`)78* **Claude command**: Specify a custom command to run Claude (for example, `claude`, `/usr/local/bin/claude`, or `npx @anthropic/claude`)

74* **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

75* **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** (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)

76* **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)


104### WSL Configuration109### WSL Configuration

105 110 

106<Warning>111<Warning>

107 WSL users may need additional configuration for IDE detection to work properly. See our [WSL troubleshooting guide](/en/docs/claude-code/troubleshooting#jetbrains-ide-not-detected-on-wsl2) for detailed setup instructions.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.

108</Warning>113</Warning>

109 114 

110WSL configuration may require:115WSL configuration may require:


127* Verify the plugin is installed and enabled132* Verify the plugin is installed and enabled

128* Restart the IDE completely133* Restart the IDE completely

129* Check that you're running Claude Code from the integrated terminal134* Check that you're running Claude Code from the integrated terminal

130* For WSL users, see the [WSL troubleshooting guide](/en/docs/claude-code/troubleshooting#jetbrains-ide-not-detected-on-wsl2)135* For WSL users, see the [WSL troubleshooting guide](/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2)

131 136 

132### Command Not Found137### Command Not Found

133 138 


147* Taking extra care to ensure Claude is only used with trusted prompts152* Taking extra care to ensure Claude is only used with trusted prompts

148* Being aware of which files Claude Code has access to modify153* Being aware of which files Claude Code has access to modify

149 154 

150For additional help, see our [troubleshooting guide](/en/docs/claude-code/troubleshooting).155For additional help, see our [troubleshooting guide](/en/troubleshooting).

keybindings.md +421 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Customize keyboard shortcuts

6 

7> Customize keyboard shortcuts in Claude Code with a keybindings configuration file.

8 

9<Note>

10 Customizable keyboard shortcuts require Claude Code v2.1.18 or later. Check your version with `claude --version`.

11</Note>

12 

13Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`.

14 

15## Configuration file

16 

17The keybindings configuration file is an object with a `bindings` array. Each block specifies a context and a map of keystrokes to actions.

18 

19<Note>Changes to the keybindings file are automatically detected and applied without restarting Claude Code.</Note>

20 

21| Field | Description |

22| :--------- | :------------------------------------------------- |

23| `$schema` | Optional JSON Schema URL for editor autocompletion |

24| `$docs` | Optional documentation URL |

25| `bindings` | Array of binding blocks by context |

26 

27This example binds `Ctrl+E` to open an external editor in the chat context, and unbinds `Ctrl+U`:

28 

29```json theme={null}

30{

31 "$schema": "https://www.schemastore.org/claude-code-keybindings.json",

32 "$docs": "https://code.claude.com/docs/en/keybindings",

33 "bindings": [

34 {

35 "context": "Chat",

36 "bindings": {

37 "ctrl+e": "chat:externalEditor",

38 "ctrl+u": null

39 }

40 }

41 ]

42}

43```

44 

45## Contexts

46 

47Each binding block specifies a **context** where the bindings apply:

48 

49| Context | Description |

50| :---------------- | :----------------------------------------------- |

51| `Global` | Applies everywhere in the app |

52| `Chat` | Main chat input area |

53| `Autocomplete` | Autocomplete menu is open |

54| `Settings` | Settings menu |

55| `Confirmation` | Permission and confirmation dialogs |

56| `Tabs` | Tab navigation components |

57| `Help` | Help menu is visible |

58| `Transcript` | Transcript viewer |

59| `HistorySearch` | History search mode (Ctrl+R) |

60| `Task` | Background task is running |

61| `ThemePicker` | Theme picker dialog |

62| `Attachments` | Image attachment navigation in select dialogs |

63| `Footer` | Footer indicator navigation (tasks, teams, diff) |

64| `MessageSelector` | Rewind and summarize dialog message selection |

65| `DiffDialog` | Diff viewer navigation |

66| `ModelPicker` | Model picker effort level |

67| `Select` | Generic select/list components |

68| `Plugin` | Plugin dialog (browse, discover, manage) |

69 

70## Available actions

71 

72Actions follow a `namespace:action` format, such as `chat:submit` to send a message or `app:toggleTodos` to show the task list. Each context has specific actions available.

73 

74### App actions

75 

76Actions available in the `Global` context:

77 

78| Action | Default | Description |

79| :--------------------- | :------ | :-------------------------- |

80| `app:interrupt` | Ctrl+C | Cancel current operation |

81| `app:exit` | Ctrl+D | Exit Claude Code |

82| `app:redraw` | Ctrl+L | Redraw the screen |

83| `app:toggleTodos` | Ctrl+T | Toggle task list visibility |

84| `app:toggleTranscript` | Ctrl+O | Toggle verbose transcript |

85 

86### History actions

87 

88Actions for navigating command history:

89 

90| Action | Default | Description |

91| :----------------- | :------ | :-------------------- |

92| `history:search` | Ctrl+R | Open history search |

93| `history:previous` | Up | Previous history item |

94| `history:next` | Down | Next history item |

95 

96### Chat actions

97 

98Actions available in the `Chat` context:

99 

100| Action | Default | Description |

101| :-------------------- | :------------------------ | :---------------------------------- |

102| `chat:cancel` | Escape | Cancel current input |

103| `chat:killAgents` | Ctrl+X Ctrl+K | Kill all background agents |

104| `chat:cycleMode` | Shift+Tab\* | Cycle permission modes |

105| `chat:modelPicker` | Cmd+P / Meta+P | Open model picker |

106| `chat:fastMode` | Meta+O | Toggle fast mode |

107| `chat:thinkingToggle` | Cmd+T / Meta+T | Toggle extended thinking |

108| `chat:submit` | Enter | Submit message |

109| `chat:newline` | (unbound) | Insert a newline without submitting |

110| `chat:undo` | Ctrl+\_, Ctrl+Shift+- | Undo last action |

111| `chat:externalEditor` | Ctrl+G, Ctrl+X Ctrl+E | Open in external editor |

112| `chat:stash` | Ctrl+S | Stash current prompt |

113| `chat:imagePaste` | Ctrl+V (Alt+V on Windows) | Paste image |

114 

115\*On Windows without VT mode (Node \<24.2.0/\<22.17.0, Bun \<1.2.23), defaults to Meta+M.

116 

117### Autocomplete actions

118 

119Actions available in the `Autocomplete` context:

120 

121| Action | Default | Description |

122| :---------------------- | :------ | :------------------ |

123| `autocomplete:accept` | Tab | Accept suggestion |

124| `autocomplete:dismiss` | Escape | Dismiss menu |

125| `autocomplete:previous` | Up | Previous suggestion |

126| `autocomplete:next` | Down | Next suggestion |

127 

128### Confirmation actions

129 

130Actions available in the `Confirmation` context:

131 

132| Action | Default | Description |

133| :-------------------------- | :-------- | :---------------------------- |

134| `confirm:yes` | Y, Enter | Confirm action |

135| `confirm:no` | N, Escape | Decline action |

136| `confirm:previous` | Up | Previous option |

137| `confirm:next` | Down | Next option |

138| `confirm:nextField` | Tab | Next field |

139| `confirm:previousField` | (unbound) | Previous field |

140| `confirm:toggle` | Space | Toggle selection |

141| `confirm:cycleMode` | Shift+Tab | Cycle permission modes |

142| `confirm:toggleExplanation` | Ctrl+E | Toggle permission explanation |

143 

144### Permission actions

145 

146Actions available in the `Confirmation` context for permission dialogs:

147 

148| Action | Default | Description |

149| :----------------------- | :------ | :--------------------------- |

150| `permission:toggleDebug` | Ctrl+D | Toggle permission debug info |

151 

152### Transcript actions

153 

154Actions available in the `Transcript` context:

155 

156| Action | Default | Description |

157| :------------------------- | :---------------- | :---------------------- |

158| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |

159| `transcript:exit` | q, Ctrl+C, Escape | Exit transcript view |

160 

161### History search actions

162 

163Actions available in the `HistorySearch` context:

164 

165| Action | Default | Description |

166| :---------------------- | :---------- | :----------------------- |

167| `historySearch:next` | Ctrl+R | Next match |

168| `historySearch:accept` | Escape, Tab | Accept selection |

169| `historySearch:cancel` | Ctrl+C | Cancel search |

170| `historySearch:execute` | Enter | Execute selected command |

171 

172### Task actions

173 

174Actions available in the `Task` context:

175 

176| Action | Default | Description |

177| :---------------- | :------ | :---------------------- |

178| `task:background` | Ctrl+B | Background current task |

179 

180### Theme actions

181 

182Actions available in the `ThemePicker` context:

183 

184| Action | Default | Description |

185| :------------------------------- | :------ | :------------------------- |

186| `theme:toggleSyntaxHighlighting` | Ctrl+T | Toggle syntax highlighting |

187 

188### Help actions

189 

190Actions available in the `Help` context:

191 

192| Action | Default | Description |

193| :------------- | :------ | :-------------- |

194| `help:dismiss` | Escape | Close help menu |

195 

196### Tabs actions

197 

198Actions available in the `Tabs` context:

199 

200| Action | Default | Description |

201| :-------------- | :-------------- | :----------- |

202| `tabs:next` | Tab, Right | Next tab |

203| `tabs:previous` | Shift+Tab, Left | Previous tab |

204 

205### Attachments actions

206 

207Actions available in the `Attachments` context:

208 

209| Action | Default | Description |

210| :--------------------- | :---------------- | :------------------------- |

211| `attachments:next` | Right | Next attachment |

212| `attachments:previous` | Left | Previous attachment |

213| `attachments:remove` | Backspace, Delete | Remove selected attachment |

214| `attachments:exit` | Down, Escape | Exit attachment navigation |

215 

216### Footer actions

217 

218Actions available in the `Footer` context:

219 

220| Action | Default | Description |

221| :---------------------- | :------ | :--------------------------------------- |

222| `footer:next` | Right | Next footer item |

223| `footer:previous` | Left | Previous footer item |

224| `footer:up` | Up | Navigate up in footer (deselects at top) |

225| `footer:down` | Down | Navigate down in footer |

226| `footer:openSelected` | Enter | Open selected footer item |

227| `footer:clearSelection` | Escape | Clear footer selection |

228 

229### Message selector actions

230 

231Actions available in the `MessageSelector` context:

232 

233| Action | Default | Description |

234| :----------------------- | :---------------------------------------- | :---------------- |

235| `messageSelector:up` | Up, K, Ctrl+P | Move up in list |

236| `messageSelector:down` | Down, J, Ctrl+N | Move down in list |

237| `messageSelector:top` | Ctrl+Up, Shift+Up, Meta+Up, Shift+K | Jump to top |

238| `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | Jump to bottom |

239| `messageSelector:select` | Enter | Select message |

240 

241### Diff actions

242 

243Actions available in the `DiffDialog` context:

244 

245| Action | Default | Description |

246| :-------------------- | :----------------- | :--------------------- |

247| `diff:dismiss` | Escape | Close diff viewer |

248| `diff:previousSource` | Left | Previous diff source |

249| `diff:nextSource` | Right | Next diff source |

250| `diff:previousFile` | Up | Previous file in diff |

251| `diff:nextFile` | Down | Next file in diff |

252| `diff:viewDetails` | Enter | View diff details |

253| `diff:back` | (context-specific) | Go back in diff viewer |

254 

255### Model picker actions

256 

257Actions available in the `ModelPicker` context:

258 

259| Action | Default | Description |

260| :--------------------------- | :------ | :-------------------- |

261| `modelPicker:decreaseEffort` | Left | Decrease effort level |

262| `modelPicker:increaseEffort` | Right | Increase effort level |

263 

264### Select actions

265 

266Actions available in the `Select` context:

267 

268| Action | Default | Description |

269| :---------------- | :-------------- | :--------------- |

270| `select:next` | Down, J, Ctrl+N | Next option |

271| `select:previous` | Up, K, Ctrl+P | Previous option |

272| `select:accept` | Enter | Accept selection |

273| `select:cancel` | Escape | Cancel selection |

274 

275### Plugin actions

276 

277Actions available in the `Plugin` context:

278 

279| Action | Default | Description |

280| :--------------- | :------ | :----------------------- |

281| `plugin:toggle` | Space | Toggle plugin selection |

282| `plugin:install` | I | Install selected plugins |

283 

284### Settings actions

285 

286Actions available in the `Settings` context:

287 

288| Action | Default | Description |

289| :---------------- | :------ | :-------------------------------------------------------------------------- |

290| `settings:search` | / | Enter search mode |

291| `settings:retry` | R | Retry loading usage data (on error) |

292| `settings:close` | Enter | Save changes and close the config panel. Escape discards changes and closes |

293 

294### Voice actions

295 

296Actions available in the `Chat` context when [voice dictation](/en/voice-dictation) is enabled:

297 

298| Action | Default | Description |

299| :----------------- | :------ | :----------------------- |

300| `voice:pushToTalk` | Space | Hold to dictate a prompt |

301 

302## Keystroke syntax

303 

304### Modifiers

305 

306Use modifier keys with the `+` separator:

307 

308* `ctrl` or `control` - Control key

309* `alt`, `opt`, or `option` - Alt/Option key

310* `shift` - Shift key

311* `meta`, `cmd`, or `command` - Meta/Command key

312 

313For example:

314 

315```text theme={null}

316ctrl+k Single key with modifier

317shift+tab Shift + Tab

318meta+p Command/Meta + P

319ctrl+shift+c Multiple modifiers

320```

321 

322### Uppercase letters

323 

324A standalone uppercase letter implies Shift. For example, `K` is equivalent to `shift+k`. This is useful for vim-style bindings where uppercase and lowercase keys have different meanings.

325 

326Uppercase letters with modifiers (e.g., `ctrl+K`) are treated as stylistic and do **not** imply Shift: `ctrl+K` is the same as `ctrl+k`.

327 

328### Chords

329 

330Chords are sequences of keystrokes separated by spaces:

331 

332```text theme={null}

333ctrl+k ctrl+s Press Ctrl+K, release, then Ctrl+S

334```

335 

336### Special keys

337 

338* `escape` or `esc` - Escape key

339* `enter` or `return` - Enter key

340* `tab` - Tab key

341* `space` - Space bar

342* `up`, `down`, `left`, `right` - Arrow keys

343* `backspace`, `delete` - Delete keys

344 

345## Unbind default shortcuts

346 

347Set an action to `null` to unbind a default shortcut:

348 

349```json theme={null}

350{

351 "bindings": [

352 {

353 "context": "Chat",

354 "bindings": {

355 "ctrl+s": null

356 }

357 }

358 ]

359}

360```

361 

362This also works for chord bindings. Unbinding every chord that shares a prefix frees that prefix for use as a single-key binding:

363 

364```json theme={null}

365{

366 "bindings": [

367 {

368 "context": "Chat",

369 "bindings": {

370 "ctrl+x ctrl+k": null,

371 "ctrl+x ctrl+e": null,

372 "ctrl+x": "chat:newline"

373 }

374 }

375 ]

376}

377```

378 

379If you unbind some but not all chords on a prefix, pressing the prefix still enters chord-wait mode for the remaining bindings.

380 

381## Reserved shortcuts

382 

383These shortcuts cannot be rebound:

384 

385| Shortcut | Reason |

386| :------- | :--------------------------------------------- |

387| Ctrl+C | Hardcoded interrupt/cancel |

388| Ctrl+D | Hardcoded exit |

389| Ctrl+M | Identical to Enter in terminals (both send CR) |

390 

391## Terminal conflicts

392 

393Some shortcuts may conflict with terminal multiplexers:

394 

395| Shortcut | Conflict |

396| :------- | :-------------------------------- |

397| Ctrl+B | tmux prefix (press twice to send) |

398| Ctrl+A | GNU screen prefix |

399| Ctrl+Z | Unix process suspend (SIGTSTP) |

400 

401## Vim mode interaction

402 

403When vim mode is enabled (`/vim`), keybindings and vim mode operate independently:

404 

405* **Vim mode** handles input at the text input level (cursor movement, modes, motions)

406* **Keybindings** handle actions at the component level (toggle todos, submit, etc.)

407* The Escape key in vim mode switches INSERT to NORMAL mode; it does not trigger `chat:cancel`

408* Most Ctrl+key shortcuts pass through vim mode to the keybinding system

409* In vim NORMAL mode, `?` shows the help menu (vim behavior)

410 

411## Validation

412 

413Claude Code validates your keybindings and shows warnings for:

414 

415* Parse errors (invalid JSON or structure)

416* Invalid context names

417* Reserved shortcut conflicts

418* Terminal multiplexer conflicts

419* Duplicate bindings in the same context

420 

421Run `/doctor` to see any keybinding warnings.

llm-gateway.md +56 −13

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# LLM gateway configuration5# LLM gateway configuration

2 6 

3> Learn how to configure Claude Code with LLM gateway solutions, including LiteLLM setup, authentication methods, and enterprise features like usage tracking and budget management.7> Learn how to configure Claude Code to work with LLM gateway solutions. Covers gateway requirements, authentication configuration, model selection, and provider-specific endpoint setup.

4 8 

5LLM gateways provide a centralized proxy layer between Claude Code and model providers, offering:9LLM gateways provide a centralized proxy layer between Claude Code and model providers, often providing:

6 10 

7* **Centralized authentication** - Single point for API key management11* **Centralized authentication** - Single point for API key management

8* **Usage tracking** - Monitor usage across teams and projects12* **Usage tracking** - Monitor usage across teams and projects


10* **Audit logging** - Track all model interactions for compliance14* **Audit logging** - Track all model interactions for compliance

11* **Model routing** - Switch between providers without code changes15* **Model routing** - Switch between providers without code changes

12 16 

13## LiteLLM configuration17## Gateway requirements

18 

19For an LLM gateway to work with Claude Code, it must meet the following requirements:

20 

21**API format**

22 

23The gateway must expose to clients at least one of the following API formats:

24 

251. **Anthropic Messages**: `/v1/messages`, `/v1/messages/count_tokens`

26 * Must forward request headers: `anthropic-beta`, `anthropic-version`

27 

282. **Bedrock InvokeModel**: `/invoke`, `/invoke-with-response-stream`

29 * Must preserve request body fields: `anthropic_beta`, `anthropic_version`

30 

313. **Vertex rawPredict**: `:rawPredict`, `:streamRawPredict`, `/count-tokens:rawPredict`

32 * Must forward request headers: `anthropic-beta`, `anthropic-version`

33 

34Failure to forward headers or preserve body fields may result in reduced functionality or inability to use Claude Code features.

14 35 

15<Note>36<Note>

16 LiteLLM is a third-party proxy service. Anthropic doesn't endorse, maintain, or audit LiteLLM's security or functionality. This guide is provided for informational purposes and may become outdated. Use at your own discretion.37 Claude Code determines which features to enable based on the API format. When using the Anthropic Messages format with Bedrock or Vertex, you may need to set environment variable `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`.

17</Note>38</Note>

18 39 

40**Request headers**

41 

42Claude Code includes the following headers on every API request:

43 

44| Header | Description |

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. |

47 

48## Configuration

49 

50### Model selection

51 

52By default, Claude Code will use standard model names for the selected API format.

53 

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.

55 

56## LiteLLM configuration

57 

58<Warning>

59 LiteLLM PyPI versions 1.82.7 and 1.82.8 were compromised with credential-stealing malware. Do not install these versions. If you have already installed them:

60 

61 * Remove the package

62 * Rotate all credentials on affected systems

63 * Follow the remediation steps in [BerriAI/litellm#24518](https://github.com/BerriAI/litellm/issues/24518)

64 

65 LiteLLM is a third-party proxy service. Anthropic doesn't endorse, maintain, or audit LiteLLM's security or functionality. This guide is provided for informational purposes and may become outdated. Use at your own discretion.

66</Warning>

67 

19### Prerequisites68### Prerequisites

20 69 

21* Claude Code updated to the latest version70* Claude Code updated to the latest version


129export CLOUD_ML_REGION=us-east5178export CLOUD_ML_REGION=us-east5

130```179```

131 180 

132### Model selection

133 

134By default, the models will use those specified in [Model configuration](/en/docs/claude-code/bedrock-vertex-proxies#model-configuration).

135 

136If you have configured custom model names in LiteLLM, set the aforementioned environment variables to those custom names.

137 

138For more detailed information, refer to the [LiteLLM documentation](https://docs.litellm.ai/).181For more detailed information, refer to the [LiteLLM documentation](https://docs.litellm.ai/).

139 182 

140## Additional resources183## Additional resources

141 184 

142* [LiteLLM documentation](https://docs.litellm.ai/)185* [LiteLLM documentation](https://docs.litellm.ai/)

143* [Claude Code settings](/en/docs/claude-code/settings)186* [Claude Code settings](/en/settings)

144* [Enterprise network configuration](/en/docs/claude-code/network-config)187* [Enterprise network configuration](/en/network-config)

145* [Third-party integrations overview](/en/docs/claude-code/third-party-integrations)188* [Third-party integrations overview](/en/third-party-integrations)

mcp.md +598 −86

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Connect Claude Code to tools via MCP5# Connect Claude Code to tools via MCP

2 6 

3> Learn how to connect Claude Code to your tools with the Model Context Protocol.7> Learn how to connect Claude Code to your tools with the Model Context Protocol.

4 8 

5 9 

6Claude Code can connect to hundreds of external tools and data sources through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction), an open-source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs.10Claude Code can connect to hundreds of external tools and data sources through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction), an open source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs.

7 11 

8## What you can do with MCP12## What you can do with MCP

9 13 


11 15 

12* **Implement features from issue trackers**: "Add the feature described in JIRA issue ENG-4521 and create a PR on GitHub."16* **Implement features from issue trackers**: "Add the feature described in JIRA issue ENG-4521 and create a PR on GitHub."

13* **Analyze monitoring data**: "Check Sentry and Statsig to check the usage of the feature described in ENG-4521."17* **Analyze monitoring data**: "Check Sentry and Statsig to check the usage of the feature described in ENG-4521."

14* **Query databases**: "Find emails of 10 random users who used feature ENG-4521, based on our Postgres database."18* **Query databases**: "Find emails of 10 random users who used feature ENG-4521, based on our PostgreSQL database."

15* **Integrate designs**: "Update our standard email template based on the new Figma designs that were posted in Slack"19* **Integrate designs**: "Update our standard email template based on the new Figma designs that were posted in Slack"

16* **Automate workflows**: "Create Gmail drafts inviting these 10 users to a feedback session about the new feature."20* **Automate workflows**: "Create Gmail drafts inviting these 10 users to a feedback session about the new feature."

21* **React to external events**: An MCP server can also act as a [channel](/en/channels) that pushes messages into your session, so Claude reacts to Telegram messages, Discord chats, or webhook events while you're away.

17 22 

18## Popular MCP servers23## Popular MCP servers

19 24 


77 82 

78```bash theme={null}83```bash theme={null}

79# Basic syntax84# Basic syntax

80claude mcp add --transport stdio <name> <command> [args...]85claude mcp add [options] <name> -- <command> [args...]

81 86 

82# Real example: Add Airtable server87# Real example: Add Airtable server

83claude mcp add --transport stdio airtable --env AIRTABLE_API_KEY=YOUR_KEY \88claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \

84 -- npx -y airtable-mcp-server89 -- npx -y airtable-mcp-server

85```90```

86 91 

87<Note>92<Note>

88 **Understanding the "--" parameter:**93 **Important: Option ordering**

89 The `--` (double dash) separates Claude's own CLI flags from the command and arguments that get passed to the MCP server. Everything before `--` are options for Claude (like `--env`, `--scope`), and everything after `--` is the actual command to run the MCP server.94 

95 All options (`--transport`, `--env`, `--scope`, `--header`) must come **before** the server name. The `--` (double dash) then separates the server name from the command and arguments that get passed to the MCP server.

90 96 

91 For example:97 For example:

92 98 

93 * `claude mcp add --transport stdio myserver -- npx server` → runs `npx server`99 * `claude mcp add --transport stdio myserver -- npx server` → runs `npx server`

94 * `claude mcp add --transport stdio myserver --env KEY=value -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment100 * `claude mcp add --transport stdio --env KEY=value myserver -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment

95 101 

96 This prevents conflicts between Claude's flags and the server's flags.102 This prevents conflicts between Claude's flags and the server's flags.

97</Note>103</Note>


114/mcp120/mcp

115```121```

116 122 

123### Dynamic tool updates

124 

125Claude 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.

126 

127### Push messages with channels

128 

129An 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.

130 

117<Tip>131<Tip>

118 Tips:132 Tips:

119 133 


121 * `local` (default): Available only to you in the current project (was called `project` in older versions)135 * `local` (default): Available only to you in the current project (was called `project` in older versions)

122 * `project`: Shared with everyone in the project via `.mcp.json` file136 * `project`: Shared with everyone in the project via `.mcp.json` file

123 * `user`: Available to you across all projects (was called `global` in older versions)137 * `user`: Available to you across all projects (was called `global` in older versions)

124 * Set environment variables with `--env` flags (e.g., `--env KEY=value`)138 * Set environment variables with `--env` flags (for example, `--env KEY=value`)

125 * Configure MCP server startup timeout using the MCP\_TIMEOUT environment variable (e.g., `MCP_TIMEOUT=10000 claude` sets a 10-second timeout)139 * Configure MCP server startup timeout using the MCP\_TIMEOUT environment variable (for example, `MCP_TIMEOUT=10000 claude` sets a 10-second timeout)

126 * Claude Code will display a warning when MCP tool output exceeds 10,000 tokens. To increase this limit, set the `MAX_MCP_OUTPUT_TOKENS` environment variable (e.g., `MAX_MCP_OUTPUT_TOKENS=50000`)140 * Claude Code will display a warning when MCP tool output exceeds 10,000 tokens. To increase this limit, set the `MAX_MCP_OUTPUT_TOKENS` environment variable (for example, `MAX_MCP_OUTPUT_TOKENS=50000`)

127 * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication141 * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication

128</Tip>142</Tip>

129 143 


140 154 

141### Plugin-provided MCP servers155### Plugin-provided MCP servers

142 156 

143[Plugins](/en/docs/claude-code/plugins) can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured servers.157[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.

144 158 

145**How plugin MCP servers work**:159**How plugin MCP servers work**:

146 160 


155 169 

156```json theme={null}170```json theme={null}

157{171{

172 "mcpServers": {

158 "database-tools": {173 "database-tools": {

159 "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",174 "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",

160 "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],175 "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],


162 "DB_URL": "${DB_URL}"177 "DB_URL": "${DB_URL}"

163 }178 }

164 }179 }

180 }

165}181}

166```182```

167 183 


181 197 

182**Plugin MCP features**:198**Plugin MCP features**:

183 199 

184* **Automatic lifecycle**: Servers start when plugin enables, but you must restart Claude Code to apply MCP server changes (enabling or disabling)200* **Automatic lifecycle**: At session startup, servers for enabled plugins connect automatically. If you enable or disable a plugin during a session, run `/reload-plugins` to connect or disconnect its MCP servers

185* **Environment variables**: Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths201* **Environment variables**: use `${CLAUDE_PLUGIN_ROOT}` for bundled plugin files and `${CLAUDE_PLUGIN_DATA}` for [persistent state](/en/plugins-reference#persistent-data-directory) that survives plugin updates

186* **User environment access**: Access to same environment variables as manually configured servers202* **User environment access**: Access to same environment variables as manually configured servers

187* **Multiple transport types**: Support stdio, SSE, and HTTP transports (transport support may vary by server)203* **Multiple transport types**: Support stdio, SSE, and HTTP transports (transport support may vary by server)

188 204 


201* **Automatic setup**: No manual MCP configuration needed217* **Automatic setup**: No manual MCP configuration needed

202* **Team consistency**: Everyone gets the same tools when plugin is installed218* **Team consistency**: Everyone gets the same tools when plugin is installed

203 219 

204See the [plugin components reference](/en/docs/claude-code/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins.220See the [plugin components reference](/en/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins.

205 221 

206## MCP installation scopes222## MCP installation scopes

207 223 


209 225 

210### Local scope226### Local scope

211 227 

212Local-scoped servers represent the default configuration level and are stored in your project-specific user settings. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn't be shared.228Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project's path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn't be shared.

229 

230<Note>

231 The term "local scope" for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](/en/settings#settings-files) for details on settings file locations.

232</Note>

213 233 

214```bash theme={null}234```bash theme={null}

215# Add a local-scoped server (default)235# Add a local-scoped server (default)


246 266 

247### User scope267### User scope

248 268 

249User-scoped servers provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects.269User-scoped servers are stored in `~/.claude.json` and provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects.

250 270 

251```bash theme={null}271```bash theme={null}

252# Add a user server272# Add a user server


259 279 

260* **Local scope**: Personal servers, experimental configurations, or sensitive credentials specific to one project280* **Local scope**: Personal servers, experimental configurations, or sensitive credentials specific to one project

261* **Project scope**: Team-shared servers, project-specific tools, or services required for collaboration281* **Project scope**: Team-shared servers, project-specific tools, or services required for collaboration

262* **User scope**: Personal utilities needed across multiple projects, development tools, or frequently-used services282* **User scope**: Personal utilities needed across multiple projects, development tools, or frequently used services

283 

284<Note>

285 **Where are MCP servers stored?**

286 

287 * **User and local scope**: `~/.claude.json` (in the `mcpServers` field or under project paths)

288 * **Project scope**: `.mcp.json` in your project root (checked into source control)

289 * **Managed**: `managed-mcp.json` in system directories (see [Managed MCP configuration](#managed-mcp-configuration))

290</Note>

263 291 

264### Scope hierarchy and precedence292### Scope hierarchy and precedence

265 293 

266MCP server configurations follow a clear precedence hierarchy. When servers with the same name exist at multiple scopes, the system resolves conflicts by prioritizing local-scoped servers first, followed by project-scoped servers, and finally user-scoped servers. This design ensures that personal configurations can override shared ones when needed.294MCP server configurations follow a clear precedence hierarchy. When servers with the same name exist at multiple scopes, the system resolves conflicts by prioritizing local-scoped servers first, followed by project-scoped servers, and finally user-scoped servers. This design ensures that personal configurations can override shared ones when needed.

267 295 

296If a server is configured both locally and through a [claude.ai connector](#use-mcp-servers-from-claude-ai), the local configuration takes precedence and the connector entry is skipped.

297 

268### Environment variable expansion in `.mcp.json`298### Environment variable expansion in `.mcp.json`

269 299 

270Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys.300Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys.


306{/* ### Example: Automate browser testing with Playwright336{/* ### Example: Automate browser testing with Playwright

307 337 

308 ```bash338 ```bash

309 # 1. Add the Playwright MCP server

310 claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest339 claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest

340 ```

311 341 

312 # 2. Write and run browser tests342 Then write and run browser tests:

313 > "Test if the login flow works with test@example.com"343 

314 > "Take a screenshot of the checkout page on mobile"344 ```text

315 > "Verify that the search feature returns results"345 Test if the login flow works with test@example.com

346 ```

347 ```text

348 Take a screenshot of the checkout page on mobile

349 ```

350 ```text

351 Verify that the search feature returns results

316 ``` */}352 ``` */}

317 353 

318### Example: Monitor errors with Sentry354### Example: Monitor errors with Sentry

319 355 

320```bash theme={null}356```bash theme={null}

321# 1. Add the Sentry MCP server

322claude mcp add --transport http sentry https://mcp.sentry.dev/mcp357claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

358```

323 359 

324# 2. Use /mcp to authenticate with your Sentry account360Authenticate with your Sentry account:

325> /mcp

326 361 

327# 3. Debug production issues362```text theme={null}

328> "What are the most common errors in the last 24 hours?"363/mcp

329> "Show me the stack trace for error ID abc123"364```

330> "Which deployment introduced these new errors?"365 

366Then debug production issues:

367 

368```text theme={null}

369What are the most common errors in the last 24 hours?

370```

371 

372```text theme={null}

373Show me the stack trace for error ID abc123

374```

375 

376```text theme={null}

377Which deployment introduced these new errors?

331```378```

332 379 

333### Example: Connect to GitHub for code reviews380### Example: Connect to GitHub for code reviews

334 381 

335```bash theme={null}382```bash theme={null}

336# 1. Add the GitHub MCP server

337claude mcp add --transport http github https://api.githubcopilot.com/mcp/383claude mcp add --transport http github https://api.githubcopilot.com/mcp/

384```

385 

386Authenticate if needed by selecting "Authenticate" for GitHub:

387 

388```text theme={null}

389/mcp

390```

338 391 

339# 2. In Claude Code, authenticate if needed392Then work with GitHub:

340> /mcp

341# Select "Authenticate" for GitHub

342 393 

343# 3. Now you can ask Claude to work with GitHub394```text theme={null}

344> "Review PR #456 and suggest improvements"395Review PR #456 and suggest improvements

345> "Create a new issue for the bug we just found"396```

346> "Show me all open PRs assigned to me"397 

398```text theme={null}

399Create a new issue for the bug we just found

400```

401 

402```text theme={null}

403Show me all open PRs assigned to me

347```404```

348 405 

349### Example: Query your PostgreSQL database406### Example: Query your PostgreSQL database

350 407 

351```bash theme={null}408```bash theme={null}

352# 1. Add the database server with your connection string

353claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \409claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \

354 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"410 --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"

411```

355 412 

356# 2. Query your database naturally413Then query your database naturally:

357> "What's our total revenue this month?"414 

358> "Show me the schema for the orders table"415```text theme={null}

359> "Find customers who haven't made a purchase in 90 days"416What's our total revenue this month?

417```

418 

419```text theme={null}

420Show me the schema for the orders table

421```

422 

423```text theme={null}

424Find customers who haven't made a purchase in 90 days

360```425```

361 426 

362## Authenticate with remote MCP servers427## Authenticate with remote MCP servers


375 <Step title="Use the /mcp command within Claude Code">440 <Step title="Use the /mcp command within Claude Code">

376 In Claude code, use the command:441 In Claude code, use the command:

377 442 

378 ```443 ```text theme={null}

379 > /mcp444 /mcp

380 ```445 ```

381 446 

382 Then follow the steps in your browser to login.447 Then follow the steps in your browser to login.


388 453 

389 * Authentication tokens are stored securely and refreshed automatically454 * Authentication tokens are stored securely and refreshed automatically

390 * Use "Clear authentication" in the `/mcp` menu to revoke access455 * Use "Clear authentication" in the `/mcp` menu to revoke access

391 * If your browser doesn't open automatically, copy the provided URL456 * If your browser doesn't open automatically, copy the provided URL and open it manually

457 * If the browser redirect fails with a connection error after authenticating, paste the full callback URL from your browser's address bar into the URL prompt that appears in Claude Code

392 * OAuth authentication works with HTTP servers458 * OAuth authentication works with HTTP servers

393</Tip>459</Tip>

394 460 

461### Use a fixed OAuth callback port

462 

463Some MCP servers require a specific redirect URI registered in advance. By default, Claude Code picks a random available port for the OAuth callback. Use `--callback-port` to fix the port so it matches a pre-registered redirect URI of the form `http://localhost:PORT/callback`.

464 

465You can use `--callback-port` on its own (with dynamic client registration) or together with `--client-id` (with pre-configured credentials).

466 

467```bash theme={null}

468# Fixed callback port with dynamic client registration

469claude mcp add --transport http \

470 --callback-port 8080 \

471 my-server https://mcp.example.com/mcp

472```

473 

474### Use pre-configured OAuth credentials

475 

476Some MCP servers don't support automatic OAuth setup via Dynamic Client Registration. If you see an error like "Incompatible auth server: does not support dynamic client registration," the server requires pre-configured credentials. Claude Code also supports servers that use a Client ID Metadata Document (CIMD) instead of Dynamic Client Registration, and discovers these automatically. If automatic discovery fails, register an OAuth app through the server's developer portal first, then provide the credentials when adding the server.

477 

478<Steps>

479 <Step title="Register an OAuth app with the server">

480 Create an app through the server's developer portal and note your client ID and client secret.

481 

482 Many servers also require a redirect URI. If so, choose a port and register a redirect URI in the format `http://localhost:PORT/callback`. Use that same port with `--callback-port` in the next step.

483 </Step>

484 

485 <Step title="Add the server with your credentials">

486 Choose one of the following methods. The port used for `--callback-port` can be any available port. It just needs to match the redirect URI you registered in the previous step.

487 

488 <Tabs>

489 <Tab title="claude mcp add">

490 Use `--client-id` to pass your app's client ID. The `--client-secret` flag prompts for the secret with masked input:

491 

492 ```bash theme={null}

493 claude mcp add --transport http \

494 --client-id your-client-id --client-secret --callback-port 8080 \

495 my-server https://mcp.example.com/mcp

496 ```

497 </Tab>

498 

499 <Tab title="claude mcp add-json">

500 Include the `oauth` object in the JSON config and pass `--client-secret` as a separate flag:

501 

502 ```bash theme={null}

503 claude mcp add-json my-server \

504 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \

505 --client-secret

506 ```

507 </Tab>

508 

509 <Tab title="claude mcp add-json (callback port only)">

510 Use `--callback-port` without a client ID to fix the port while using dynamic client registration:

511 

512 ```bash theme={null}

513 claude mcp add-json my-server \

514 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"callbackPort":8080}}'

515 ```

516 </Tab>

517 

518 <Tab title="CI / env var">

519 Set the secret via environment variable to skip the interactive prompt:

520 

521 ```bash theme={null}

522 MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \

523 --client-id your-client-id --client-secret --callback-port 8080 \

524 my-server https://mcp.example.com/mcp

525 ```

526 </Tab>

527 </Tabs>

528 </Step>

529 

530 <Step title="Authenticate in Claude Code">

531 Run `/mcp` in Claude Code and follow the browser login flow.

532 </Step>

533</Steps>

534 

535<Tip>

536 Tips:

537 

538 * The client secret is stored securely in your system keychain (macOS) or a credentials file, not in your config

539 * If the server uses a public OAuth client with no secret, use only `--client-id` without `--client-secret`

540 * `--callback-port` can be used with or without `--client-id`

541 * These flags only apply to HTTP and SSE transports. They have no effect on stdio servers

542 * Use `claude mcp get <name>` to verify that OAuth credentials are configured for a server

543</Tip>

544 

545### Override OAuth metadata discovery

546 

547If 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`.

548 

549Set `authServerMetadataUrl` in the `oauth` object of your server's config in `.mcp.json`:

550 

551```json theme={null}

552{

553 "mcpServers": {

554 "my-server": {

555 "type": "http",

556 "url": "https://mcp.example.com/mcp",

557 "oauth": {

558 "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration"

559 }

560 }

561 }

562}

563```

564 

565The URL must use `https://`. This option requires Claude Code v2.1.64 or later.

566 

567### Use dynamic headers for custom authentication

568 

569If your MCP server uses an authentication scheme other than OAuth (such as Kerberos, short-lived tokens, or an internal SSO), use `headersHelper` to generate request headers at connection time. Claude Code runs the command and merges its output into the connection headers.

570 

571```json theme={null}

572{

573 "mcpServers": {

574 "internal-api": {

575 "type": "http",

576 "url": "https://mcp.internal.example.com",

577 "headersHelper": "/opt/bin/get-mcp-auth-headers.sh"

578 }

579 }

580}

581```

582 

583The command can also be inline:

584 

585```json theme={null}

586{

587 "mcpServers": {

588 "internal-api": {

589 "type": "http",

590 "url": "https://mcp.internal.example.com",

591 "headersHelper": "echo '{\"Authorization\": \"Bearer '\"$(get-token)\"'\"}'"

592 }

593 }

594}

595```

596 

597**Requirements:**

598 

599* The command must write a JSON object of string key-value pairs to stdout

600* The command runs in a shell with a 10-second timeout

601* Dynamic headers override any static `headers` with the same name

602 

603The helper runs fresh on each connection (at session start and on reconnect). There is no caching, so your script is responsible for any token reuse.

604 

605Claude Code sets these environment variables when executing the helper:

606 

607| Variable | Value |

608| :---------------------------- | :------------------------- |

609| `CLAUDE_CODE_MCP_SERVER_NAME` | the name of the MCP server |

610| `CLAUDE_CODE_MCP_SERVER_URL` | the URL of the MCP server |

611 

612Use these to write a single helper script that serves multiple MCP servers.

613 

614<Note>

615 `headersHelper` executes arbitrary shell commands. When defined at project or local scope, it only runs after you accept the workspace trust dialog.

616</Note>

617 

395## Add MCP servers from JSON configuration618## Add MCP servers from JSON configuration

396 619 

397If you have a JSON configuration for an MCP server, you can add it directly:620If you have a JSON configuration for an MCP server, you can add it directly:


407 630 

408 # Example: Adding a stdio server with JSON configuration631 # Example: Adding a stdio server with JSON configuration

409 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'632 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'

633 

634 # Example: Adding an HTTP server with pre-configured OAuth credentials

635 claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret

410 ```636 ```

411 </Step>637 </Step>

412 638 


455 * It reads the Claude Desktop configuration file from its standard location on those platforms681 * It reads the Claude Desktop configuration file from its standard location on those platforms

456 * Use the `--scope user` flag to add servers to your user configuration682 * Use the `--scope user` flag to add servers to your user configuration

457 * Imported servers will have the same names as in Claude Desktop683 * Imported servers will have the same names as in Claude Desktop

458 * If servers with the same names already exist, they will get a numerical suffix (e.g., `server_1`)684 * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)

459</Tip>685</Tip>

460 686 

687## Use MCP servers from Claude.ai

688 

689If you've logged into Claude Code with a [Claude.ai](https://claude.ai) account, MCP servers you've added in Claude.ai are automatically available in Claude Code:

690 

691<Steps>

692 <Step title="Configure MCP servers in Claude.ai">

693 Add servers at [claude.ai/settings/connectors](https://claude.ai/settings/connectors). On Team and Enterprise plans, only admins can add servers.

694 </Step>

695 

696 <Step title="Authenticate the MCP server">

697 Complete any required authentication steps in Claude.ai.

698 </Step>

699 

700 <Step title="View and manage servers in Claude Code">

701 In Claude Code, use the command:

702 

703 ```text theme={null}

704 /mcp

705 ```

706 

707 Claude.ai servers appear in the list with indicators showing they come from Claude.ai.

708 </Step>

709</Steps>

710 

711To disable claude.ai MCP servers in Claude Code, set the `ENABLE_CLAUDEAI_MCP_SERVERS` environment variable to `false`:

712 

713```bash theme={null}

714ENABLE_CLAUDEAI_MCP_SERVERS=false claude

715```

716 

461## Use Claude Code as an MCP server717## Use Claude Code as an MCP server

462 718 

463You can use Claude Code itself as an MCP server that other applications can connect to:719You can use Claude Code itself as an MCP server that other applications can connect to:


482}738}

483```739```

484 740 

741<Warning>

742 **Configuring the executable path**: The `command` field must reference the Claude Code executable. If the `claude` command is not in your system's PATH, you'll need to specify the full path to the executable.

743 

744 To find the full path:

745 

746 ```bash theme={null}

747 which claude

748 ```

749 

750 Then use the full path in your configuration:

751 

752 ```json theme={null}

753 {

754 "mcpServers": {

755 "claude-code": {

756 "type": "stdio",

757 "command": "/full/path/to/claude",

758 "args": ["mcp", "serve"],

759 "env": {}

760 }

761 }

762 }

763 ```

764 

765 Without the correct executable path, you'll encounter errors like `spawn claude ENOENT`.

766</Warning>

767 

485<Tip>768<Tip>

486 Tips:769 Tips:

487 770 

488 * The server provides access to Claude's tools like View, Edit, LS, etc.771 * The server provides access to Claude's tools like View, Edit, LS, etc.

489 * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more.772 * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more.

490 * Note that this MCP server is simply exposing Claude Code's tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls.773 * Note that this MCP server is only exposing Claude Code's tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls.

491</Tip>774</Tip>

492 775 

493## MCP output limits and warnings776## MCP output limits and warnings


501To increase the limit for tools that produce large outputs:784To increase the limit for tools that produce large outputs:

502 785 

503```bash theme={null}786```bash theme={null}

504# Set a higher limit for MCP tool outputs

505export MAX_MCP_OUTPUT_TOKENS=50000787export MAX_MCP_OUTPUT_TOKENS=50000

506claude788claude

507```789```


512* Generate detailed reports or documentation794* Generate detailed reports or documentation

513* Process extensive log files or debugging information795* Process extensive log files or debugging information

514 796 

797### Override result size per tool

798 

799If you're building an MCP server, you can allow individual tools to return results larger than the default limit by setting `_meta["anthropic/maxResultSizeChars"]` in the tool's `tools/list` response entry. Claude Code uses this value as the maximum result size for that tool, up to a hard ceiling of 500,000 characters.

800 

801This is useful for tools that return inherently large but necessary outputs, such as database schemas or full file trees. Without the annotation, results that exceed the default limit are persisted to disk and replaced with a file reference in the conversation.

802 

803```json theme={null}

804{

805 "name": "get_schema",

806 "description": "Returns the full database schema",

807 "_meta": {

808 "anthropic/maxResultSizeChars": 500000

809 }

810}

811```

812 

515<Warning>813<Warning>

516 If you frequently encounter output warnings with specific MCP servers, consider increasing the limit or configuring the server to paginate or filter its responses.814 If you frequently encounter output warnings with specific MCP servers you don't control, consider increasing the `MAX_MCP_OUTPUT_TOKENS` limit or asking the server author to add the `anthropic/maxResultSizeChars` annotation.

517</Warning>815</Warning>

518 816 

817## Respond to MCP elicitation requests

818 

819MCP servers can request structured input from you mid-task using elicitation. When a server needs information it can't get on its own, Claude Code displays an interactive dialog and passes your response back to the server. No configuration is required on your side: elicitation dialogs appear automatically when a server requests them.

820 

821Servers can request input in two ways:

822 

823* **Form mode**: Claude Code shows a dialog with form fields defined by the server (for example, a username and password prompt). Fill in the fields and submit.

824* **URL mode**: Claude Code opens a browser URL for authentication or approval. Complete the flow in the browser, then confirm in the CLI.

825 

826To auto-respond to elicitation requests without showing a dialog, use the [`Elicitation` hook](/en/hooks#elicitation).

827 

828If you're building an MCP server that uses elicitation, see the [MCP elicitation specification](https://modelcontextprotocol.io/docs/learn/client-concepts#elicitation) for protocol details and schema examples.

829 

519## Use MCP resources830## Use MCP resources

520 831 

521MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files.832MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files.


530 <Step title="Reference a specific resource">841 <Step title="Reference a specific resource">

531 Use the format `@server:protocol://resource/path` to reference a resource:842 Use the format `@server:protocol://resource/path` to reference a resource:

532 843 

533 ```844 ```text theme={null}

534 > Can you analyze @github:issue://123 and suggest a fix?845 Can you analyze @github:issue://123 and suggest a fix?

535 ```846 ```

536 847 

537 ```848 ```text theme={null}

538 > Please review the API documentation at @docs:file://api/authentication849 Please review the API documentation at @docs:file://api/authentication

539 ```850 ```

540 </Step>851 </Step>

541 852 

542 <Step title="Multiple resource references">853 <Step title="Multiple resource references">

543 You can reference multiple resources in a single prompt:854 You can reference multiple resources in a single prompt:

544 855 

545 ```856 ```text theme={null}

546 > Compare @postgres:schema://users with @docs:file://database/user-model857 Compare @postgres:schema://users with @docs:file://database/user-model

547 ```858 ```

548 </Step>859 </Step>

549</Steps>860</Steps>


557 * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.)868 * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.)

558</Tip>869</Tip>

559 870 

560## Use MCP prompts as slash commands871## Scale with MCP Tool Search

872 

873Tool search keeps MCP context usage low by deferring tool definitions until Claude needs them. Only tool names load at session start, so adding more MCP servers has minimal impact on your context window.

874 

875### How it works

876 

877Tool search is enabled by default. MCP tools are deferred rather than loaded into context upfront, and Claude uses a search tool to discover relevant ones when a task needs them. Only the tools Claude actually uses enter context. From your perspective, MCP tools work exactly as before.

878 

879If you prefer threshold-based loading, set `ENABLE_TOOL_SEARCH=auto` to load schemas upfront when they fit within 10% of the context window and defer only the overflow. See [Configure tool search](#configure-tool-search) for all options.

880 

881### For MCP server authors

561 882 

562MCP servers can expose prompts that become available as slash commands in Claude Code.883If you're building an MCP server, the server instructions field becomes more useful with Tool Search enabled. Server instructions help Claude understand when to search for your tools, similar to how [skills](/en/skills) work.

884 

885Add clear, descriptive server instructions that explain:

886 

887* What category of tasks your tools handle

888* When Claude should search for your tools

889* Key capabilities your server provides

890 

891Claude Code truncates tool descriptions and server instructions at 2KB each. Keep them concise to avoid truncation, and put critical details near the start.

892 

893### Configure tool search

894 

895Tool 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.

896 

897Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:

898 

899| Value | Behavior |

900| :--------- | :----------------------------------------------------------------------------------------------------------------------------- |

901| (unset) | All MCP tools deferred and loaded on demand. Falls back to loading upfront when `ANTHROPIC_BASE_URL` is a non-first-party host |

902| `true` | All MCP tools deferred, including for non-first-party `ANTHROPIC_BASE_URL` |

903| `auto` | Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise |

904| `auto:<N>` | Threshold mode with a custom percentage, where `<N>` is 0-100 (e.g., `auto:5` for 5%) |

905| `false` | All MCP tools loaded upfront, no deferral |

906 

907```bash theme={null}

908# Use a custom 5% threshold

909ENABLE_TOOL_SEARCH=auto:5 claude

910 

911# Disable tool search entirely

912ENABLE_TOOL_SEARCH=false claude

913```

914 

915Or set the value in your [settings.json `env` field](/en/settings#available-settings).

916 

917You can also disable the `ToolSearch` tool specifically:

918 

919```json theme={null}

920{

921 "permissions": {

922 "deny": ["ToolSearch"]

923 }

924}

925```

926 

927## Use MCP prompts as commands

928 

929MCP servers can expose prompts that become available as commands in Claude Code.

563 930 

564### Execute MCP prompts931### Execute MCP prompts

565 932 


569 </Step>936 </Step>

570 937 

571 <Step title="Execute a prompt without arguments">938 <Step title="Execute a prompt without arguments">

572 ```939 ```text theme={null}

573 > /mcp__github__list_prs940 /mcp__github__list_prs

574 ```941 ```

575 </Step>942 </Step>

576 943 

577 <Step title="Execute a prompt with arguments">944 <Step title="Execute a prompt with arguments">

578 Many prompts accept arguments. Pass them space-separated after the command:945 Many prompts accept arguments. Pass them space-separated after the command:

579 946 

580 ```947 ```text theme={null}

581 > /mcp__github__pr_review 456948 /mcp__github__pr_review 456

582 ```949 ```

583 950 

584 ```951 ```text theme={null}

585 > /mcp__jira__create_issue "Bug in login flow" high952 /mcp__jira__create_issue "Bug in login flow" high

586 ```953 ```

587 </Step>954 </Step>

588</Steps>955</Steps>


596 * Server and prompt names are normalized (spaces become underscores)963 * Server and prompt names are normalized (spaces become underscores)

597</Tip>964</Tip>

598 965 

599## Enterprise MCP configuration966## Managed MCP configuration

967 

968For organizations that need centralized control over MCP servers, Claude Code supports two configuration options:

969 

9701. **Exclusive control with `managed-mcp.json`**: Deploy a fixed set of MCP servers that users cannot modify or extend

9712. **Policy-based control with allowlists/denylists**: Allow users to add their own servers, but restrict which ones are permitted

600 972 

601For organizations that need centralized control over MCP servers, Claude Code supports enterprise-managed MCP configurations. This allows IT administrators to:973These options allow IT administrators to:

602 974 

603* **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization975* **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization

604* **Prevent unauthorized MCP servers**: Optionally restrict users from adding their own MCP servers976* **Prevent unauthorized MCP servers**: Restrict users from adding unapproved MCP servers

605* **Disable MCP entirely**: Remove MCP functionality completely if needed977* **Disable MCP entirely**: Remove MCP functionality completely if needed

606 978 

607### Setting up enterprise MCP configuration979### Option 1: Exclusive control with managed-mcp.json

608 980 

609System administrators can deploy an enterprise MCP configuration file alongside the managed settings file:981When you deploy a `managed-mcp.json` file, it takes **exclusive control** over all MCP servers. Users cannot add, modify, or use any MCP servers other than those defined in this file. This is the simplest approach for organizations that want complete control.

610 982 

611* **macOS**: `/Library/Application Support/ClaudeCode/managed-mcp.json`983System administrators deploy the configuration file to a system-wide directory:

612* **Windows**: `C:\ProgramData\ClaudeCode\managed-mcp.json`984 

613* **Linux**: `/etc/claude-code/managed-mcp.json`985* macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`

986* Linux and WSL: `/etc/claude-code/managed-mcp.json`

987* Windows: `C:\Program Files\ClaudeCode\managed-mcp.json`

988 

989<Note>

990 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.

991</Note>

614 992 

615The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file:993The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file:

616 994 


637}1015}

638```1016```

639 1017 

640### Restricting MCP servers with allowlists and denylists1018### Option 2: Policy-based control with allowlists and denylists

1019 

1020Instead of taking exclusive control, administrators can allow users to configure their own MCP servers while enforcing restrictions on which servers are permitted. This approach uses `allowedMcpServers` and `deniedMcpServers` in the [managed settings file](/en/settings#settings-files).

1021 

1022<Note>

1023 **Choosing between options**: Use Option 1 (`managed-mcp.json`) when you want to deploy a fixed set of servers with no user customization. Use Option 2 (allowlists/denylists) when you want to allow users to add their own servers within policy constraints.

1024</Note>

1025 

1026#### Restriction options

1027 

1028Each entry in the allowlist or denylist can restrict servers in three ways:

1029 

10301. **By server name** (`serverName`): Matches the configured name of the server

10312. **By command** (`serverCommand`): Matches the exact command and arguments used to start stdio servers

10323. **By URL pattern** (`serverUrl`): Matches remote server URLs with wildcard support

641 1033 

642In addition to providing enterprise-managed servers, administrators can control which MCP servers users are allowed to configure using `allowedMcpServers` and `deniedMcpServers` in the `managed-settings.json` file:1034**Important**: Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`.

643 1035 

644* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`1036#### Example configuration

645* **Windows**: `C:\ProgramData\ClaudeCode\managed-settings.json`

646* **Linux**: `/etc/claude-code/managed-settings.json`

647 1037 

648```json theme={null}1038```json theme={null}

649{1039{

650 "allowedMcpServers": [1040 "allowedMcpServers": [

1041 // Allow by server name

651 { "serverName": "github" },1042 { "serverName": "github" },

652 { "serverName": "sentry" },1043 { "serverName": "sentry" },

653 { "serverName": "company-internal" }1044 

1045 // Allow by exact command (for stdio servers)

1046 { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },

1047 { "serverCommand": ["python", "/usr/local/bin/approved-server.py"] },

1048 

1049 // Allow by URL pattern (for remote servers)

1050 { "serverUrl": "https://mcp.company.com/*" },

1051 { "serverUrl": "https://*.internal.corp/*" }

654 ],1052 ],

655 "deniedMcpServers": [1053 "deniedMcpServers": [

656 { "serverName": "filesystem" }1054 // Block by server name

1055 { "serverName": "dangerous-server" },

1056 

1057 // Block by exact command (for stdio servers)

1058 { "serverCommand": ["npx", "-y", "unapproved-package"] },

1059 

1060 // Block by URL pattern (for remote servers)

1061 { "serverUrl": "https://*.untrusted.com/*" }

657 ]1062 ]

658}1063}

659```1064```

660 1065 

661**Allowlist behavior (`allowedMcpServers`)**:1066#### How command-based restrictions work

1067 

1068**Exact matching**:

1069 

1070* Command arrays must match **exactly** - both the command and all arguments in the correct order

1071* Example: `["npx", "-y", "server"]` will NOT match `["npx", "server"]` or `["npx", "-y", "server", "--flag"]`

1072 

1073**Stdio server behavior**:

1074 

1075* When the allowlist contains **any** `serverCommand` entries, stdio servers **must** match one of those commands

1076* Stdio servers cannot pass by name alone when command restrictions are present

1077* This ensures administrators can enforce which commands are allowed to run

1078 

1079**Non-stdio server behavior**:

1080 

1081* Remote servers (HTTP, SSE, WebSocket) use URL-based matching when `serverUrl` entries exist in the allowlist

1082* If no URL entries exist, remote servers fall back to name-based matching

1083* Command restrictions do not apply to remote servers

1084 

1085#### How URL-based restrictions work

1086 

1087URL patterns support wildcards using `*` to match any sequence of characters. This is useful for allowing entire domains or subdomains.

1088 

1089**Wildcard examples**:

1090 

1091* `https://mcp.company.com/*` - Allow all paths on a specific domain

1092* `https://*.example.com/*` - Allow any subdomain of example.com

1093* `http://localhost:*/*` - Allow any port on localhost

1094 

1095**Remote server behavior**:

1096 

1097* When the allowlist contains **any** `serverUrl` entries, remote servers **must** match one of those URL patterns

1098* Remote servers cannot pass by name alone when URL restrictions are present

1099* This ensures administrators can enforce which remote endpoints are allowed

1100 

1101<Accordion title="Example: URL-only allowlist">

1102 ```json theme={null}

1103 {

1104 "allowedMcpServers": [

1105 { "serverUrl": "https://mcp.company.com/*" },

1106 { "serverUrl": "https://*.internal.corp/*" }

1107 ]

1108 }

1109 ```

1110 

1111 **Result**:

1112 

1113 * HTTP server at `https://mcp.company.com/api`: ✅ Allowed (matches URL pattern)

1114 * HTTP server at `https://api.internal.corp/mcp`: ✅ Allowed (matches wildcard subdomain)

1115 * HTTP server at `https://external.com/mcp`: ❌ Blocked (doesn't match any URL pattern)

1116 * Stdio server with any command: ❌ Blocked (no name or command entries to match)

1117</Accordion>

1118 

1119<Accordion title="Example: Command-only allowlist">

1120 ```json theme={null}

1121 {

1122 "allowedMcpServers": [

1123 { "serverCommand": ["npx", "-y", "approved-package"] }

1124 ]

1125 }

1126 ```

1127 

1128 **Result**:

1129 

1130 * Stdio server with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command)

1131 * Stdio server with `["node", "server.js"]`: ❌ Blocked (doesn't match command)

1132 * HTTP server named "my-api": ❌ Blocked (no name entries to match)

1133</Accordion>

1134 

1135<Accordion title="Example: Mixed name and command allowlist">

1136 ```json theme={null}

1137 {

1138 "allowedMcpServers": [

1139 { "serverName": "github" },

1140 { "serverCommand": ["npx", "-y", "approved-package"] }

1141 ]

1142 }

1143 ```

1144 

1145 **Result**:

1146 

1147 * Stdio server named "local-tool" with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command)

1148 * Stdio server named "local-tool" with `["node", "server.js"]`: ❌ Blocked (command entries exist but doesn't match)

1149 * Stdio server named "github" with `["node", "server.js"]`: ❌ Blocked (stdio servers must match commands when command entries exist)

1150 * HTTP server named "github": ✅ Allowed (matches name)

1151 * HTTP server named "other-api": ❌ Blocked (name doesn't match)

1152</Accordion>

1153 

1154<Accordion title="Example: Name-only allowlist">

1155 ```json theme={null}

1156 {

1157 "allowedMcpServers": [

1158 { "serverName": "github" },

1159 { "serverName": "internal-tool" }

1160 ]

1161 }

1162 ```

1163 

1164 **Result**:

1165 

1166 * Stdio server named "github" with any command: ✅ Allowed (no command restrictions)

1167 * Stdio server named "internal-tool" with any command: ✅ Allowed (no command restrictions)

1168 * HTTP server named "github": ✅ Allowed (matches name)

1169 * Any server named "other": ❌ Blocked (name doesn't match)

1170</Accordion>

1171 

1172#### Allowlist behavior (`allowedMcpServers`)

662 1173 

663* `undefined` (default): No restrictions - users can configure any MCP server1174* `undefined` (default): No restrictions - users can configure any MCP server

664* Empty array `[]`: Complete lockdown - users cannot configure any MCP servers1175* Empty array `[]`: Complete lockdown - users cannot configure any MCP servers

665* List of server names: Users can only configure the specified servers1176* List of entries: Users can only configure servers that match by name, command, or URL pattern

666 1177 

667**Denylist behavior (`deniedMcpServers`)**:1178#### Denylist behavior (`deniedMcpServers`)

668 1179 

669* `undefined` (default): No servers are blocked1180* `undefined` (default): No servers are blocked

670* Empty array `[]`: No servers are blocked1181* Empty array `[]`: No servers are blocked

671* List of server names: Specified servers are explicitly blocked across all scopes1182* List of entries: Specified servers are explicitly blocked across all scopes

672 1183 

673**Important notes**:1184#### Important notes

674 1185 

675* These restrictions apply to all scopes: user, project, local, and even enterprise servers from `managed-mcp.json`1186* **Option 1 and Option 2 can be combined**: If `managed-mcp.json` exists, it has exclusive control and users cannot add servers. Allowlists/denylists still apply to the managed servers themselves.

676* **Denylist takes absolute precedence**: If a server appears in both lists, it will be blocked1187* **Denylist takes absolute precedence**: If a server matches a denylist entry (by name, command, or URL), it will be blocked even if it's on the allowlist

1188* Name-based, command-based, and URL-based restrictions work together: a server passes if it matches **either** a name entry, a command entry, or a URL pattern (unless blocked by denylist)

677 1189 

678<Note>1190<Note>

679 **Enterprise configuration precedence**: The enterprise MCP configuration has the highest precedence and cannot be overridden by user, local, or project configurations when `useEnterpriseMcpConfigOnly` is enabled.1191 **When using `managed-mcp.json`**: Users cannot add MCP servers through `claude mcp add` or configuration files. The `allowedMcpServers` and `deniedMcpServers` settings still apply to filter which managed servers are actually loaded.

680</Note>1192</Note>

memory.md +343 −51

Details

1# Manage Claude's memory1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.5# How Claude remembers your project

4 6 

5Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow.7> Give Claude persistent instructions with CLAUDE.md files, and let Claude accumulate learnings automatically with auto memory.

6 8 

7## Determine memory type9Each Claude Code session begins with a fresh context window. Two mechanisms carry knowledge across sessions:

8 10 

9Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose:11* **CLAUDE.md files**: instructions you write to give Claude persistent context

12* **Auto memory**: notes Claude writes itself based on your corrections and preferences

10 13 

11| Memory Type | Location | Purpose | Use Case Examples | Shared With |14This page covers how to:

12| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |

13| **Enterprise policy** | macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />Linux: `/etc/claude-code/CLAUDE.md`<br />Windows: `C:\ProgramData\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |

14| **Project memory** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |

15| **User memory** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |

16| **Project memory (local)** | `./CLAUDE.local.md` | Personal project-specific preferences | *(Deprecated, see below)* Your sandbox URLs, preferred test data | Just you (current project) |

17 15 

18All memory files are automatically loaded into Claude Code's context when launched. Files higher in the hierarchy take precedence and are loaded first, providing a foundation that more specific memories build upon.16* [Write and organize CLAUDE.md files](#claude-md-files)

17* [Scope rules to specific file types](#organize-rules-with-claude/rules/) with `.claude/rules/`

18* [Configure auto memory](#auto-memory) so Claude takes notes automatically

19* [Troubleshoot](#troubleshoot-memory-issues) when instructions aren't being followed

19 20 

20## CLAUDE.md imports21## CLAUDE.md vs auto memory

21 22 

22CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files:23Claude Code has two complementary memory systems. Both are loaded at the start of every conversation. Claude treats them as context, not enforced configuration. The more specific and concise your instructions, the more consistently Claude follows them.

23 24 

24```25| | CLAUDE.md files | Auto memory |

26| :------------------- | :------------------------------------------------ | :--------------------------------------------------------------- |

27| **Who writes it** | You | Claude |

28| **What it contains** | Instructions and rules | Learnings and patterns |

29| **Scope** | Project, user, or org | Per working tree |

30| **Loaded into** | Every session | Every session (first 200 lines or 25KB) |

31| **Use for** | Coding standards, workflows, project architecture | Build commands, debugging insights, preferences Claude discovers |

32 

33Use CLAUDE.md files when you want to guide Claude's behavior. Auto memory lets Claude learn from your corrections without manual effort.

34 

35Subagents can also maintain their own auto memory. See [subagent configuration](/en/sub-agents#enable-persistent-memory) for details.

36 

37## CLAUDE.md files

38 

39CLAUDE.md files are markdown files that give Claude persistent instructions for a project, your personal workflow, or your entire organization. You write these files in plain text; Claude reads them at the start of every session.

40 

41### Choose where to put CLAUDE.md files

42 

43CLAUDE.md files can live in several locations, each with a different scope. More specific locations take precedence over broader ones.

44 

45| Scope | Location | Purpose | Use case examples | Shared with |

46| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |

47| **Managed policy** | • macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />• Linux and WSL: `/etc/claude-code/CLAUDE.md`<br />• Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |

48| **Project instructions** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |

49| **User instructions** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |

50| **Local instructions** | `./CLAUDE.local.md` | Personal project-specific preferences; add to `.gitignore` | Your sandbox URLs, preferred test data | Just you (current project) |

51 

52CLAUDE.md and CLAUDE.local.md files in the directory hierarchy above the working directory are loaded in full at launch. Files in subdirectories load on demand when Claude reads files in those directories. See [How CLAUDE.md files load](#how-claude-md-files-load) for the full resolution order.

53 

54For large projects, you can break instructions into topic-specific files using [project rules](#organize-rules-with-claude/rules/). Rules let you scope instructions to specific file types or subdirectories.

55 

56### Set up a project CLAUDE.md

57 

58A project CLAUDE.md can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`. Create this file and add instructions that apply to anyone working on the project: build and test commands, coding standards, architectural decisions, naming conventions, and common workflows. These instructions are shared with your team through version control, so focus on project-level standards rather than personal preferences.

59 

60<Tip>

61 Run `/init` to generate a starting CLAUDE.md automatically. Claude analyzes your codebase and creates a file with build commands, test instructions, and project conventions it discovers. If a CLAUDE.md already exists, `/init` suggests improvements rather than overwriting it. Refine from there with instructions Claude wouldn't discover on its own.

62 

63 Set `CLAUDE_CODE_NEW_INIT=1` to enable an interactive multi-phase flow. `/init` asks which artifacts to set up: CLAUDE.md files, skills, and hooks. It then explores your codebase with a subagent, fills in gaps via follow-up questions, and presents a reviewable proposal before writing any files.

64</Tip>

65 

66### Write effective instructions

67 

68CLAUDE.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.

69 

70**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.

71 

72**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.

73 

74**Specificity**: write instructions that are concrete enough to verify. For example:

75 

76* "Use 2-space indentation" instead of "Format code properly"

77* "Run `npm test` before committing" instead of "Test your changes"

78* "API handlers live in `src/api/handlers/`" instead of "Keep files organized"

79 

80**Consistency**: if two rules contradict each other, Claude may pick one arbitrarily. Review your CLAUDE.md files, nested CLAUDE.md files in subdirectories, and [`.claude/rules/`](#organize-rules-with-claude/rules/) periodically to remove outdated or conflicting instructions. In monorepos, use [`claudeMdExcludes`](#exclude-specific-claude-md-files) to skip CLAUDE.md files from other teams that aren't relevant to your work.

81 

82### Import additional files

83 

84CLAUDE.md files can import additional files using `@path/to/import` syntax. Imported files are expanded and loaded into context at launch alongside the CLAUDE.md that references them.

85 

86Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. Imported files can recursively import other files, with a maximum depth of five hops.

87 

88To pull in a README, package.json, and a workflow guide, reference them with `@` syntax anywhere in your CLAUDE.md:

89 

90```text theme={null}

25See @README for project overview and @package.json for available npm commands for this project.91See @README for project overview and @package.json for available npm commands for this project.

26 92 

27# Additional Instructions93# Additional Instructions

28- git workflow @docs/git-instructions.md94- git workflow @docs/git-instructions.md

29```95```

30 96 

31Both relative and absolute paths are allowed. In particular, importing files in user's home dir is a convenient way for your team members to provide individual instructions that are not checked into the repository. Previously CLAUDE.local.md served a similar purpose, but is now deprecated in favor of imports since they work better across multiple git worktrees.97For private per-project preferences that shouldn't be checked into version control, create a `CLAUDE.local.md` at the project root. It loads alongside `CLAUDE.md` and is treated the same way. Add `CLAUDE.local.md` to your `.gitignore` so it isn't committed; running `/init` and choosing the personal option does this for you.

32 98 

33```99If you work across multiple git worktrees of the same repository, a gitignored `CLAUDE.local.md` only exists in the worktree where you created it. To share personal instructions across worktrees, import a file from your home directory instead:

100 

101```text theme={null}

34# Individual Preferences102# Individual Preferences

35- @~/.claude/my-project-instructions.md103- @~/.claude/my-project-instructions.md

36```104```

37 105 

38To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.106<Warning>

107 The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the files. If you decline, the imports stay disabled and the dialog does not appear again.

108</Warning>

109 

110For a more structured approach to organizing instructions, see [`.claude/rules/`](#organize-rules-with-claude/rules/).

111 

112### AGENTS.md

113 

114Claude Code reads `CLAUDE.md`, not `AGENTS.md`. If your repository already uses `AGENTS.md` for other coding agents, create a `CLAUDE.md` that imports it so both tools read the same instructions without duplicating them. You can also add Claude-specific instructions below the import. Claude loads the imported file at session start, then appends the rest:

115 

116```markdown CLAUDE.md theme={null}

117@AGENTS.md

118 

119## Claude Code

120 

121Use plan mode for changes under `src/billing/`.

122```

123 

124### How CLAUDE.md files load

125 

126Claude 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.

127 

128All 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.

129 

130Claude 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.

131 

132If you work in a large monorepo where other teams' CLAUDE.md files get picked up, use [`claudeMdExcludes`](#exclude-specific-claude-md-files) to skip them.

133 

134Block-level HTML comments (`<!-- maintainer notes -->`) in CLAUDE.md files are stripped before the content is injected into Claude's context. Use them to leave notes for human maintainers without spending context tokens on them. Comments inside code blocks are preserved. When you open a CLAUDE.md file directly with the Read tool, comments remain visible.

135 

136#### Load from additional directories

137 

138The `--add-dir` flag gives Claude access to additional directories outside your main working directory. By default, CLAUDE.md files from these directories are not loaded.

139 

140To also load CLAUDE.md files from additional directories, including `CLAUDE.md`, `.claude/CLAUDE.md`, and `.claude/rules/*.md`, set the `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable:

141 

142```bash theme={null}

143CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config

144```

145 

146`CLAUDE.local.md` files in additional directories are not loaded.

147 

148### Organize rules with `.claude/rules/`

149 

150For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This keeps instructions modular and easier for teams to maintain. Rules can also be [scoped to specific file paths](#path-specific-rules), so they only load into context when Claude works with matching files, reducing noise and saving context space.

151 

152<Note>

153 Rules load into context every session or when matching files are opened. For task-specific instructions that don't need to be in context all the time, use [skills](/en/skills) instead, which only load when you invoke them or when Claude determines they're relevant to your prompt.

154</Note>

155 

156#### Set up rules

157 

158Place markdown files in your project's `.claude/rules/` directory. Each file should cover one topic, with a descriptive filename like `testing.md` or `api-design.md`. All `.md` files are discovered recursively, so you can organize rules into subdirectories like `frontend/` or `backend/`:

159 

160```text theme={null}

161your-project/

162├── .claude/

163│ ├── CLAUDE.md # Main project instructions

164│ └── rules/

165│ ├── code-style.md # Code style guidelines

166│ ├── testing.md # Testing conventions

167│ └── security.md # Security requirements

168```

169 

170Rules without [`paths` frontmatter](#path-specific-rules) are loaded at launch with the same priority as `.claude/CLAUDE.md`.

171 

172#### Path-specific rules

173 

174Rules can be scoped to specific files using YAML frontmatter with the `paths` field. These conditional rules only apply when Claude is working with files matching the specified patterns.

175 

176```markdown theme={null}

177---

178paths:

179 - "src/api/**/*.ts"

180---

39 181 

182# API Development Rules

183 

184- All API endpoints must include input validation

185- Use the standard error response format

186- Include OpenAPI documentation comments

40```187```

41This code span will not be treated as an import: `@anthropic-ai/claude-code`188 

189Rules without a `paths` field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use.

190 

191Use glob patterns in the `paths` field to match files by extension, directory, or any combination:

192 

193| Pattern | Matches |

194| ---------------------- | ---------------------------------------- |

195| `**/*.ts` | All TypeScript files in any directory |

196| `src/**/*` | All files under `src/` directory |

197| `*.md` | Markdown files in the project root |

198| `src/components/*.tsx` | React components in a specific directory |

199 

200You can specify multiple patterns and use brace expansion to match multiple extensions in one pattern:

201 

202```markdown theme={null}

203---

204paths:

205 - "src/**/*.{ts,tsx}"

206 - "lib/**/*.ts"

207 - "tests/**/*.test.ts"

208---

42```209```

43 210 

44Imported files can recursively import additional files, with a max-depth of 5 hops. You can see what memory files are loaded by running `/memory` command.211#### Share rules across projects with symlinks

45 212 

46## How Claude looks up memories213The `.claude/rules/` directory supports symlinks, so you can maintain a shared set of rules and link them into multiple projects. Symlinks are resolved and loaded normally, and circular symlinks are detected and handled gracefully.

47 214 

48Claude Code reads memories recursively: starting in the cwd, Claude Code recurses up to (but not including) the root directory */* and reads any CLAUDE.md or CLAUDE.local.md files it finds. This is especially convenient when working in large repositories where you run Claude Code in *foo/bar/*, and have memories in both *foo/CLAUDE.md* and *foo/bar/CLAUDE.md*.215This example links both a shared directory and an individual file:

49 216 

50Claude will also discover CLAUDE.md nested in subtrees under your current working directory. Instead of loading them at launch, they are only included when Claude reads files in those subtrees.217```bash theme={null}

218ln -s ~/shared-claude-rules .claude/rules/shared

219ln -s ~/company-standards/security.md .claude/rules/security.md

220```

51 221 

52## Quickly add memories with the `#` shortcut222#### User-level rules

53 223 

54The fastest way to add a memory is to start your input with the `#` character:224Personal rules in `~/.claude/rules/` apply to every project on your machine. Use them for preferences that aren't project-specific:

55 225 

226```text theme={null}

227~/.claude/rules/

228├── preferences.md # Your personal coding preferences

229└── workflows.md # Your preferred workflows

56```230```

57# Always use descriptive variable names231 

232User-level rules are loaded before project rules, giving project rules higher priority.

233 

234### Manage CLAUDE.md for large teams

235 

236For organizations deploying Claude Code across teams, you can centralize instructions and control which CLAUDE.md files are loaded.

237 

238#### Deploy organization-wide CLAUDE.md

239 

240Organizations can deploy a centrally managed CLAUDE.md that applies to all users on a machine. This file cannot be excluded by individual settings.

241 

242<Steps>

243 <Step title="Create the file at the managed policy location">

244 * macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`

245 * Linux and WSL: `/etc/claude-code/CLAUDE.md`

246 * Windows: `C:\Program Files\ClaudeCode\CLAUDE.md`

247 </Step>

248 

249 <Step title="Deploy with your configuration management system">

250 Use MDM, Group Policy, Ansible, or similar tools to distribute the file across developer machines. See [managed settings](/en/permissions#managed-settings) for other organization-wide configuration options.

251 </Step>

252</Steps>

253 

254A managed CLAUDE.md and [managed settings](/en/settings#settings-files) serve different purposes. Use settings for technical enforcement and CLAUDE.md for behavioral guidance:

255 

256| Concern | Configure in |

257| :--------------------------------------------- | :-------------------------------------------------------- |

258| Block specific tools, commands, or file paths | Managed settings: `permissions.deny` |

259| Enforce sandbox isolation | Managed settings: `sandbox.enabled` |

260| Environment variables and API provider routing | Managed settings: `env` |

261| Authentication method and organization lock | Managed settings: `forceLoginMethod`, `forceLoginOrgUUID` |

262| Code style and quality guidelines | Managed CLAUDE.md |

263| Data handling and compliance reminders | Managed CLAUDE.md |

264| Behavioral instructions for Claude | Managed CLAUDE.md |

265 

266Settings rules are enforced by the client regardless of what Claude decides to do. CLAUDE.md instructions shape Claude's behavior but are not a hard enforcement layer.

267 

268#### Exclude specific CLAUDE.md files

269 

270In large monorepos, ancestor CLAUDE.md files may contain instructions that aren't relevant to your work. The `claudeMdExcludes` setting lets you skip specific files by path or glob pattern.

271 

272This example excludes a top-level CLAUDE.md and a rules directory from a parent folder. Add it to `.claude/settings.local.json` so the exclusion stays local to your machine:

273 

274```json theme={null}

275{

276 "claudeMdExcludes": [

277 "**/monorepo/CLAUDE.md",

278 "/home/user/monorepo/other-team/.claude/rules/**"

279 ]

280}

58```281```

59 282 

60You'll be prompted to select which memory file to store this in.283Patterns are matched against absolute file paths using glob syntax. You can configure `claudeMdExcludes` at any [settings layer](/en/settings#settings-files): user, project, local, or managed policy. Arrays merge across layers.

284 

285Managed policy CLAUDE.md files cannot be excluded. This ensures organization-wide instructions always apply regardless of individual settings.

286 

287## Auto memory

288 

289Auto memory lets Claude accumulate knowledge across sessions without you writing anything. Claude saves notes for itself as it works: build commands, debugging insights, architecture notes, code style preferences, and workflow habits. Claude doesn't save something every session. It decides what's worth remembering based on whether the information would be useful in a future conversation.

61 290 

62## Directly edit memories with `/memory`291<Note>

292 Auto memory requires Claude Code v2.1.59 or later. Check your version with `claude --version`.

293</Note>

63 294 

64Use the `/memory` slash command during a session to open any memory file in your system editor for more extensive additions or organization.295### Enable or disable auto memory

65 296 

66## Set up project memory297Auto memory is on by default. To toggle it, open `/memory` in a session and use the auto memory toggle, or set `autoMemoryEnabled` in your project settings:

67 298 

68Suppose you want to set up a CLAUDE.md file to store important project information, conventions, and frequently used commands. Project memory can be stored in either `./CLAUDE.md` or `./.claude/CLAUDE.md`.299```json theme={null}

300{

301 "autoMemoryEnabled": false

302}

303```

304 

305To disable auto memory via environment variable, set `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1`.

306 

307### Storage location

308 

309Each 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.

69 310 

70Bootstrap a CLAUDE.md for your codebase with the following command:311To store auto memory in a different location, set `autoMemoryDirectory` in your user or local settings:

71 312 

313```json theme={null}

314{

315 "autoMemoryDirectory": "~/my-custom-memory-dir"

316}

72```317```

73> /init 318 

319This 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.

320 

321The directory contains a `MEMORY.md` entrypoint and optional topic files:

322 

323```text theme={null}

324~/.claude/projects/<project>/memory/

325├── MEMORY.md # Concise index, loaded into every session

326├── debugging.md # Detailed notes on debugging patterns

327├── api-conventions.md # API design decisions

328└── ... # Any other topic files Claude creates

74```329```

75 330 

76<Tip>331`MEMORY.md` acts as an index of the memory directory. Claude reads and writes files in this directory throughout your session, using `MEMORY.md` to keep track of what's stored where.

77 Tips:332 

333Auto memory is machine-local. All worktrees and subdirectories within the same git repository share one auto memory directory. Files are not shared across machines or cloud environments.

334 

335### How it works

336 

337The first 200 lines of `MEMORY.md`, or the first 25KB, whichever comes first, are loaded at the start of every conversation. Content beyond that threshold is not loaded at session start. Claude keeps `MEMORY.md` concise by moving detailed notes into separate topic files.

338 

339This limit applies only to `MEMORY.md`. CLAUDE.md files are loaded in full regardless of length, though shorter files produce better adherence.

340 

341Topic files like `debugging.md` or `patterns.md` are not loaded at startup. Claude reads them on demand using its standard file tools when it needs the information.

342 

343Claude reads and writes memory files during your session. When you see "Writing memory" or "Recalled memory" in the Claude Code interface, Claude is actively updating or reading from `~/.claude/projects/<project>/memory/`.

78 344 

79 * Include frequently used commands (build, test, lint) to avoid repeated searches345### Audit and edit your memory

80 * Document code style preferences and naming conventions346 

81 * Add important architectural patterns specific to your project347Auto memory files are plain markdown you can edit or delete at any time. Run [`/memory`](#view-and-edit-with-memory) to browse and open memory files from within a session.

82 * CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences.348 

349## View and edit with `/memory`

350 

351The `/memory` command lists all CLAUDE.md, CLAUDE.local.md, and rules files loaded in your current session, lets you toggle auto memory on or off, and provides a link to open the auto memory folder. Select any file to open it in your editor.

352 

353When you ask Claude to remember something, like "always use pnpm, not npm" or "remember that the API tests require a local Redis instance," Claude saves it to auto memory. To add instructions to CLAUDE.md instead, ask Claude directly, like "add this to CLAUDE.md," or edit the file yourself via `/memory`.

354 

355## Troubleshoot memory issues

356 

357These are the most common issues with CLAUDE.md and auto memory, along with steps to debug them.

358 

359### Claude isn't following my CLAUDE.md

360 

361CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself. Claude reads it and tries to follow it, but there's no guarantee of strict compliance, especially for vague or conflicting instructions.

362 

363To debug:

364 

365* Run `/memory` to verify your CLAUDE.md and CLAUDE.local.md files are being loaded. If a file isn't listed, Claude can't see it.

366* Check that the relevant CLAUDE.md is in a location that gets loaded for your session (see [Choose where to put CLAUDE.md files](#choose-where-to-put-claude-md-files)).

367* Make instructions more specific. "Use 2-space indentation" works better than "format code nicely."

368* Look for conflicting instructions across CLAUDE.md files. If two files give different guidance for the same behavior, Claude may pick one arbitrarily.

369 

370For 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.

371 

372<Tip>

373 Use the [`InstructionsLoaded` hook](/en/hooks#instructionsloaded) to log exactly which instruction files are loaded, when they load, and why. This is useful for debugging path-specific rules or lazy-loaded files in subdirectories.

83</Tip>374</Tip>

84 375 

85## Organization-level memory management376### I don't know what auto memory saved

377 

378Run `/memory` and select the auto memory folder to browse what Claude has saved. Everything is plain markdown you can read, edit, or delete.

86 379 

87Enterprise organizations can deploy centrally managed CLAUDE.md files that apply to all users.380### My CLAUDE.md is too large

88 381 

89To set up organization-level memory management:382Files 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.

90 383 

911. Create the enterprise memory file in the appropriate location for your operating system:384### Instructions seem lost after `/compact`

92 385 

93* macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`386CLAUDE.md fully survives compaction. After `/compact`, Claude re-reads your CLAUDE.md from disk and re-injects it fresh into the session. If an instruction disappeared after compaction, it was given only in conversation, not written to CLAUDE.md. Add it to CLAUDE.md to make it persist across sessions.

94* Linux/WSL: `/etc/claude-code/CLAUDE.md`

95* Windows: `C:\ProgramData\ClaudeCode\CLAUDE.md`

96 387 

972. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines.388See [Write effective instructions](#write-effective-instructions) for guidance on size, structure, and specificity.

98 389 

99## Memory best practices390## Related resources

100 391 

101* **Be specific**: "Use 2-space indentation" is better than "Format code properly".392* [Skills](/en/skills): package repeatable workflows that load on demand

102* **Use structure to organize**: Format each individual memory as a bullet point and group related memories under descriptive markdown headings.393* [Settings](/en/settings): configure Claude Code behavior with settings files

103* **Review periodically**: Update memories as your project evolves to ensure Claude is always using the most up to date information and context.394* [Manage sessions](/en/sessions): manage context, resume conversations, and run parallel sessions

395* [Subagent memory](/en/sub-agents#enable-persistent-memory): let subagents maintain their own auto memory

microsoft-foundry.md +124 −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# Claude Code on Microsoft Foundry

6 

7> Learn about configuring Claude Code through Microsoft Foundry, including setup, configuration, and troubleshooting.

8 

9## Prerequisites

10 

11Before configuring Claude Code with Microsoft Foundry, ensure you have:

12 

13* An Azure subscription with access to Microsoft Foundry

14* RBAC permissions to create Microsoft Foundry resources and deployments

15* Azure CLI installed and configured (optional - only needed if you don't have another mechanism for getting credentials)

16 

17<Note>

18 If you are deploying Claude Code to multiple users, [pin your model versions](#4-pin-model-versions) to prevent breakage when Anthropic releases new models.

19</Note>

20 

21## Setup

22 

23### 1. Provision Microsoft Foundry resource

24 

25First, create a Claude resource in Azure:

26 

271. Navigate to the [Microsoft Foundry portal](https://ai.azure.com/)

282. Create a new resource, noting your resource name

293. Create deployments for the Claude models:

30 * Claude Opus

31 * Claude Sonnet

32 * Claude Haiku

33 

34### 2. Configure Azure credentials

35 

36Claude Code supports two authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements.

37 

38**Option A: API key authentication**

39 

401. Navigate to your resource in the Microsoft Foundry portal

412. Go to the **Endpoints and keys** section

423. Copy **API Key**

434. Set the environment variable:

44 

45```bash theme={null}

46export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key

47```

48 

49**Option B: Microsoft Entra ID authentication**

50 

51When `ANTHROPIC_FOUNDRY_API_KEY` is not set, Claude Code automatically uses the Azure SDK [default credential chain](https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview).

52This supports a variety of methods for authenticating local and remote workloads.

53 

54On local environments, you commonly may use the Azure CLI:

55 

56```bash theme={null}

57az login

58```

59 

60<Note>

61 When using Microsoft Foundry, the `/login` and `/logout` commands are disabled since authentication is handled through Azure credentials.

62</Note>

63 

64### 3. Configure Claude Code

65 

66Set the following environment variables to enable Microsoft Foundry:

67 

68```bash theme={null}

69# Enable Microsoft Foundry integration

70export CLAUDE_CODE_USE_FOUNDRY=1

71 

72# Azure resource name (replace {resource} with your resource name)

73export ANTHROPIC_FOUNDRY_RESOURCE={resource}

74# Or provide the full base URL:

75# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com/anthropic

76```

77 

78### 4. Pin model versions

79 

80<Warning>

81 Pin specific model versions for every deployment. If you use model aliases (`sonnet`, `opus`, `haiku`) without pinning, Claude Code may attempt to use a newer model version that isn't available in your Foundry account, breaking existing users when Anthropic releases updates. When you create Azure deployments, select a specific model version rather than "auto-update to latest."

82</Warning>

83 

84Set the model variables to match the deployment names you created in step 1:

85 

86```bash theme={null}

87export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'

88export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-6'

89export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'

90```

91 

92For current and legacy model IDs, see [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for the full list of environment variables.

93 

94## Azure RBAC configuration

95 

96The `Azure AI User` and `Cognitive Services User` default roles include all required permissions for invoking Claude models.

97 

98For more restrictive permissions, create a custom role with the following:

99 

100```json theme={null}

101{

102 "permissions": [

103 {

104 "dataActions": [

105 "Microsoft.CognitiveServices/accounts/providers/*"

106 ]

107 }

108 ]

109}

110```

111 

112For details, see [Microsoft Foundry RBAC documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry).

113 

114## Troubleshooting

115 

116If you receive an error "Failed to get token from azureADTokenProvider: ChainedTokenCredential authentication failed":

117 

118* Configure Entra ID on the environment, or set `ANTHROPIC_FOUNDRY_API_KEY`.

119 

120## Additional resources

121 

122* [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)

123* [Microsoft Foundry models](https://ai.azure.com/explore/models)

124* [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)

model-config.md +240 −29

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Model configuration5# Model configuration

2 6 

3> Learn about the Claude Code model configuration, including model aliases like `opusplan`7> Learn about the Claude Code model configuration, including model aliases like `opusplan`

4 8 

5## Available models9## Available models

6 10 

7For the `model` setting in Claude Code, you can either configure:11For the `model` setting in Claude Code, you can configure either:

8 12 

9* A **model alias**13* A **model alias**

10* A full **[model name](/en/docs/about-claude/models/overview#model-names)**14* A **model name**

11* For Bedrock, an ARN15 * Anthropic API: A full **[model name](https://platform.claude.com/docs/en/about-claude/models/overview)**

16 * Bedrock: an inference profile ARN

17 * Foundry: a deployment name

18 * Vertex: a version name

12 19 

13### Model aliases20### Model aliases

14 21 


16remembering exact version numbers:23remembering exact version numbers:

17 24 

18| Model alias | Behavior |25| Model alias | Behavior |

19| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |26| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

20| **`default`** | Recommended model setting, depending on your account type |27| **`default`** | Special value that clears any model override and reverts to the recommended model for your account type. Not itself a model alias |

21| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.5) for daily coding tasks |28| **`best`** | Uses the most capable available model, currently equivalent to `opus` |

22| **`opus`** | Uses Opus model (currently Opus 4.1) for specialized complex reasoning tasks |29| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.6) for daily coding tasks |

30| **`opus`** | Uses the latest Opus model (currently Opus 4.6) for complex reasoning tasks |

23| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |31| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |

24| **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](/en/docs/build-with-claude/context-windows#1m-token-context-window) window for long sessions |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 |

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 |

25| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |34| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |

26 35 

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`.

37 

27### Setting your model38### Setting your model

28 39 

29You can configure your model in several ways, listed in order of priority:40You can configure your model in several ways, listed in order of priority:


46 57 

47Example settings file:58Example settings file:

48 59 

49```60```json theme={null}

50{61{

51 "permissions": {62 "permissions": {

52 ...63 ...


55}66}

56```67```

57 68 

69## Restrict model selection

70 

71Enterprise administrators can use `availableModels` in [managed or policy settings](/en/settings#settings-files) to restrict which models users can select.

72 

73When `availableModels` is set, users cannot switch to models not in the list via `/model`, `--model` flag, Config tool, or `ANTHROPIC_MODEL` environment variable.

74 

75```json theme={null}

76{

77 "availableModels": ["sonnet", "haiku"]

78}

79```

80 

81### Default model behavior

82 

83The Default option in the model picker is not affected by `availableModels`. It always remains available and represents the system's runtime default [based on the user's subscription tier](#default-model-setting).

84 

85Even with `availableModels: []`, users can still use Claude Code with the Default model for their tier.

86 

87### Control the model users run on

88 

89The `model` setting is an initial selection, not enforcement. It sets which model is active when a session starts, but users can still open `/model` and pick Default, which resolves to the system default for their tier regardless of what `model` is set to.

90 

91To fully control the model experience, combine three settings:

92 

93* **`availableModels`**: restricts which named models users can switch to

94* **`model`**: sets the initial model selection when a session starts

95* **`ANTHROPIC_DEFAULT_SONNET_MODEL`** / **`ANTHROPIC_DEFAULT_OPUS_MODEL`** / **`ANTHROPIC_DEFAULT_HAIKU_MODEL`**: control what the Default option and the `sonnet`, `opus`, and `haiku` aliases resolve to

96 

97This example starts users on Sonnet 4.5, limits the picker to Sonnet and Haiku, and pins Default to resolve to Sonnet 4.5 rather than the latest release:

98 

99```json theme={null}

100{

101 "model": "claude-sonnet-4-5",

102 "availableModels": ["claude-sonnet-4-5", "haiku"],

103 "env": {

104 "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-4-5"

105 }

106}

107```

108 

109Without the `env` block, a user who selects Default in the picker would get the latest Sonnet release, bypassing the version pin in `model` and `availableModels`.

110 

111### Merge behavior

112 

113When `availableModels` is set at multiple levels, such as user settings and project settings, arrays are merged and deduplicated. To enforce a strict allowlist, set `availableModels` in managed or policy settings which take highest priority.

114 

58## Special model behavior115## Special model behavior

59 116 

60### `default` model setting117### `default` model setting

61 118 

62The behavior of `default` depends on your account type.119The behavior of `default` depends on your account type:

120 

121* **Max and Team Premium**: defaults to Opus 4.6

122* **Pro and Team Standard**: defaults to Sonnet 4.6

123* **Enterprise**: Opus 4.6 is available but not the default

63 124 

64For certain Max users, Claude Code will automatically fall back to Sonnet if you125Claude Code may automatically fall back to Sonnet if you hit a usage threshold with Opus.

65hit a usage threshold with Opus.

66 126 

67### `opusplan` model setting127### `opusplan` model setting

68 128 


76This gives you the best of both worlds: Opus's superior reasoning for planning,136This gives you the best of both worlds: Opus's superior reasoning for planning,

77and Sonnet's efficiency for execution.137and Sonnet's efficiency for execution.

78 138 

79### Extended context with \[1m]139### Adjust effort level

140 

141[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.

142 

143Three 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.

144 

145Opus 4.6 and Sonnet 4.6 default to medium effort. This applies to all providers, including Bedrock, Vertex AI, and direct API access.

146 

147Medium is the recommended level for most coding tasks: it balances speed and reasoning depth, and higher levels can cause the model to overthink routine work. Reserve `high` or `max` for tasks that genuinely benefit from deeper reasoning, such as hard debugging problems or complex architectural decisions.

148 

149For one-off deep reasoning without changing your session setting, include "ultrathink" in your prompt to trigger high effort for that turn.

150 

151**Setting effort:**

152 

153* **`/effort`**: run `/effort low`, `/effort medium`, `/effort high`, or `/effort max` to change the level, or `/effort auto` to reset to the model default

154* **In `/model`**: use left/right arrow keys to adjust the effort slider when selecting a model

155* **`--effort` flag**: pass `low`, `medium`, `high`, or `max` to set the level for a single session when launching Claude Code

156* **Environment variable**: set `CLAUDE_CODE_EFFORT_LEVEL` to `low`, `medium`, `high`, `max`, or `auto`

157* **Settings**: set `effortLevel` in your settings file to `"low"`, `"medium"`, or `"high"`

158* **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

159 

160The 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.

80 161 

81For Console/API users, the `[1m]` suffix can be added to full model names to162Effort 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`.

82enable a163 

83[1 million token context window](/en/docs/build-with-claude/context-windows#1m-token-context-window).164To 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).

165 

166### Extended context

167 

168Opus 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.

169 

170Availability 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.

171 

172| Plan | Opus 4.6 with 1M context | Sonnet 4.6 with 1M context |

173| ------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |

174| Max, Team, and Enterprise | Included with subscription | Requires [extra usage](https://support.claude.com/en/articles/12429409-extra-usage-for-paid-claude-plans) |

175| 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) |

176| API and pay-as-you-go | Full access | Full access |

177 

178To disable 1M context entirely, set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. This removes 1M model variants from the model picker. See [environment variables](/en/env-vars).

179 

180The 1M context window uses standard model pricing with no premium for tokens beyond 200K. For plans where extended context is included with your subscription, usage remains covered by your subscription. For plans that access extended context through extra usage, tokens are billed to extra usage.

181 

182If your account supports 1M context, the option appears in the model picker (`/model`) in the latest versions of Claude Code. If you don't see it, try restarting your session.

183 

184You can also use the `[1m]` suffix with model aliases or full model names:

84 185 

85```bash theme={null}186```bash theme={null}

86# Example of using a full model name with the [1m] suffix187# Use the opus[1m] or sonnet[1m] alias

87/model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]188/model opus[1m]

88```189/model sonnet[1m]

89 190 

90Note: Extended context models have191# Or append [1m] to a full model name

91[different pricing](/en/docs/about-claude/pricing#long-context-pricing).192/model claude-opus-4-6[1m]

193```

92 194 

93## Checking your current model195## Checking your current model

94 196 

95You can see which model you're currently using in several ways:197You can see which model you're currently using in several ways:

96 198 

971. In [status line](/en/docs/claude-code/statusline) (if configured)1991. In [status line](/en/statusline) (if configured)

982. In `/status`, which also displays your account information.2002. In `/status`, which also displays your account information.

99 201 

202## Add a custom model option

203 

204Use `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.

205 

206This example sets all three variables to make a gateway-routed Opus deployment selectable:

207 

208```bash theme={null}

209export ANTHROPIC_CUSTOM_MODEL_OPTION="my-gateway/claude-opus-4-6"

210export ANTHROPIC_CUSTOM_MODEL_OPTION_NAME="Opus via Gateway"

211export ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION="Custom deployment routed through the internal LLM gateway"

212```

213 

214The custom entry appears at the bottom of the `/model` picker. `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` and `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` are optional. If omitted, the model ID is used as the name and the description defaults to `Custom model (<model-id>)`.

215 

216Claude Code skips validation for the model ID set in `ANTHROPIC_CUSTOM_MODEL_OPTION`, so you can use any string your API endpoint accepts.

217 

100## Environment variables218## Environment variables

101 219 

102You can use the following environment variables, which must be full **model220You can use the following environment variables, which must be full **model

103names**, to control the model names that the aliases map to.221names** (or equivalent for your API provider), to control the model names that the aliases map to.

104 222 

105| Env var | Description |223| Environment variable | Description |

106| -------------------------------- | -------------------------------------------------------------------------------------------------------------- |224| -------------------------------- | --------------------------------------------------------------------------------------------- |

107| `ANTHROPIC_DEFAULT_OPUS_MODEL` | The model to use for `opus`, or for `opusplan` when Plan Mode is active. |225| `ANTHROPIC_DEFAULT_OPUS_MODEL` | The model to use for `opus`, or for `opusplan` when Plan Mode is active. |

108| `ANTHROPIC_DEFAULT_SONNET_MODEL` | The model to use for `sonnet`, or for `opusplan` when Plan Mode is not active. |226| `ANTHROPIC_DEFAULT_SONNET_MODEL` | The model to use for `sonnet`, or for `opusplan` when Plan Mode is not active. |

109| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | The model to use for `haiku`, or [background functionality](/en/docs/claude-code/costs#background-token-usage) |227| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | The model to use for `haiku`, or [background functionality](/en/costs#background-token-usage) |

110| `CLAUDE_CODE_SUBAGENT_MODEL` | The model to use for [subagents](/en/docs/claude-code/sub-agents) |228| `CLAUDE_CODE_SUBAGENT_MODEL` | The model to use for [subagents](/en/sub-agents) |

111 229 

112Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of230Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of

113`ANTHROPIC_DEFAULT_HAIKU_MODEL`.231`ANTHROPIC_DEFAULT_HAIKU_MODEL`.

114 232 

233### Pin models for third-party deployments

234 

235When deploying Claude Code through [Bedrock](/en/amazon-bedrock), [Vertex AI](/en/google-vertex-ai), or [Foundry](/en/microsoft-foundry), pin model versions before rolling out to users.

236 

237Without pinning, Claude Code uses model aliases (`sonnet`, `opus`, `haiku`) that resolve to the latest version. When Anthropic releases a new model, users whose accounts don't have the new version enabled will break silently.

238 

239<Warning>

240 Set all three model environment variables to specific version IDs as part of your initial setup. Skipping this step means a Claude Code update can break your users without any action on your part.

241</Warning>

242 

243Use the following environment variables with version-specific model IDs for your provider:

244 

245| Provider | Example |

246| :-------- | :---------------------------------------------------------------------- |

247| Bedrock | `export ANTHROPIC_DEFAULT_OPUS_MODEL='us.anthropic.claude-opus-4-6-v1'` |

248| Vertex AI | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |

249| Foundry | `export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'` |

250 

251Apply 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.

252 

253To 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`:

254 

255```bash theme={null}

256export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6[1m]'

257```

258 

259The `[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.

260 

261<Note>

262 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.

263</Note>

264 

265### Customize pinned model display and capabilities

266 

267When 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.

268 

269These 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.

270 

271| Environment variable | Description |

272| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |

273| `ANTHROPIC_DEFAULT_OPUS_MODEL_NAME` | Display name for the pinned Opus model in the `/model` picker. Defaults to the model ID when not set |

274| `ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION` | Display description for the pinned Opus model in the `/model` picker. Defaults to `Custom Opus model` when not set |

275| `ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES` | Comma-separated list of capabilities the pinned Opus model supports |

276 

277The same `_NAME`, `_DESCRIPTION`, and `_SUPPORTED_CAPABILITIES` suffixes are available for `ANTHROPIC_DEFAULT_SONNET_MODEL` and `ANTHROPIC_DEFAULT_HAIKU_MODEL`.

278 

279Claude 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:

280 

281| Capability value | Enables |

282| ---------------------- | ------------------------------------------------------------------------------- |

283| `effort` | [Effort levels](#adjust-effort-level) and the `/effort` command |

284| `max_effort` | The `max` effort level |

285| `thinking` | [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) |

286| `adaptive_thinking` | Adaptive reasoning that dynamically allocates thinking based on task complexity |

287| `interleaved_thinking` | Thinking between tool calls |

288 

289When `_SUPPORTED_CAPABILITIES` is set, listed capabilities are enabled and unlisted capabilities are disabled for the matching pinned model. When the variable is unset, Claude Code falls back to built-in detection based on the model ID.

290 

291This example pins Opus to a Bedrock custom model ARN, sets a friendly name, and declares its capabilities:

292 

293```bash theme={null}

294export ANTHROPIC_DEFAULT_OPUS_MODEL='arn:aws:bedrock:us-east-1:123456789012:custom-model/abc'

295export ANTHROPIC_DEFAULT_OPUS_MODEL_NAME='Opus via Bedrock'

296export ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION='Opus 4.6 routed through a Bedrock custom endpoint'

297export ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES='effort,max_effort,thinking,adaptive_thinking,interleaved_thinking'

298```

299 

300### Override model IDs per version

301 

302The family-level environment variables above configure one model ID per family alias. If you need to map several versions within the same family to distinct provider IDs, use the `modelOverrides` setting instead.

303 

304`modelOverrides` maps individual Anthropic model IDs to the provider-specific strings that Claude Code sends to your provider's API. When a user selects a mapped model in the `/model` picker, Claude Code uses your configured value instead of the built-in default.

305 

306This lets enterprise administrators route each model version to a specific Bedrock inference profile ARN, Vertex AI version name, or Foundry deployment name for governance, cost allocation, or regional routing.

307 

308Set `modelOverrides` in your [settings file](/en/settings#settings-files):

309 

310```json theme={null}

311{

312 "modelOverrides": {

313 "claude-opus-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod",

314 "claude-opus-4-5-20251101": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-45-prod",

315 "claude-sonnet-4-6": "arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/sonnet-prod"

316 }

317}

318```

319 

320Keys must be Anthropic model IDs as listed in the [Models overview](https://platform.claude.com/docs/en/about-claude/models/overview). For dated model IDs, include the date suffix exactly as it appears there. Unknown keys are ignored.

321 

322Overrides replace the built-in model IDs that back each entry in the `/model` picker. On Bedrock, overrides take precedence over any inference profiles that Claude Code discovers automatically at startup. Values you supply directly through `ANTHROPIC_MODEL`, `--model`, or the `ANTHROPIC_DEFAULT_*_MODEL` environment variables are passed to the provider as-is and are not transformed by `modelOverrides`.

323 

324`modelOverrides` works alongside `availableModels`. The allowlist is evaluated against the Anthropic model ID, not the override value, so an entry like `"opus"` in `availableModels` continues to match even when Opus versions are mapped to ARNs.

325 

115### Prompt caching configuration326### Prompt caching configuration

116 327 

117Claude Code automatically uses [prompt caching](/en/docs/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:328Claude Code automatically uses [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:

118 329 

119| Env var | Description |330| Environment variable | Description |

120| ------------------------------- | ---------------------------------------------------------------------------------------------- |331| ------------------------------- | ---------------------------------------------------------------------------------------------- |

121| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |332| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |

122| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only |333| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only |

monitoring-usage.md +167 −107

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Monitoring5# Monitoring

2 6 

3> Learn how to enable and configure OpenTelemetry for Claude Code.7> Learn how to enable and configure OpenTelemetry for Claude Code.

4 8 

5Claude Code supports OpenTelemetry (OTel) metrics and events for monitoring and observability.9Track Claude Code usage, costs, and tool activity across your organization by exporting telemetry data through OpenTelemetry (OTel). Claude Code exports metrics as time series data via the standard metrics protocol, events via the logs/events protocol, and optionally distributed traces via the [traces protocol](#traces-beta). Configure your metrics, logs, and traces backends to match your monitoring requirements.

6 

7All metrics are time series data exported via OpenTelemetry's standard metrics protocol, and events are exported via OpenTelemetry's logs/events protocol. It is the user's responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements.

8 

9<Note>

10 OpenTelemetry support is currently in beta and details are subject to change.

11</Note>

12 10 

13## Quick Start11## Quick start

14 12 

15Configure OpenTelemetry using environment variables:13Configure OpenTelemetry using environment variables:

16 14 


19export CLAUDE_CODE_ENABLE_TELEMETRY=117export CLAUDE_CODE_ENABLE_TELEMETRY=1

20 18 

21# 2. Choose exporters (both are optional - configure only what you need)19# 2. Choose exporters (both are optional - configure only what you need)

22export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console20export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console, none

23export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console21export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console, none

24 22 

25# 3. Configure OTLP endpoint (for OTLP exporter)23# 3. Configure OTLP endpoint (for OTLP exporter)

26export OTEL_EXPORTER_OTLP_PROTOCOL=grpc24export OTEL_EXPORTER_OTLP_PROTOCOL=grpc


43 41 

44For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).42For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).

45 43 

46## Administrator Configuration44## Administrator configuration

47 

48Administrators can configure OpenTelemetry settings for all users through the managed settings file. This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/en/docs/claude-code/settings#settings-precedence) for more information about how settings are applied.

49 45 

50The managed settings file is located at:46Administrators can configure OpenTelemetry settings for all users through the [managed settings file](/en/settings#settings-files). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/en/settings#settings-precedence) for more information about how settings are applied.

51 

52* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`

53* Linux and WSL: `/etc/claude-code/managed-settings.json`

54* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`

55 47 

56Example managed settings configuration:48Example managed settings configuration:

57 49 


62 "OTEL_METRICS_EXPORTER": "otlp",54 "OTEL_METRICS_EXPORTER": "otlp",

63 "OTEL_LOGS_EXPORTER": "otlp",55 "OTEL_LOGS_EXPORTER": "otlp",

64 "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",56 "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",

65 "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317",57 "OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.example.com:4317",

66 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token"58 "OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer example-token"

67 }59 }

68}60}

69```61```


72 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.

73</Note>65</Note>

74 66 

75## Configuration Details67## Configuration details

76 68 

77### Common Configuration Variables69### Common configuration variables

78 70 

79| Environment Variable | Description | Example Values |71| Environment Variable | Description | Example Values |

80| ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------ |72| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |

81| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |73| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |

82| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |74| `OTEL_METRICS_EXPORTER` | Metrics exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `prometheus`, `none` |

83| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |75| `OTEL_LOGS_EXPORTER` | Logs/events exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `none` |

84| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |76| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter, applies to all signals | `grpc`, `http/json`, `http/protobuf` |

85| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |77| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint for all signals | `http://localhost:4317` |

86| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics (overrides general) | `grpc`, `http/json`, `http/protobuf` |78| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

87| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint (overrides general) | `http://localhost:4318/v1/metrics` |79| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint, overrides general setting | `http://localhost:4318/v1/metrics` |

88| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs (overrides general) | `grpc`, `http/json`, `http/protobuf` |80| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs, overrides general setting | `grpc`, `http/json`, `http/protobuf` |

89| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint (overrides general) | `http://localhost:4318/v1/logs` |81| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint, overrides general setting | `http://localhost:4318/v1/logs` |

90| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |82| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |

91| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |83| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |

92| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |84| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |

93| `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` |

94| `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` |

95| `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: Bash commands, MCP server and tool names, skill names, and tool input (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 |

90| `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` |

96 92 

97### Metrics Cardinality Control93### Metrics cardinality control

98 94 

99The following environment variables control which attributes are included in metrics to manage cardinality:95The following environment variables control which attributes are included in metrics to manage cardinality:

100 96 

101| Environment Variable | Description | Default Value | Example to Disable |97| Environment Variable | Description | Default Value | Example to Disable |

102| ----------------------------------- | ----------------------------------------------- | ------------- | ------------------ |98| ----------------------------------- | --------------------------------------------------------------------- | ------------- | ------------------ |

103| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` |99| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` |

104| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` |100| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` |

105| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account\_uuid attribute in metrics | `true` | `false` |101| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account\_uuid and user.account\_id attributes in metrics | `true` | `false` |

106 102 

107These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis.103These variables help control the cardinality of metrics, which affects storage requirements and query performance in your metrics backend. Lower cardinality generally means better performance and lower storage costs but less granular data for analysis.

108 104 

109### Dynamic Headers105### Traces (beta)

106 

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.

108 

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.

110 

111| Environment Variable | Description | Example Values |

112| ------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------ |

113| `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` | Enable span tracing (required). `ENABLE_ENHANCED_TELEMETRY_BETA` is also accepted | `1` |

114| `OTEL_TRACES_EXPORTER` | Traces exporter types, comma-separated. Use `none` to disable | `console`, `otlp`, `none` |

115| `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | Protocol for traces, overrides `OTEL_EXPORTER_OTLP_PROTOCOL` | `grpc`, `http/json`, `http/protobuf` |

116| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | OTLP traces endpoint, overrides `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318/v1/traces` |

117| `OTEL_TRACES_EXPORT_INTERVAL` | Span batch export interval in milliseconds (default: 5000) | `1000`, `10000` |

118 

119Spans redact user prompt text and tool content by default. Set `OTEL_LOG_USER_PROMPTS=1` and `OTEL_LOG_TOOL_CONTENT=1` to include them.

120 

121### Dynamic headers

110 122 

111For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:123For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:

112 124 

113#### Settings Configuration125#### Settings configuration

114 126 

115Add to your `.claude/settings.json`:127Add to your `.claude/settings.json`:

116 128 


120}132}

121```133```

122 134 

123#### Script Requirements135#### Script requirements

124 136 

125The script must output valid JSON with string key-value pairs representing HTTP headers:137The script must output valid JSON with string key-value pairs representing HTTP headers:

126 138 


130echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"142echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"

131```143```

132 144 

133#### Important Limitations145#### Refresh behavior

134 

135**Headers are fetched only at startup, not during runtime.** This is due to OpenTelemetry exporter architecture limitations.

136 146 

137For scenarios requiring frequent token refresh, use an OpenTelemetry Collector as a proxy that can refresh its own headers.147The headers helper script runs at startup and periodically thereafter to support token refresh. By default, the script runs every 29 minutes. Customize the interval with the `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` environment variable.

138 148 

139### Multi-Team Organization Support149### Multi-team organization support

140 150 

141Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:151Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:

142 152 


155<Warning>165<Warning>

156 **Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:**166 **Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:**

157 167 

158 The `OTEL_RESOURCE_ATTRIBUTES` environment variable follows the [W3C Baggage specification](https://www.w3.org/TR/baggage/), which has strict formatting requirements:168 The `OTEL_RESOURCE_ATTRIBUTES` environment variable uses comma-separated key=value pairs with strict formatting requirements:

159 169 

160 * **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid170 * **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid

161 * **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2`171 * **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2`


176 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"186 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"

177 ```187 ```

178 188 

179 Note: Quoting the entire key=value pair (e.g., `"key=value with spaces"`) is not supported by the OpenTelemetry specification and will result in attributes being prefixed with quotes.189 Note: wrapping values in quotes doesn't escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` (with quotes included), not `My Company`.

180</Warning>190</Warning>

181 191 

182### Example Configurations192### Example configurations

193 

194Set these environment variables before running `claude`. Each block shows a complete configuration for a different exporter or deployment scenario:

183 195 

184```bash theme={null}196```bash theme={null}

185# Console debugging (1-second intervals)197# Console debugging (1-second intervals)


207export OTEL_METRICS_EXPORTER=otlp219export OTEL_METRICS_EXPORTER=otlp

208export OTEL_LOGS_EXPORTER=otlp220export OTEL_LOGS_EXPORTER=otlp

209export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf221export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http/protobuf

210export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.company.com:4318222export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://metrics.example.com:4318

211export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc223export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc

212export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.company.com:4317224export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://logs.example.com:4317

213 225 

214# Metrics only (no events/logs)226# Metrics only (no events/logs)

215export CLAUDE_CODE_ENABLE_TELEMETRY=1227export CLAUDE_CODE_ENABLE_TELEMETRY=1


224export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317236export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

225```237```

226 238 

227## Available Metrics and Events239## Available metrics and events

228 240 

229### Standard Attributes241### Standard attributes

230 242 

231All metrics and events share these standard attributes:243All metrics and events share these standard attributes:

232 244 

233| Attribute | Description | Controlled By |245| Attribute | Description | Controlled By |

234| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |246| ------------------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |

235| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |247| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |

236| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |248| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |

237| `organization.id` | Organization UUID (when authenticated) | Always included when available |249| `organization.id` | Organization UUID (when authenticated) | Always included when available |

238| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |250| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |

239| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |251| `user.account_id` | Account ID in tagged format matching Anthropic admin APIs (when authenticated), such as `user_01BWBeN28...` | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |

252| `user.id` | Anonymous device/installation identifier, generated per Claude Code installation | Always included |

253| `user.email` | User email address (when authenticated via OAuth) | Always included when available |

254| `terminal.type` | Terminal type, such as `iTerm.app`, `vscode`, `cursor`, or `tmux` | Always included when detected |

255 

256Events additionally include the following attributes. These are never attached to metrics because they would cause unbounded cardinality:

257 

258* `prompt.id`: UUID correlating a user prompt with all subsequent events until the next prompt. See [Event correlation attributes](#event-correlation-attributes).

259* `workspace.host_paths`: host workspace directories selected in the desktop app, as a string array

240 260 

241### Metrics261### Metrics

242 262 


253| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |273| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |

254| `claude_code.active_time.total` | Total active time in seconds | s |274| `claude_code.active_time.total` | Total active time in seconds | s |

255 275 

256### Metric Details276### Metric details

257 277 

258#### Session Counter278Each metric includes the standard attributes listed above. Metrics with additional context-specific attributes are noted below.

279 

280#### Session counter

259 281 

260Incremented at the start of each session.282Incremented at the start of each session.

261 283 


263 285 

264* All [standard attributes](#standard-attributes)286* All [standard attributes](#standard-attributes)

265 287 

266#### Lines of Code Counter288#### Lines of code counter

267 289 

268Incremented when code is added or removed.290Incremented when code is added or removed.

269 291 


272* All [standard attributes](#standard-attributes)294* All [standard attributes](#standard-attributes)

273* `type`: (`"added"`, `"removed"`)295* `type`: (`"added"`, `"removed"`)

274 296 

275#### Pull Request Counter297#### Pull request counter

276 298 

277Incremented when creating pull requests via Claude Code.299Incremented when creating pull requests via Claude Code.

278 300 


280 302 

281* All [standard attributes](#standard-attributes)303* All [standard attributes](#standard-attributes)

282 304 

283#### Commit Counter305#### Commit counter

284 306 

285Incremented when creating git commits via Claude Code.307Incremented when creating git commits via Claude Code.

286 308 


288 310 

289* All [standard attributes](#standard-attributes)311* All [standard attributes](#standard-attributes)

290 312 

291#### Cost Counter313#### Cost counter

292 314 

293Incremented after each API request.315Incremented after each API request.

294 316 

295**Attributes**:317**Attributes**:

296 318 

297* All [standard attributes](#standard-attributes)319* All [standard attributes](#standard-attributes)

298* `model`: Model identifier (e.g., "claude-sonnet-4-5-20250929")320* `model`: Model identifier (for example, "claude-sonnet-4-6")

299 321 

300#### Token Counter322#### Token counter

301 323 

302Incremented after each API request.324Incremented after each API request.

303 325 


305 327 

306* All [standard attributes](#standard-attributes)328* All [standard attributes](#standard-attributes)

307* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)329* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)

308* `model`: Model identifier (e.g., "claude-sonnet-4-5-20250929")330* `model`: Model identifier (for example, "claude-sonnet-4-6")

309 331 

310#### Code Edit Tool Decision Counter332#### Code edit tool decision counter

311 333 

312Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.334Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.

313 335 

314**Attributes**:336**Attributes**:

315 337 

316* All [standard attributes](#standard-attributes)338* All [standard attributes](#standard-attributes)

317* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)339* `tool_name`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)

318* `decision`: User decision (`"accept"`, `"reject"`)340* `decision`: User decision (`"accept"`, `"reject"`)

319* `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.341* `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

342* `language`: Programming language of the edited file, such as `"TypeScript"`, `"Python"`, `"JavaScript"`, or `"Markdown"`. Returns `"unknown"` for unrecognized file extensions.

320 343 

321#### Active Time Counter344#### Active time counter

322 345 

323Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.346Tracks actual time spent actively using Claude Code, excluding idle time. This metric is incremented during user interactions (typing, reading responses) and during CLI processing (tool execution, AI response generation).

324 347 

325**Attributes**:348**Attributes**:

326 349 

327* All [standard attributes](#standard-attributes)350* All [standard attributes](#standard-attributes)

351* `type`: `"user"` for keyboard interactions, `"cli"` for tool execution and AI responses

328 352 

329### Events353### Events

330 354 

331Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):355Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):

332 356 

333#### User Prompt Event357#### Event correlation attributes

358 

359When a user submits a prompt, Claude Code may make multiple API calls and run several tools. The `prompt.id` attribute lets you tie all of those events back to the single prompt that triggered them.

360 

361| Attribute | Description |

362| ----------- | ------------------------------------------------------------------------------------ |

363| `prompt.id` | UUID v4 identifier linking all events produced while processing a single user prompt |

364 

365To trace all activity triggered by a single prompt, filter your events by a specific `prompt.id` value. This returns the user\_prompt event, any api\_request events, and any tool\_result events that occurred while processing that prompt.

366 

367<Note>

368 `prompt.id` is intentionally excluded from metrics because each prompt generates a unique ID, which would create an ever-growing number of time series. Use it for event-level analysis and audit trails only.

369</Note>

370 

371#### User prompt event

334 372 

335Logged when a user submits a prompt.373Logged when a user submits a prompt.

336 374 


341* All [standard attributes](#standard-attributes)379* All [standard attributes](#standard-attributes)

342* `event.name`: `"user_prompt"`380* `event.name`: `"user_prompt"`

343* `event.timestamp`: ISO 8601 timestamp381* `event.timestamp`: ISO 8601 timestamp

382* `event.sequence`: monotonically increasing counter for ordering events within a session

344* `prompt_length`: Length of the prompt383* `prompt_length`: Length of the prompt

345* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)384* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)

346 385 

347#### Tool Result Event386#### Tool result event

348 387 

349Logged when a tool completes execution.388Logged when a tool completes execution.

350 389 


355* All [standard attributes](#standard-attributes)394* All [standard attributes](#standard-attributes)

356* `event.name`: `"tool_result"`395* `event.name`: `"tool_result"`

357* `event.timestamp`: ISO 8601 timestamp396* `event.timestamp`: ISO 8601 timestamp

397* `event.sequence`: monotonically increasing counter for ordering events within a session

358* `tool_name`: Name of the tool398* `tool_name`: Name of the tool

359* `success`: `"true"` or `"false"`399* `success`: `"true"` or `"false"`

360* `duration_ms`: Execution time in milliseconds400* `duration_ms`: Execution time in milliseconds

361* `error`: Error message (if failed)401* `error`: Error message (if failed)

362* `decision`: Either `"accept"` or `"reject"`402* `decision_type`: Either `"accept"` or `"reject"`

363* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`403* `decision_source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

364* `tool_parameters`: JSON string containing tool-specific parameters (when available)404* `tool_result_size_bytes`: Size of the tool result in bytes

365 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`405* `mcp_server_scope`: MCP server scope identifier (for MCP tools)

366 406* `tool_parameters` (when `OTEL_LOG_TOOL_DETAILS=1`): JSON string containing tool-specific parameters:

367#### API Request Event407 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `dangerouslyDisableSandbox`, and `git_commit_id` (the commit SHA, when a `git commit` command succeeds)

408 * For MCP tools: includes `mcp_server_name`, `mcp_tool_name`

409 * For Skill tool: includes `skill_name`

410* `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.

411 

412#### API request event

368 413 

369Logged for each API request to Claude.414Logged for each API request to Claude.

370 415 


375* All [standard attributes](#standard-attributes)420* All [standard attributes](#standard-attributes)

376* `event.name`: `"api_request"`421* `event.name`: `"api_request"`

377* `event.timestamp`: ISO 8601 timestamp422* `event.timestamp`: ISO 8601 timestamp

378* `model`: Model used (e.g., "claude-sonnet-4-5-20250929")423* `event.sequence`: monotonically increasing counter for ordering events within a session

424* `model`: Model used (for example, "claude-sonnet-4-6")

379* `cost_usd`: Estimated cost in USD425* `cost_usd`: Estimated cost in USD

380* `duration_ms`: Request duration in milliseconds426* `duration_ms`: Request duration in milliseconds

381* `input_tokens`: Number of input tokens427* `input_tokens`: Number of input tokens

382* `output_tokens`: Number of output tokens428* `output_tokens`: Number of output tokens

383* `cache_read_tokens`: Number of tokens read from cache429* `cache_read_tokens`: Number of tokens read from cache

384* `cache_creation_tokens`: Number of tokens used for cache creation430* `cache_creation_tokens`: Number of tokens used for cache creation

431* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active

385 432 

386#### API Error Event433#### API error event

387 434 

388Logged when an API request to Claude fails.435Logged when an API request to Claude fails.

389 436 


394* All [standard attributes](#standard-attributes)441* All [standard attributes](#standard-attributes)

395* `event.name`: `"api_error"`442* `event.name`: `"api_error"`

396* `event.timestamp`: ISO 8601 timestamp443* `event.timestamp`: ISO 8601 timestamp

397* `model`: Model used (e.g., "claude-sonnet-4-5-20250929")444* `event.sequence`: monotonically increasing counter for ordering events within a session

445* `model`: Model used (for example, "claude-sonnet-4-6")

398* `error`: Error message446* `error`: Error message

399* `status_code`: HTTP status code (if applicable)447* `status_code`: HTTP status code as a string, or `"undefined"` for non-HTTP errors

400* `duration_ms`: Request duration in milliseconds448* `duration_ms`: Request duration in milliseconds

401* `attempt`: Attempt number (for retried requests)449* `attempt`: Attempt number (for retried requests)

450* `speed`: `"fast"` or `"normal"`, indicating whether fast mode was active

402 451 

403#### Tool Decision Event452#### Tool decision event

404 453 

405Logged when a tool permission decision is made (accept/reject).454Logged when a tool permission decision is made (accept/reject).

406 455 


411* All [standard attributes](#standard-attributes)460* All [standard attributes](#standard-attributes)

412* `event.name`: `"tool_decision"`461* `event.name`: `"tool_decision"`

413* `event.timestamp`: ISO 8601 timestamp462* `event.timestamp`: ISO 8601 timestamp

414* `tool_name`: Name of the tool (e.g., "Read", "Edit", "Write", "NotebookEdit", etc.)463* `event.sequence`: monotonically increasing counter for ordering events within a session

464* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")

415* `decision`: Either `"accept"` or `"reject"`465* `decision`: Either `"accept"` or `"reject"`

416* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`466* `source`: Decision source - `"config"`, `"hook"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

417 467 

418## Interpreting Metrics and Events Data468## Interpret metrics and events data

419 469 

420The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:470The exported metrics and events support a range of analyses:

421 471 

422### Usage Monitoring472### Usage monitoring

423 473 

424| Metric | Analysis Opportunity |474| Metric | Analysis Opportunity |

425| ------------------------------------------------------------- | --------------------------------------------------------- |475| ------------------------------------------------------------- | --------------------------------------------------------- |


428| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |478| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |

429| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |479| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |

430 480 

431### Cost Monitoring481### Cost monitoring

432 482 

433The `claude_code.cost.usage` metric helps with:483The `claude_code.cost.usage` metric helps with:

434 484 


439 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).489 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).

440</Note>490</Note>

441 491 

442### Alerting and Segmentation492### Alerting and segmentation

443 493 

444Common alerts to consider:494Common alerts to consider:

445 495 


447* Unusual token consumption497* Unusual token consumption

448* High session volume from specific users498* High session volume from specific users

449 499 

450All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`.500All metrics can be segmented by `user.account_uuid`, `user.account_id`, `organization.id`, `session.id`, `model`, and `app.version`.

451 501 

452### Event Analysis502### Event analysis

453 503 

454The event data provides detailed insights into Claude Code interactions:504The event data provides detailed insights into Claude Code interactions:

455 505 

456**Tool Usage Patterns**: Analyze tool result events to identify:506**Tool Usage Patterns**: analyze tool result events to identify:

457 507 

458* Most frequently used tools508* Most frequently used tools

459* Tool success rates509* Tool success rates

460* Average tool execution times510* Average tool execution times

461* Error patterns by tool type511* Error patterns by tool type

462 512 

463**Performance Monitoring**: Track API request durations and tool execution times to identify performance bottlenecks.513**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.

514 

515## Backend considerations

516 

517Your choice of metrics, logs, and traces backends determines the types of analyses you can perform:

518 

519### For metrics

464 520 

465## Backend Considerations521* **Time series databases (for example, Prometheus)**: Rate calculations, aggregated metrics

522* **Columnar stores (for example, ClickHouse)**: Complex queries, unique user analysis

523* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Advanced querying, visualization, alerting

466 524 

467Your choice of metrics and logs backends will determine the types of analyses you can perform:525### For events/logs

468 526 

469### For Metrics:527* **Log aggregation systems (for example, Elasticsearch, Loki)**: Full-text search, log analysis

528* **Columnar stores (for example, ClickHouse)**: Structured event analysis

529* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Correlation between metrics and events

470 530 

471* **Time series databases (e.g., Prometheus)**: Rate calculations, aggregated metrics531### For traces

472* **Columnar stores (e.g., ClickHouse)**: Complex queries, unique user analysis

473* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Advanced querying, visualization, alerting

474 532 

475### For Events/Logs:533Choose a backend that supports distributed trace storage and span correlation:

476 534 

477* **Log aggregation systems (e.g., Elasticsearch, Loki)**: Full-text search, log analysis535* **Distributed tracing systems (for example, Jaeger, Zipkin, Grafana Tempo)**: Span visualization, request waterfalls, latency analysis

478* **Columnar stores (e.g., ClickHouse)**: Structured event analysis536* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Trace search and correlation with metrics and logs

479* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Correlation between metrics and events

480 537 

481For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.538For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.

482 539 

483## Service Information540## Service information

484 541 

485All metrics and events are exported with the following resource attributes:542All metrics and events are exported with the following resource attributes:

486 543 

487* `service.name`: `claude-code`544* `service.name`: `claude-code`

488* `service.version`: Current Claude Code version545* `service.version`: Current Claude Code version

489* `os.type`: Operating system type (e.g., `linux`, `darwin`, `windows`)546* `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`)

490* `os.version`: Operating system version string547* `os.version`: Operating system version string

491* `host.arch`: Host architecture (e.g., `amd64`, `arm64`)548* `host.arch`: Host architecture (for example, `amd64`, `arm64`)

492* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)549* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)

493* Meter Name: `com.anthropic.claude_code`550* Meter Name: `com.anthropic.claude_code`

494 551 

495## ROI Measurement Resources552## ROI measurement resources

496 553 

497For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear.554For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear.

498 555 

499## Security/Privacy Considerations556## Security and privacy

500 557 

501* Telemetry is opt-in and requires explicit configuration558* Telemetry is opt-in and requires explicit configuration

502* Sensitive information like API keys or file contents are never included in metrics or events559* 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

503* User prompt content is redacted by default - only prompt length is recorded. To enable user prompt logging, set `OTEL_LOG_USER_PROMPTS=1`560* 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

561* User prompt content is not collected by default. Only prompt length is recorded. To include prompt content, set `OTEL_LOG_USER_PROMPTS=1`

562* 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. 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

563* 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

504 564 

505## Monitoring Claude Code on Amazon Bedrock565## Monitor Claude Code on Amazon Bedrock

506 566 

507For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md).567For detailed Claude Code usage monitoring guidance for Amazon Bedrock, see [Claude Code Monitoring Implementation (Bedrock)](https://github.com/aws-solutions-library-samples/guidance-for-claude-code-with-amazon-bedrock/blob/main/assets/docs/MONITORING.md).

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Enterprise network configuration5# Enterprise network configuration

2 6 

3> Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.7> Configure Claude Code for enterprise environments with proxy servers, custom Certificate Authorities (CA), and mutual Transport Layer Security (mTLS) authentication.


5Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.9Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.

6 10 

7<Note>11<Note>

8 All environment variables shown on this page can also be configured in [`settings.json`](/en/docs/claude-code/settings).12 All environment variables shown on this page can also be configured in [`settings.json`](/en/settings).

9</Note>13</Note>

10 14 

11## Proxy configuration15## Proxy configuration


76 80 

77Claude Code requires access to the following URLs:81Claude Code requires access to the following URLs:

78 82 

79* `api.anthropic.com` - Claude API endpoints83* `api.anthropic.com`: Claude API endpoints

80* `claude.ai` - WebFetch safeguards84* `claude.ai`: authentication for claude.ai accounts

81* `statsig.anthropic.com` - Telemetry and metrics85* `platform.claude.com`: authentication for Anthropic Console accounts

82* `sentry.io` - Error reporting

83 86 

84Ensure these URLs are allowlisted in your proxy configuration and firewall rules. This is especially important when using Claude Code in containerized or restricted network environments.87Ensure these URLs are allowlisted in your proxy configuration and firewall rules. This is especially important when using Claude Code in containerized or restricted network environments.

85 88 

89The 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:

90 

91* `storage.googleapis.com`: download bucket for the Claude Code binary and auto-updater

92* `downloads.claude.ai`: CDN hosting the install script, version pointers, manifests, signing keys, and plugin executables

93 

94[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).

95 

96For self-hosted [GitHub Enterprise Server](/en/github-enterprise-server) instances behind a firewall, allowlist the same [Anthropic API IP addresses](https://platform.claude.com/docs/en/api/ip-addresses) so Anthropic infrastructure can reach your GHES host to clone repositories and post review comments.

97 

86## Additional resources98## Additional resources

87 99 

88* [Claude Code settings](/en/docs/claude-code/settings)100* [Claude Code settings](/en/settings)

89* [Environment variables reference](/en/docs/claude-code/settings#environment-variables)101* [Environment variables reference](/en/env-vars)

90* [Troubleshooting guide](/en/docs/claude-code/troubleshooting)102* [Troubleshooting guide](/en/troubleshooting)

output-styles.md +74 −112

Details

1# Output styles1> ## Documentation Index

2 2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> [DEPRECATED] Adapt Claude Code for uses beyond software engineering3> Use this file to discover all available pages before exploring further.

4 

5<Warning>

6 Output styles are **DEPRECATED.** On **November 5, 2025** or later, we'll

7 stop supporting the output styles feature. Use `--system-prompt-file`,

8 `--system-prompt`, `--append-system-prompt`, CLAUDE.md, or [plugins](/en/docs/claude-code/plugins) instead.

9 For **Explanatory** output style users, you can reference the ([explanatory-output-style

10 plugin](https://github.com/anthropics/claude-code/tree/main/plugins/explanatory-output-style)

11 in our public repository.)

12</Warning>

13 

14## Deprecation timeline

15 

16As of **November 5, 2025**, Claude Code will:

17 

18* Stop supporting the output styles feature

19* Remove the `/output-style` command and related functionality

20 

21## Alternative for Custom Output Styles

22 

23Use `--system-prompt-file` to start a Claude Code session with your own system

24prompt. You can also use `--system-prompt` to pass in a string to use as the system prompt, or

25`--append-system-prompt` to add to the default Claude Code system prompt.

26 

27## Alternative for Explanatory Output Style: explanatory-output-style Plugin

28 

29Plugins provide more powerful and flexible ways to customize Claude Code's

30behavior. The

31[`explanatory-output-style` plugin](https://github.com/anthropics/claude-code/tree/main/plugins/explanatory-output-style)

32recreates the deprecated Explanatory output style functionality.

33 4 

34### Example: Explanatory Output Style Plugin5# Output styles

35 

36The `explanatory-output-style` plugin uses a SessionStart hook to inject

37additional context that encourages Claude to provide educational insights.

38Here's what it does:

39 

40* Provides educational insights about implementation choices

41* Explains codebase patterns and decisions

42* Balances task completion with learning opportunities

43 

44### Installing a plugin

45 

46To install a plugin like `explanatory-output-style`:

47 

48```shell Add the marketplace (if not already added) theme={null}

49/plugin marketplace add anthropics/claude-code

50```

51 

52```shell Install the plugin theme={null}

53/plugin install explanatory-output-style@claude-code-plugins

54```

55 

56```shell Restart Claude Code to activate the plugin theme={null}

57/exit

58```

59 

60```shell Disable the plugin theme={null}

61/plugin manage explanatory-output-style@claude-code-plugins

62 

631. Press enter when you see claude-code-marketplace

642. Press space when you see explanatory-output-style to toggle enabled

653. Press down to "Apply changes", then press enter

66 You should see "Disabled 1 plugin. Restart Claude Code to apply changes."

67 

68/exit

69```

70 

71For more details on plugins, see the

72[Plugins documentation](/en/docs/claude-code/plugins).

73 

74***

75 

76## Reference: Original output styles documentation

77 6 

78<Note>7> Adapt Claude Code for uses beyond software engineering

79 The content below is preserved for reference only. Output styles are

80 deprecated and will be removed on November 5, 2025. Please migrate to plugins,

81 hooks, or subagents.

82</Note>

83 8 

84Output styles allow you to use Claude Code as any type of agent while keeping9Output styles allow you to use Claude Code as any type of agent while keeping

85its core capabilities, such as running local scripts, reading/writing files, and10its core capabilities, such as running local scripts, reading/writing files, and

86tracking TODOs.11tracking TODOs.

87 12 

88### Built-in output styles13## Built-in output styles

89 14 

90Claude Code's **Default** output style is the existing system prompt, designed15Claude Code's **Default** output style is the existing system prompt, designed

91to help you complete software engineering tasks efficiently.16to help you complete software engineering tasks efficiently.


102 pieces of code yourself. Claude Code will add `TODO(human)` markers in your27 pieces of code yourself. Claude Code will add `TODO(human)` markers in your

103 code for you to implement.28 code for you to implement.

104 29 

105### How output styles work30## How output styles work

106 31 

107Output styles directly modify Claude Code's system prompt.32Output styles directly modify Claude Code's system prompt.

108 33 

109* Non-default output styles exclude instructions specific to code generation and34* Custom output styles exclude instructions for coding (such as verifying code

110 efficient output normally built into Claude Code (such as responding concisely35 with tests), unless `keep-coding-instructions` is true.

111 and verifying code with tests).36* All output styles have their own custom instructions added to the end of the

112* Instead, these output styles have their own custom instructions added to the

113 system prompt.37 system prompt.

38* All output styles trigger reminders for Claude to adhere to the output style

39 instructions during the conversation.

114 40 

115### Change your output style41Token usage depends on the style. Adding instructions to the system prompt

42increases input tokens, though prompt caching reduces this cost after the first

43request in a session. The built-in Explanatory and Learning styles produce

44longer responses than Default by design, which increases output tokens. For

45custom styles, output token usage depends on what your instructions tell Claude

46to produce.

116 47 

117You can either:48## Change your output style

118 49 

119* Run `/output-style` to access the menu and select your output style (this can50Run `/config` and select **Output style** to pick a style from a menu. Your

120 also be accessed from the `/config` menu)51selection is saved to `.claude/settings.local.json` at the

52[local project level](/en/settings).

121 53 

122* Run `/output-style [style]`, such as `/output-style explanatory`, to directly54To set a style without the menu, edit the `outputStyle` field directly in a

123 switch to a style55settings file:

124 56 

125These changes apply to the [local project level](/en/docs/claude-code/settings)57```json theme={null}

126and are saved in `.claude/settings.local.json`.58{

59 "outputStyle": "Explanatory"

60}

61```

127 62 

128You can also create your own output style Markdown files and save them either at63Because the output style is set in the system prompt at session start,

129the user level (`~/.claude/output-styles`) or the project level64changes take effect the next time you start a new session. This keeps the system

130(`.claude/output-styles`).65prompt stable throughout a conversation so prompt caching can reduce latency and

66cost.

131 67 

132### Comparisons to related features68## Create a custom output style

133 69 

134#### Output Styles vs. CLAUDE.md vs. System Prompt Flags70Custom output styles are Markdown files with frontmatter and the text that will

71be added to the system prompt:

135 72 

136Output styles completely "turn off" the parts of Claude Code's default system73```markdown theme={null}

137prompt specific to software engineering.74---

75name: My Custom Style

76description:

77 A brief description of what this style does, to be displayed to the user

78---

138 79 

139**CLAUDE.md** adds the contents as a user message *following* Claude Code's default system80# Custom Style Instructions

140prompt, rather than modifying the system prompt itself.

141 81 

142**System prompt CLI flags** provide different levels of control:82You are an interactive CLI tool that helps users with software engineering

83tasks. [Your custom instructions here...]

143 84 

144* `--append-system-prompt`: Appends text to the end of the default system prompt85## Specific Behaviors

145* `--system-prompt`: Replaces the entire default system prompt with custom text

146* `--system-prompt-file`: Loads a custom system prompt from a file

147 86 

148See the [CLI reference](/en/docs/claude-code/cli-reference#system-prompt-flags) for detailed guidance on when to use each flag.87[Define how the assistant should behave in this style...]

88```

89 

90You can save these files at the user level (`~/.claude/output-styles`) or

91project level (`.claude/output-styles`).

92 

93### Frontmatter

94 

95Output style files support frontmatter for specifying metadata:

96 

97| Frontmatter | Purpose | Default |

98| :------------------------- | :-------------------------------------------------------------------------- | :---------------------- |

99| `name` | Name of the output style, if not the file name | Inherits from file name |

100| `description` | Description of the output style, shown in the `/config` picker | None |

101| `keep-coding-instructions` | Whether to keep the parts of Claude Code's system prompt related to coding. | false |

102 

103## Comparisons to related features

104 

105### Output Styles vs. CLAUDE.md vs. --append-system-prompt

106 

107Output styles completely "turn off" the parts of Claude Code's default system

108prompt specific to software engineering. Neither CLAUDE.md nor

109`--append-system-prompt` edit Claude Code's default system prompt. CLAUDE.md

110adds the contents as a user message *following* Claude Code's default system

111prompt. `--append-system-prompt` appends the content to the system prompt.

149 112 

150#### Output Styles vs. [Agents](/en/docs/claude-code/sub-agents)113### Output Styles vs. [Agents](/en/sub-agents)

151 114 

152Output styles directly affect the main agent loop and only affect the system115Output styles directly affect the main agent loop and only affect the system

153prompt. Agents are invoked to handle specific tasks and can include additional116prompt. Agents are invoked to handle specific tasks and can include additional

154settings like the model to use, the tools they have available, and some context117settings like the model to use, the tools they have available, and some context

155about when to use the agent.118about when to use the agent.

156 119 

157#### Output Styles vs. [Custom Slash Commands](/en/docs/claude-code/slash-commands)120### Output Styles vs. [Skills](/en/skills)

158 121 

159You can think of output styles as “stored system prompts” and custom slash122Output styles modify how Claude responds (formatting, tone, structure) and are always active once selected. Skills are task-specific prompts that you invoke with `/skill-name` or that Claude loads automatically when relevant. Use output styles for consistent formatting preferences; use skills for reusable workflows and tasks.

160commands as “stored prompts”.

overview.md +189 −70

Details

1# Claude Code overview1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Learn about Claude Code, Anthropic's agentic coding tool that lives in your terminal and helps you turn ideas into code faster than ever before.5# Claude Code overview

4 6 

5## Get started in 30 seconds7> Claude Code is an agentic coding tool that reads your codebase, edits files, runs commands, and integrates with your development tools. Available in your terminal, IDE, desktop app, and browser.

6 8 

7Prerequisites:9Claude Code is an AI-powered coding assistant that helps you build features, fix bugs, and automate development tasks. It understands your entire codebase and can work across multiple files and tools to get things done.

8 10 

9* A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account11## Get started

10 12 

11**Install Claude Code:**13Choose your environment to get started. Most surfaces require a [Claude subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_pricing) or [Anthropic Console](https://console.anthropic.com/) account. The Terminal CLI and VS Code also support [third-party providers](/en/third-party-integrations).

12 14 

13<Tabs>15<Tabs>

14 <Tab title="macOS/Linux">16 <Tab title="Terminal">

17 The full-featured CLI for working with Claude Code directly in your terminal. Edit files, run commands, and manage your entire project from the command line.

18 

19 To install Claude Code, use one of the following methods:

20 

21 <Tabs>

22 <Tab title="Native Install (Recommended)">

23 **macOS, Linux, WSL:**

24 

15 ```bash theme={null}25 ```bash theme={null}

16 curl -fsSL https://claude.ai/install.sh | bash26 curl -fsSL https://claude.ai/install.sh | bash

17 ```27 ```

28 

29 **Windows PowerShell:**

30 

31 ```powershell theme={null}

32 irm https://claude.ai/install.ps1 | iex

33 ```

34 

35 **Windows CMD:**

36 

37 ```batch theme={null}

38 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

39 ```

40 

41 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. Use the PowerShell command above instead. Your prompt shows `PS C:\` when you're in PowerShell.

42 

43 **Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it.

44 

45 <Info>

46 Native installations automatically update in the background to keep you on the latest version.

47 </Info>

18 </Tab>48 </Tab>

19 49 

20 <Tab title="Homebrew">50 <Tab title="Homebrew">

21 ```bash theme={null}51 ```bash theme={null}

22 brew install --cask claude-code52 brew install --cask claude-code

23 ```53 ```

54 

55 <Info>

56 Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

57 </Info>

24 </Tab>58 </Tab>

25 59 

26 <Tab title="Windows">60 <Tab title="WinGet">

27 ```powershell theme={null}61 ```powershell theme={null}

28 irm https://claude.ai/install.ps1 | iex62 winget install Anthropic.ClaudeCode

29 ```63 ```

64 

65 <Info>

66 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

67 </Info>

30 </Tab>68 </Tab>

69 </Tabs>

70 

71 Then start Claude Code in any project:

31 72 

32 <Tab title="NPM">

33 ```bash theme={null}73 ```bash theme={null}

34 npm install -g @anthropic-ai/claude-code74 cd your-project

75 claude

35 ```76 ```

36 77 

37 Requires [Node.js 18+](https://nodejs.org/en/download/)78 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/en/quickstart)

79 

80 <Tip>

81 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.

82 </Tip>

83 </Tab>

84 

85 <Tab title="VS Code">

86 The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.

87 

88 * [Install for VS Code](vscode:extension/anthropic.claude-code)

89 * [Install for Cursor](cursor:extension/anthropic.claude-code)

90 

91 Or search for "Claude Code" in the Extensions view (`Cmd+Shift+X` on Mac, `Ctrl+Shift+X` on Windows/Linux). After installing, open the Command Palette (`Cmd+Shift+P` / `Ctrl+Shift+P`), type "Claude Code", and select **Open in New Tab**.

92 

93 [Get started with VS Code →](/en/vs-code#get-started)

94 </Tab>

95 

96 <Tab title="Desktop app">

97 A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, schedule recurring tasks, and kick off cloud sessions.

98 

99 Download and install:

100 

101 * [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) (Intel and Apple Silicon)

102 * [Windows](https://claude.ai/api/desktop/win32/x64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs) (x64)

103 * [Windows ARM64](https://claude.ai/api/desktop/win32/arm64/setup/latest/redirect?utm_source=claude_code\&utm_medium=docs) (remote sessions only)

104 

105 After installing, launch Claude, sign in, and click the **Code** tab to start coding. A [paid subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_desktop_pricing) is required.

106 

107 [Learn more about the desktop app →](/en/desktop-quickstart)

108 </Tab>

109 

110 <Tab title="Web">

111 Run Claude Code in your browser with no local setup. Kick off long-running tasks and check back when they're done, work on repos you don't have locally, or run multiple tasks in parallel. Available on desktop browsers and the Claude iOS app.

112 

113 Start coding at [claude.ai/code](https://claude.ai/code).

114 

115 [Get started on the web →](/en/claude-code-on-the-web#getting-started)

116 </Tab>

117 

118 <Tab title="JetBrains">

119 A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.

120 

121 Install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains Marketplace and restart your IDE.

122 

123 [Get started with JetBrains →](/en/jetbrains)

38 </Tab>124 </Tab>

39</Tabs>125</Tabs>

40 126 

41**Start using Claude Code:**127## What you can do

42 128 

43```bash theme={null}129Here are some of the ways you can use Claude Code:

44cd your-project

45claude

46```

47 130 

48You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 mins) →](/en/docs/claude-code/quickstart)131<AccordionGroup>

132 <Accordion title="Automate the work you keep putting off" icon="wand-magic-sparkles">

133 Claude Code handles the tedious tasks that eat up your day: writing tests for untested code, fixing lint errors across a project, resolving merge conflicts, updating dependencies, and writing release notes.

49 134 

50<Tip>135 ```bash theme={null}

51 See [advanced setup](/en/docs/claude-code/setup) for installation options or [troubleshooting](/en/docs/claude-code/troubleshooting) if you hit issues.136 claude "write tests for the auth module, run them, and fix any failures"

52</Tip>137 ```

138 </Accordion>

53 139 

54<Note>140 <Accordion title="Build features and fix bugs" icon="hammer">

55 **New VS Code Extension (Beta)**: Prefer a graphical interface? Our new [VS Code extension](/en/docs/claude-code/vs-code) provides an easy-to-use native IDE experience without requiring terminal familiarity. Simply install from the marketplace and start coding with Claude directly in your sidebar.141 Describe what you want in plain language. Claude Code plans the approach, writes the code across multiple files, and verifies it works.

56</Note>

57 142 

58## What Claude Code does for you143 For bugs, paste an error message or describe the symptom. Claude Code traces the issue through your codebase, identifies the root cause, and implements a fix. See [common workflows](/en/common-workflows) for more examples.

144 </Accordion>

59 145 

60* **Build features from descriptions**: Tell Claude what you want to build in plain English. It will make a plan, write the code, and ensure it works.146 <Accordion title="Create commits and pull requests" icon="code-branch">

61* **Debug and fix issues**: Describe a bug or paste an error message. Claude Code will analyze your codebase, identify the problem, and implement a fix.147 Claude Code works directly with git. It stages changes, writes commit messages, creates branches, and opens pull requests.

62* **Navigate any codebase**: Ask anything about your team's codebase, and get a thoughtful answer back. Claude Code maintains awareness of your entire project structure, can find up-to-date information from the web, and with [MCP](/en/docs/claude-code/mcp) can pull from external datasources like Google Drive, Figma, and Slack.

63* **Automate tedious tasks**: Fix fiddly lint issues, resolve merge conflicts, and write release notes. Do all this in a single command from your developer machines, or automatically in CI.

64 148 

65## Why developers love Claude Code149 ```bash theme={null}

150 claude "commit my changes with a descriptive message"

151 ```

66 152 

67* **Works in your terminal**: Not another chat window. Not another IDE. Claude Code meets you where you already work, with the tools you already love.153 In CI, you can automate code review and issue triage with [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd).

68* **Takes action**: Claude Code can directly edit files, run commands, and create commits. Need more? [MCP](/en/docs/claude-code/mcp) lets Claude read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling.154 </Accordion>

69* **Unix philosophy**: Claude Code is composable and scriptable. `tail -f app.log | claude -p "Slack me if you see any anomalies appear in this log stream"` *works*. Your CI can run `claude -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`.

70* **Enterprise-ready**: Use the Claude API, or host on AWS or GCP. Enterprise-grade [security](/en/docs/claude-code/security), [privacy](/en/docs/claude-code/data-usage), and [compliance](https://trust.anthropic.com/) is built-in.

71 155 

72## Next steps156 <Accordion title="Connect your tools with MCP" icon="plug">

157 The [Model Context Protocol (MCP)](/en/mcp) is an open standard for connecting AI tools to external data sources. With MCP, Claude Code can read your design docs in Google Drive, update tickets in Jira, pull data from Slack, or use your own custom tooling.

158 </Accordion>

159 

160 <Accordion title="Customize with instructions, skills, and hooks" icon="sliders">

161 [`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.

162 

163 Create [custom commands](/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.

164 

165 [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.

166 </Accordion>

167 

168 <Accordion title="Run agent teams and build custom agents" icon="users">

169 Spawn [multiple Claude Code agents](/en/sub-agents) that work on different parts of a task simultaneously. A lead agent coordinates the work, assigns subtasks, and merges results.

170 

171 For fully custom workflows, the [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) lets you build your own agents powered by Claude Code's tools and capabilities, with full control over orchestration, tool access, and permissions.

172 </Accordion>

173 

174 <Accordion title="Pipe, script, and automate with the CLI" icon="terminal">

175 Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:

73 176 

74<CardGroup>177 ```bash theme={null}

75 <Card title="Quickstart" icon="rocket" href="/en/docs/claude-code/quickstart">178 # Analyze recent log output

76 See Claude Code in action with practical examples179 tail -200 app.log | claude -p "Slack me if you see any anomalies"

77 </Card>180 

181 # Automate translations in CI

182 claude -p "translate new strings into French and raise a PR for review"

183 

184 # Bulk operations across files

185 git diff main --name-only | claude -p "review these changed files for security issues"

186 ```

78 187 

79 <Card title="Common workflows" icon="graduation-cap" href="/en/docs/claude-code/common-workflows">188 See the [CLI reference](/en/cli-reference) for the full set of commands and flags.

80 Step-by-step guides for common workflows189 </Accordion>

81 </Card>

82 190 

83 <Card title="Troubleshooting" icon="wrench" href="/en/docs/claude-code/troubleshooting">191 <Accordion title="Schedule recurring tasks" icon="clock">

84 Solutions for common issues with Claude Code192 Run Claude on a schedule to automate work that repeats: morning PR reviews, overnight CI failure analysis, weekly dependency audits, or syncing docs after PRs merge.

85 </Card>

86 193 

87 <Card title="IDE setup" icon="laptop" href="/en/docs/claude-code/ide-integrations">194 * [Cloud scheduled tasks](/en/web-scheduled-tasks) run on Anthropic-managed infrastructure, so they keep running even when your computer is off. Create them from the web, the Desktop app, or by running `/schedule` in the CLI.

88 Add Claude Code to your IDE195 * [Desktop scheduled tasks](/en/desktop-scheduled-tasks) run on your machine, with direct access to your local files and tools

89 </Card>196 * [`/loop`](/en/scheduled-tasks) repeats a prompt within a CLI session for quick polling

90</CardGroup>197 </Accordion>

91 198 

92## Additional resources199 <Accordion title="Work from anywhere" icon="globe">

200 Sessions aren't tied to a single surface. Move work between environments as your context changes:

93 201 

94<CardGroup>202 * Step away from your desk and keep working from your phone or any browser with [Remote Control](/en/remote-control)

95 <Card title="Host on AWS or GCP" icon="cloud" href="/en/docs/claude-code/third-party-integrations">203 * Message [Dispatch](/en/desktop#sessions-from-dispatch) a task from your phone and open the Desktop session it creates

96 Configure Claude Code with Amazon Bedrock or Google Vertex AI204 * Kick off a long-running task on the [web](/en/claude-code-on-the-web) or [iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684), then pull it into your terminal with `claude --teleport`

97 </Card>205 * Hand off a terminal session to the [Desktop app](/en/desktop) with `/desktop` for visual diff review

206 * Route tasks from team chat: mention `@Claude` in [Slack](/en/slack) with a bug report and get a pull request back

207 </Accordion>

208</AccordionGroup>

98 209 

99 <Card title="Settings" icon="gear" href="/en/docs/claude-code/settings">210## Use Claude Code everywhere

100 Customize Claude Code for your workflow

101 </Card>

102 211 

103 <Card title="Commands" icon="terminal" href="/en/docs/claude-code/cli-reference">212Each surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them.

104 Learn about CLI commands and controls

105 </Card>

106 213 

107 <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">214Beyond the [Terminal](/en/quickstart), [VS Code](/en/vs-code), [JetBrains](/en/jetbrains), [Desktop](/en/desktop), and [Web](/en/claude-code-on-the-web) environments above, Claude Code integrates with CI/CD, chat, and browser workflows:

108 Clone our development container reference implementation215 

109 </Card>216| I want to... | Best option |

217| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |

218| Continue a local session from my phone or another device | [Remote Control](/en/remote-control) |

219| Push events from Telegram, Discord, iMessage, or my own webhooks into a session | [Channels](/en/channels) |

220| Start a task locally, continue on mobile | [Web](/en/claude-code-on-the-web) or [Claude iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684) |

221| Run Claude on a recurring schedule | [Cloud scheduled tasks](/en/web-scheduled-tasks) or [Desktop scheduled tasks](/en/desktop-scheduled-tasks) |

222| Automate PR reviews and issue triage | [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd) |

223| Get automatic code review on every PR | [GitHub Code Review](/en/code-review) |

224| Route bug reports from Slack to pull requests | [Slack](/en/slack) |

225| Debug live web applications | [Chrome](/en/chrome) |

226| Build custom agents for your own workflows | [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) |

227 

228## Next steps

110 229 

111 <Card title="Security" icon="shield" href="/en/docs/claude-code/security">230Once you've installed Claude Code, these guides help you go deeper.

112 Discover Claude Code's safeguards and best practices for safe usage

113 </Card>

114 231 

115 <Card title="Privacy and data usage" icon="lock" href="/en/docs/claude-code/data-usage">232* [Quickstart](/en/quickstart): walk through your first real task, from exploring a codebase to committing a fix

116 Understand how Claude Code handles your data233* [Store instructions and memories](/en/memory): give Claude persistent instructions with CLAUDE.md files and auto memory

117 </Card>234* [Common workflows](/en/common-workflows) and [best practices](/en/best-practices): patterns for getting the most out of Claude Code

118</CardGroup>235* [Settings](/en/settings): customize Claude Code for your workflow

236* [Troubleshooting](/en/troubleshooting): solutions for common issues

237* [code.claude.com](https://code.claude.com/): demos, pricing, and product details

permission-modes.md +285 −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# Choose a permission mode

6 

7> Control whether Claude asks before editing files or running commands. Cycle modes with Shift+Tab in the CLI or use the mode selector in VS Code, Desktop, and claude.ai.

8 

9When Claude wants to edit a file, run a shell command, or make a network request, it pauses and asks you to approve the action. Permission modes control how often that pause happens. The mode you pick shapes the flow of a session: default mode has you review each action as it comes, while looser modes let Claude work in longer uninterrupted stretches and report back when done. Pick more oversight for sensitive work, or fewer interruptions when you trust the direction.

10 

11## Available modes

12 

13Each mode makes a different tradeoff between convenience and oversight. The table below shows what Claude can do without a permission prompt in each mode.

14 

15| Mode | What runs without asking | Best for |

16| :------------------------------------------------------------------ | :---------------------------------------- | :-------------------------------------- |

17| `default` | Reads only | Getting started, sensitive work |

18| [`acceptEdits`](#auto-approve-file-edits-with-acceptedits-mode) | Reads and file edits | Iterating on code you're reviewing |

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 |

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 |

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.

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.

27 

28## Switch permission modes

29 

30You can switch modes mid-session, at startup, or as a persistent default. The mode is set through these controls, not by asking Claude in chat. Select your interface below to see how to change it.

31 

32<Tabs>

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:

35 

36 * `auto`: appears after you opt in with `--enable-auto-mode` or the persisted equivalent in settings

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 it

38 * `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`

39 

40 Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.

41 

42 **At startup**: pass the mode as a flag.

43 

44 ```bash theme={null}

45 claude --permission-mode plan

46 ```

47 

48 **As a default**: set `defaultMode` in [settings](/en/settings#settings-files).

49 

50 ```json theme={null}

51 {

52 "permissions": {

53 "defaultMode": "acceptEdits"

54 }

55 }

56 ```

57 

58 The same `--permission-mode` flag works with `-p` for [non-interactive runs](/en/headless).

59 </Tab>

60 

61 <Tab title="VS Code">

62 **During a session**: click the mode indicator at the bottom of the prompt box.

63 

64 **As a default**: set `claudeCode.initialPermissionMode` in VS Code settings, or use the Claude Code extension settings panel.

65 

66 The mode indicator shows these labels, mapped to the mode each one applies:

67 

68 | UI label | Mode |

69 | :----------------- | :------------------ |

70 | Ask before edits | `default` |

71 | Edit automatically | `acceptEdits` |

72 | Plan mode | `plan` |

73 | Auto mode | `auto` |

74 | Bypass permissions | `bypassPermissions` |

75 

76 Auto mode appears in the mode indicator after you enable **Allow dangerously skip permissions** in the extension settings, but it stays unavailable until your account meets every requirement listed in the [auto mode section](#eliminate-prompts-with-auto-mode). The `claudeCode.initialPermissionMode` setting does not accept `auto`; to start in auto mode by default, set `defaultMode` in your Claude Code [`settings.json`](/en/settings#settings-files) instead.

77 

78 Bypass permissions also requires the **Allow dangerously skip permissions** toggle before it appears in the mode indicator.

79 

80 See the [VS Code guide](/en/vs-code) for extension-specific details.

81 </Tab>

82 

83 <Tab title="JetBrains">

84 The JetBrains plugin runs Claude Code in the IDE terminal, so switching modes works the same as in the CLI: press `Shift+Tab` to cycle, or pass `--permission-mode` when launching.

85 </Tab>

86 

87 <Tab title="Desktop">

88 Use the mode selector next to the send button. Auto and Bypass permissions appear only after you enable them in Desktop settings. See the [Desktop guide](/en/desktop#choose-a-permission-mode).

89 </Tab>

90 

91 <Tab title="Web and mobile">

92 Use the mode dropdown next to the prompt box on [claude.ai/code](https://claude.ai/code) or in the mobile app. Permission prompts appear in claude.ai for approval. Which modes appear depends on where the session runs:

93 

94 * **Cloud sessions** on [Claude Code on the web](/en/claude-code-on-the-web): Auto accept edits and Plan mode. Ask permissions, Auto, and Bypass permissions are not available.

95 * **[Remote Control](/en/remote-control) sessions** on your local machine: Ask permissions, Auto accept edits, and Plan mode. Auto and Bypass permissions are not available.

96 

97 For Remote Control, you can also set the starting mode when launching the host:

98 

99 ```bash theme={null}

100 claude remote-control --permission-mode acceptEdits

101 ```

102 </Tab>

103</Tabs>

104 

105## Auto-approve file edits with acceptEdits mode

106 

107`acceptEdits` mode lets Claude create and edit files in your working directory without prompting. Writes to [protected paths](#protected-paths) and all non-edit actions still prompt the same as default mode. The status bar shows `⏵⏵ accept edits on` while this mode is active.

108 

109Use `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:

110 

111```bash theme={null}

112claude --permission-mode acceptEdits

113```

114 

115## Analyze before you edit with plan mode

116 

117Plan mode tells Claude to research and propose changes without making them. Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source. Permission prompts still apply the same as default mode.

118 

119Enter plan mode by pressing `Shift+Tab` or prefixing a single prompt with `/plan`. You can also start in plan mode from the CLI:

120 

121```bash theme={null}

122claude --permission-mode plan

123```

124 

125Press `Shift+Tab` again to leave plan mode without approving a plan.

126 

127When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:

128 

129* Approve and start in auto mode

130* Approve and accept edits

131* Approve and review each edit manually

132* Keep planning with feedback

133* Refine with [Ultraplan](/en/ultraplan) for browser-based review

134 

135Each approve option also offers to clear the planning context first.

136 

137## Eliminate prompts with auto mode

138 

139<Note>

140 Auto mode requires Claude Code v2.1.83 or later.

141</Note>

142 

143Auto mode lets Claude execute without permission prompts. A separate classifier model reviews actions before they run, blocking anything that escalates beyond your request, targets unrecognized infrastructure, or appears driven by hostile content Claude read.

144 

145<Warning>

146 Auto mode is a research preview. It reduces prompts but does not guarantee safety. Use it for tasks where you trust the general direction, not as a replacement for review on sensitive operations.

147</Warning>

148 

149Auto mode is available only when your account meets all of these requirements:

150 

151* **Plan**: Team, Enterprise, or API. Not available on Pro or Max.

152* **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).

153* **Model**: Claude Sonnet 4.6 or Opus 4.6. Not available on Haiku or claude-3 models.

154* **Provider**: Anthropic API only. Not available on Bedrock, Vertex, or Foundry.

155 

156If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage.

157 

158Once enabled, start with the flag and `auto` joins the `Shift+Tab` cycle:

159 

160```bash theme={null}

161claude --enable-auto-mode

162```

163 

164### What the classifier blocks by default

165 

166The 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).

167 

168**Blocked by default**:

169 

170* Downloading and executing code, like `curl | bash`

171* Sending sensitive data to external endpoints

172* Production deploys and migrations

173* Mass deletion on cloud storage

174* Granting IAM or repo permissions

175* Modifying shared infrastructure

176* Irreversibly destroying files that existed before the session

177* Force push, or pushing directly to `main`

178 

179**Allowed by default**:

180 

181* Local file operations in your working directory

182* Installing dependencies declared in your lock files or manifests

183* Reading `.env` and sending credentials to their matching API

184* Read-only HTTP requests

185* Pushing to the branch you started on or one Claude created

186 

187Run `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).

188 

189### When auto mode falls back

190 

191Each denied action shows a notification and appears in `/permissions` under the Recently denied tab, where you can press `r` to retry it with a manual approval.

192 

193If the classifier blocks an action 3 times in a row or 20 times total, auto mode pauses and Claude Code resumes prompting. Approving the prompted action resumes auto mode. These thresholds are not configurable. Any allowed action resets the consecutive counter, while the total counter persists for the session and resets only when its own limit triggers a fallback.

194 

195In [non-interactive mode](/en/headless) with the `-p` flag, repeated blocks abort the session since there is no user to prompt.

196 

197Repeated 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).

198 

199<AccordionGroup>

200 <Accordion title="How the classifier evaluates actions">

201 Each action goes through a fixed decision order. The first matching step wins:

202 

203 1. Actions matching your [allow or deny rules](/en/permissions#manage-permissions) resolve immediately

204 2. Read-only actions and file edits in your working directory are auto-approved, except writes to [protected paths](#protected-paths)

205 3. Everything else goes to the classifier

206 4. If the classifier blocks, Claude receives the reason and tries an alternative

207 

208 On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:

209 

210 * Blanket `Bash(*)`

211 * Wildcarded interpreters like `Bash(python*)`

212 * Package-manager run commands

213 * `Agent` allow rules

214 

215 Narrow rules like `Bash(npm test)` carry over. Dropped rules are restored when you leave auto mode.

216 

217 The classifier sees user messages, tool calls, and your CLAUDE.md content. Tool results are stripped, so hostile content in a file or web page cannot manipulate it directly. A separate server-side probe scans incoming tool results and flags suspicious content before Claude reads it. For more on how these layers work together, see the [auto mode announcement](https://claude.com/blog/auto-mode) and the [engineering deep dive](https://www.anthropic.com/engineering/claude-code-auto-mode).

218 </Accordion>

219 

220 <Accordion title="How auto mode handles subagents">

221 The classifier checks [subagent](/en/sub-agents) work at three points:

222 

223 1. Before a subagent starts, the delegated task description is evaluated, so a dangerous-looking task is blocked at spawn time.

224 2. While the subagent runs, each of its actions goes through the classifier with the same rules as the parent session, and any `permissionMode` in the subagent's frontmatter is ignored.

225 3. When the subagent finishes, the classifier reviews its full action history; if that return check flags a concern, a security warning is prepended to the subagent's results.

226 </Accordion>

227 

228 <Accordion title="Cost and latency">

229 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.

230 </Accordion>

231</AccordionGroup>

232 

233## Allow only pre-approved tools with dontAsk mode

234 

235`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.

236 

237Set it at startup with the flag:

238 

239```bash theme={null}

240claude --permission-mode dontAsk

241```

242 

243## Skip all checks with bypassPermissions mode

244 

245`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.

246 

247You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:

248 

249```bash theme={null}

250claude --permission-mode bypassPermissions

251```

252 

253The `--dangerously-skip-permissions` flag is equivalent.

254 

255<Warning>

256 `bypassPermissions` offers no protection against prompt injection or unintended actions. For background safety checks without prompts, use [auto mode](#eliminate-prompts-with-auto-mode) instead. Administrators can block this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in [managed settings](/en/permissions#managed-settings).

257</Warning>

258 

259## Protected paths

260 

261Writes 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.

262 

263Protected directories:

264 

265* `.git`

266* `.vscode`

267* `.idea`

268* `.husky`

269* `.claude`, except for `.claude/commands`, `.claude/agents`, `.claude/skills`, and `.claude/worktrees` where Claude routinely creates content

270 

271Protected files:

272 

273* `.gitconfig`, `.gitmodules`

274* `.bashrc`, `.bash_profile`, `.zshrc`, `.zprofile`, `.profile`

275* `.ripgreprc`

276* `.mcp.json`, `.claude.json`

277 

278## See also

279 

280* [Permissions](/en/permissions): allow, ask, and deny rules; auto mode classifier configuration; managed policies

281* [Hooks](/en/hooks): custom permission logic via `PreToolUse` and `PermissionRequest` hooks

282* [Ultraplan](/en/ultraplan): run plan mode in a Claude Code on the web session with browser-based review

283* [Security](/en/security): safeguards and best practices

284* [Sandboxing](/en/sandboxing): filesystem and network isolation for Bash commands

285* [Non-interactive mode](/en/headless): run Claude Code with the `-p` flag

permissions.md +415 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Configure permissions

6 

7> Control what Claude Code can access and do with fine-grained permission rules, modes, and managed policies.

8 

9Claude Code supports fine-grained permissions so that you can specify exactly what the agent is allowed to do and what it cannot. Permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.

10 

11## Permission system

12 

13Claude Code uses a tiered permission system to balance power and safety:

14 

15| Tool type | Example | Approval required | "Yes, don't ask again" behavior |

16| :---------------- | :--------------- | :---------------- | :-------------------------------------------- |

17| Read-only | File reads, Grep | No | N/A |

18| Bash commands | Shell execution | Yes | Permanently per project directory and command |

19| File modification | Edit/write files | Yes | Until session end |

20 

21## Manage permissions

22 

23You can view and manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.

24 

25* **Allow** rules let Claude Code use the specified tool without manual approval.

26* **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool.

27* **Deny** rules prevent Claude Code from using the specified tool.

28 

29Rules are evaluated in order: **deny -> ask -> allow**. The first matching rule wins, so deny rules always take precedence.

30 

31## Permission modes

32 

33Claude Code supports several permission modes that control how tools are approved. See [Permission modes](/en/permission-modes) for when to use each one. Set the `defaultMode` in your [settings files](/en/settings#settings-files):

34 

35| Mode | Description |

36| :------------------ | :------------------------------------------------------------------------------------------------------------------------------- |

37| `default` | Standard behavior: prompts for permission on first use of each tool |

38| `acceptEdits` | Automatically accepts file edit permissions for the session, except writes to protected directories |

39| `plan` | Plan Mode: Claude can analyze but not modify files or execute commands |

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 |

42| `bypassPermissions` | Skips permission prompts except for writes to protected directories (see warning below) |

43 

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).

46</Warning>

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.

49 

50## Permission rule syntax

51 

52Permission rules follow the format `Tool` or `Tool(specifier)`.

53 

54### Match all uses of a tool

55 

56To match all uses of a tool, use just the tool name without parentheses:

57 

58| Rule | Effect |

59| :--------- | :----------------------------- |

60| `Bash` | Matches all Bash commands |

61| `WebFetch` | Matches all web fetch requests |

62| `Read` | Matches all file reads |

63 

64`Bash(*)` is equivalent to `Bash` and matches all Bash commands.

65 

66### Use specifiers for fine-grained control

67 

68Add a specifier in parentheses to match specific tool uses:

69 

70| Rule | Effect |

71| :----------------------------- | :------------------------------------------------------- |

72| `Bash(npm run build)` | Matches the exact command `npm run build` |

73| `Read(./.env)` | Matches reading the `.env` file in the current directory |

74| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

75 

76### Wildcard patterns

77 

78Bash rules support glob patterns with `*`. Wildcards can appear at any position in the command. This configuration allows npm and git commit commands while blocking git push:

79 

80```json theme={null}

81{

82 "permissions": {

83 "allow": [

84 "Bash(npm run *)",

85 "Bash(git commit *)",

86 "Bash(git * main)",

87 "Bash(* --version)",

88 "Bash(* --help *)"

89 ],

90 "deny": [

91 "Bash(git push *)"

92 ]

93 }

94}

95```

96 

97The space before `*` matters: `Bash(ls *)` matches `ls -la` but not `lsof`, while `Bash(ls*)` matches both. The legacy `:*` suffix syntax is equivalent to ` *` but is deprecated.

98 

99## Tool-specific permission rules

100 

101### Bash

102 

103Bash permission rules support wildcard matching with `*`. Wildcards can appear at any position in the command, including at the beginning, middle, or end:

104 

105* `Bash(npm run build)` matches the exact Bash command `npm run build`

106* `Bash(npm run test *)` matches Bash commands starting with `npm run test`

107* `Bash(npm *)` matches any command starting with `npm `

108* `Bash(* install)` matches any command ending with ` install`

109* `Bash(git * main)` matches commands like `git checkout main`, `git merge main`

110 

111When `*` 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.

112 

113<Tip>

114 Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd *)` won't give it permission to run the command `safe-cmd && other-cmd`.

115</Tip>

116 

117When you approve a compound command with "Yes, don't ask again", Claude Code saves a separate rule for each subcommand that requires approval, rather than a single rule for the full compound string. For example, approving `git status && npm test` saves a rule for `npm test`, so future `npm test` invocations are recognized regardless of what precedes the `&&`. Subcommands like `cd` into a subdirectory generate their own Read rule for that path. Up to 5 rules may be saved for a single compound command.

118 

119<Warning>

120 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:

121 

122 * Options before URL: `curl -X GET http://github.com/...`

123 * Different protocol: `curl https://github.com/...`

124 * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)

125 * Variables: `URL=http://github.com && curl $URL`

126 * Extra spaces: `curl http://github.com`

127 

128 For more reliable URL filtering, consider:

129 

130 * **Restrict Bash network tools**: use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains

131 * **Use PreToolUse hooks**: implement a hook that validates URLs in Bash commands and blocks disallowed domains

132 * Instructing Claude Code about your allowed curl patterns via CLAUDE.md

133 

134 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.

135</Warning>

136 

137### Read and Edit

138 

139`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.

140 

141<Warning>

142 Read and Edit deny rules apply to Claude's built-in file tools, not to Bash subprocesses. A `Read(./.env)` deny rule blocks the Read tool but does not prevent `cat .env` in Bash. For OS-level enforcement that blocks all processes from accessing a path, [enable the sandbox](/en/sandboxing).

143</Warning>

144 

145Read and Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

146 

147| Pattern | Meaning | Example | Matches |

148| ------------------ | -------------------------------------- | -------------------------------- | ------------------------------ |

149| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

150| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

151| `/path` | Path **relative to project root** | `Edit(/src/**/*.ts)` | `<project root>/src/**/*.ts` |

152| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

153 

154<Warning>

155 A pattern like `/Users/alice/file` is NOT an absolute path. It's relative to the project root. Use `//Users/alice/file` for absolute paths.

156</Warning>

157 

158On Windows, paths are normalized to POSIX form before matching. `C:\Users\alice` becomes `/c/Users/alice`, so use `//c/**/.env` to match `.env` files anywhere on that drive. To match across all drives, use `//**/.env`.

159 

160Examples:

161 

162* `Edit(/docs/**)`: edits in `<project>/docs/` (NOT `/docs/` and NOT `<project>/.claude/docs/`)

163* `Read(~/.zshrc)`: reads your home directory's `.zshrc`

164* `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt`

165* `Read(src/**)`: reads from `<current-directory>/src/`

166 

167<Note>

168 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`.

169</Note>

170 

171### WebFetch

172 

173* `WebFetch(domain:example.com)` matches fetch requests to example.com

174 

175### MCP

176 

177* `mcp__puppeteer` matches any tool provided by the `puppeteer` server (name configured in Claude Code)

178* `mcp__puppeteer__*` wildcard syntax that also matches all tools from the `puppeteer` server

179* `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server

180 

181### Agent (subagents)

182 

183Use `Agent(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use:

184 

185* `Agent(Explore)` matches the Explore subagent

186* `Agent(Plan)` matches the Plan subagent

187* `Agent(my-custom-agent)` matches a custom subagent named `my-custom-agent`

188 

189Add these rules to the `deny` array in your settings or use the `--disallowedTools` CLI flag to disable specific agents. To disable the Explore agent:

190 

191```json theme={null}

192{

193 "permissions": {

194 "deny": ["Agent(Explore)"]

195 }

196}

197```

198 

199## Extend permissions with hooks

200 

201[Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission prompt. The hook output can deny the tool call, force a prompt, or skip the prompt to let the call proceed.

202 

203Skipping the prompt does not bypass permission rules. Deny and ask rules are still evaluated after a hook returns `"allow"`, so a matching deny rule still blocks the call. This preserves the deny-first precedence described in [Manage permissions](#manage-permissions), including deny rules set in managed settings.

204 

205A blocking hook also takes precedence over allow rules. A hook that exits with code 2 stops the tool call before permission rules are evaluated, so the block applies even when an allow rule would otherwise let the call proceed. To run all Bash commands without prompts except for a few you want blocked, add `"Bash"` to your allow list and register a PreToolUse hook that rejects those specific commands. See [Block edits to protected files](/en/hooks-guide#block-edits-to-protected-files) for a hook script you can adapt.

206 

207## Working directories

208 

209By default, Claude has access to files in the directory where it was launched. You can extend this access:

210 

211* **During startup**: use `--add-dir <path>` CLI argument

212* **During session**: use `/add-dir` command

213* **Persistent configuration**: add to `additionalDirectories` in [settings files](/en/settings#settings-files)

214 

215Files in additional directories follow the same permission rules as the original working directory: they become readable without prompts, and file editing permissions follow the current permission mode.

216 

217### Additional directories grant file access, not configuration

218 

219Adding a directory extends where Claude can read and edit files. It does not make that directory a full configuration root: most `.claude/` configuration is not discovered from additional directories, though a few types are loaded as exceptions.

220 

221The following configuration types are loaded from `--add-dir` directories:

222 

223| Configuration | Loaded from `--add-dir` |

224| :------------------------------------------------- | :---------------------------------------------------------------- |

225| [Skills](/en/skills) in `.claude/skills/` | Yes, with live reload |

226| Plugin settings in `.claude/settings.json` | `enabledPlugins` and `extraKnownMarketplaces` only |

227| [CLAUDE.md](/en/memory) files and `.claude/rules/` | Only when `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` is set |

228 

229Everything else, including subagents, commands, output styles, hooks, and other settings, is discovered only from the current working directory and its parents, your user directory at `~/.claude/`, and managed settings. To share that configuration across projects, use one of these approaches:

230 

231* **User-level configuration**: place files in `~/.claude/agents/`, `~/.claude/output-styles/`, or `~/.claude/settings.json` to make them available in every project

232* **Plugins**: package and distribute configuration as a [plugin](/en/plugins) that teams can install

233* **Launch from the config directory**: run Claude Code from the directory containing the `.claude/` configuration you want

234 

235## How permissions interact with sandboxing

236 

237Permissions and [sandboxing](/en/sandboxing) are complementary security layers:

238 

239* **Permissions** control which tools Claude Code can use and which files or domains it can access. They apply to all tools (Bash, Read, Edit, WebFetch, MCP, and others).

240* **Sandboxing** provides OS-level enforcement that restricts the Bash tool's filesystem and network access. It applies only to Bash commands and their child processes.

241 

242Use both for defense-in-depth:

243 

244* Permission deny rules block Claude from even attempting to access restricted resources

245* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making

246* Filesystem restrictions in the sandbox use Read and Edit deny rules, not separate sandbox configuration

247* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` list

248 

249When 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.

250 

251## Managed settings

252 

253For organizations that need centralized control over Claude Code configuration, administrators can deploy managed settings that cannot be overridden by user or project settings. These policy settings follow the same format as regular settings files and can be delivered through MDM/OS-level policies, managed settings files, or [server-managed settings](/en/server-managed-settings). See [settings files](/en/settings#settings-files) for delivery mechanisms and file locations.

254 

255### Managed-only settings

256 

257The following settings are only read from managed settings. Placing them in user or project settings files has no effect.

258 

259| Setting | Description |

260| :--------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

261| `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) |

262| `allowManagedHooksOnly` | When `true`, prevents loading of user, project, and plugin hooks. Only managed hooks and SDK hooks are allowed |

263| `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) |

264| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |

265| `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) |

266| `channelsEnabled` | Allow [channels](/en/channels) for Team and Enterprise users. Unset or `false` blocks channel message delivery regardless of what users pass to `--channels` |

267| `pluginTrustMessage` | Custom message appended to the plugin trust warning shown before installation |

268| `sandbox.filesystem.allowManagedReadPathsOnly` | When `true`, only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources |

269| `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 |

270| `strictKnownMarketplaces` | Controls which plugin marketplaces users can add. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

271 

272`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.

273 

274<Note>

275 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).

276</Note>

277 

278## Review auto mode denials

279 

280When [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.

281 

282To react to denials programmatically, use the [`PermissionDenied` hook](/en/hooks#permissiondenied).

283 

284## Configure the auto mode classifier

285 

286[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.

287 

288The 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.

289 

290| Scope | File | Use for |

291| :------------------------- | :---------------------------- | :-------------------------------------------------- |

292| One developer | `~/.claude/settings.json` | Personal trusted infrastructure |

293| One project, one developer | `.claude/settings.local.json` | Per-project trusted buckets or services, gitignored |

294| Organization-wide | Managed settings | Trusted infrastructure enforced for all developers |

295 

296Entries 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.

297 

298### Define trusted infrastructure

299 

300For 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.

301 

302```json theme={null}

303{

304 "autoMode": {

305 "environment": [

306 "Source control: github.example.com/acme-corp and all repos under it",

307 "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",

308 "Trusted internal domains: *.corp.example.com, api.internal.example.com",

309 "Key internal services: Jenkins at ci.example.com, Artifactory at artifacts.example.com"

310 ]

311 }

312}

313```

314 

315Entries 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:

316 

317* **Organization**: your company name and what Claude Code is primarily used for, like software development, infrastructure automation, or data engineering

318* **Source control**: every GitHub, GitLab, or Bitbucket org your developers push to

319* **Cloud providers and trusted buckets**: bucket names or prefixes that Claude should be able to read from and write to

320* **Trusted internal domains**: hostnames for APIs, dashboards, and services inside your network, like `*.internal.example.com`

321* **Key internal services**: CI, artifact registries, internal package indexes, incident tooling

322* **Additional context**: regulated-industry constraints, multi-tenant infrastructure, or compliance requirements that affect what the classifier should treat as risky

323 

324A useful starting template: fill in the bracketed fields and remove any lines that don't apply:

325 

326```json theme={null}

327{

328 "autoMode": {

329 "environment": [

330 "Organization: {COMPANY_NAME}. Primary use: {PRIMARY_USE_CASE, e.g. software development, infrastructure automation}",

331 "Source control: {SOURCE_CONTROL, e.g. GitHub org github.example.com/acme-corp}",

332 "Cloud provider(s): {CLOUD_PROVIDERS, e.g. AWS, GCP, Azure}",

333 "Trusted cloud buckets: {TRUSTED_BUCKETS, e.g. s3://acme-builds, gs://acme-datasets}",

334 "Trusted internal domains: {TRUSTED_DOMAINS, e.g. *.internal.example.com, api.example.com}",

335 "Key internal services: {SERVICES, e.g. Jenkins at ci.example.com, Artifactory at artifacts.example.com}",

336 "Additional context: {EXTRA, e.g. regulated industry, multi-tenant infrastructure, compliance requirements}"

337 ]

338 }

339}

340```

341 

342The more specific context you give, the better the classifier can distinguish routine internal operations from exfiltration attempts.

343 

344You 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.

345 

346### Override the block and allow rules

347 

348Two 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.

349 

350Inside 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.

351 

352To 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.

353 

354```json theme={null}

355{

356 "autoMode": {

357 "environment": [

358 "Source control: github.example.com/acme-corp and all repos under it"

359 ],

360 "allow": [

361 "Deploying to the staging namespace is allowed: staging is isolated from production and resets nightly",

362 "Writing to s3://acme-scratch/ is allowed: ephemeral bucket with a 7-day lifecycle policy"

363 ],

364 "soft_deny": [

365 "Never run database migrations outside the migrations CLI, even against dev databases",

366 "Never modify files under infra/terraform/prod/: production infrastructure changes go through the review workflow",

367 "...copy full default soft_deny list here first, then add your rules..."

368 ]

369 }

370}

371```

372 

373<Danger>

374 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.

375</Danger>

376 

377The three sections are evaluated independently, so setting `environment` alone leaves the default `allow` and `soft_deny` lists intact.

378 

379### Inspect the defaults and your effective config

380 

381Because 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:

382 

383```bash theme={null}

384claude auto-mode defaults # the built-in environment, allow, and soft_deny rules

385claude auto-mode config # what the classifier actually uses: your settings where set, defaults otherwise

386claude auto-mode critique # get AI feedback on your custom allow and soft_deny rules

387```

388 

389Save 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.

390 

391## Settings precedence

392 

393Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings:

394 

3951. **Managed settings**: cannot be overridden by any other level, including command line arguments

3962. **Command line arguments**: temporary session overrides

3973. **Local project settings** (`.claude/settings.local.json`)

3984. **Shared project settings** (`.claude/settings.json`)

3995. **User settings** (`~/.claude/settings.json`)

400 

401If a tool is denied at any level, no other level can allow it. For example, a managed settings deny cannot be overridden by `--allowedTools`, and `--disallowedTools` can add restrictions beyond what managed settings define.

402 

403If a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked.

404 

405## Example configurations

406 

407This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios. Use these as starting points and adjust them to fit your needs.

408 

409## See also

410 

411* [Settings](/en/settings): complete configuration reference including the permission settings table

412* [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands

413* [Authentication](/en/authentication): set up user access to Claude Code

414* [Security](/en/security): security safeguards and best practices

415* [Hooks](/en/hooks-guide): automate workflows and extend permission evaluation

platforms.md +79 −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# Platforms and integrations

6 

7> Choose where to run Claude Code and what to connect it to. Compare the CLI, Desktop, VS Code, JetBrains, web, and integrations like Chrome, Slack, and CI/CD.

8 

9Claude Code runs the same underlying engine everywhere, but each surface is tuned for a different way of working. This page helps you pick the right platform for your workflow and connect the tools you already use.

10 

11## Where to run Claude Code

12 

13Choose a platform based on how you like to work and where your project lives.

14 

15| Platform | Best for | What you get |

16| :-------------------------------- | :------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |

17| [CLI](/en/quickstart) | Terminal workflows, scripting, remote servers | Full feature set, [Agent SDK](/en/headless), [computer use](/en/computer-use) on macOS (Pro and Max), third-party providers |

18| [Desktop](/en/desktop) | Visual review, parallel sessions, managed setup | Diff viewer, app preview, [computer use](/en/desktop#let-claude-use-your-computer) and [Dispatch](/en/desktop#sessions-from-dispatch) on Pro and Max |

19| [VS Code](/en/vs-code) | Working inside VS Code without switching to a terminal | Inline diffs, integrated terminal, file context |

20| [JetBrains](/en/jetbrains) | Working inside IntelliJ, PyCharm, WebStorm, or other JetBrains IDEs | Diff viewer, selection sharing, terminal session |

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 

23The 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.

24 

25You can mix surfaces on the same project. Configuration, project memory, and MCP servers are shared across the local surfaces.

26 

27## Connect your tools

28 

29Integrations let Claude work with services outside your codebase.

30 

31| Integration | What it does | Use it for |

32| :----------------------------------- | :------------------------------------------------- | :--------------------------------------------------------------- |

33| [Chrome](/en/chrome) | Controls your browser with your logged-in sessions | Testing web apps, filling forms, automating sites without an API |

34| [GitHub Actions](/en/github-actions) | Runs Claude in your CI pipeline | Automated PR reviews, issue triage, scheduled maintenance |

35| [GitLab CI/CD](/en/gitlab-ci-cd) | Same as GitHub Actions for GitLab | CI-driven automation on GitLab |

36| [Code Review](/en/code-review) | Reviews every PR automatically | Catching bugs before human review |

37| [Slack](/en/slack) | Responds to `@Claude` mentions in your channels | Turning bug reports into pull requests from team chat |

38 

39For integrations not listed here, [MCP servers](/en/mcp) and [connectors](/en/desktop#connect-external-tools) let you connect almost anything: Linear, Notion, Google Drive, or your own internal APIs.

40 

41## Work when you are away from your terminal

42 

43Claude Code offers several ways to work when you're not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up.

44 

45| | Trigger | Claude runs on | Setup | Best for |

46| :--------------------------------------------- | :--------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------ |

47| [Dispatch](/en/desktop#sessions-from-dispatch) | Message a task from the Claude mobile app | Your machine (Desktop) | [Pair the mobile app with Desktop](https://support.claude.com/en/articles/13947068) | Delegating work while you're away, minimal setup |

48| [Remote Control](/en/remote-control) | Drive a running session from [claude.ai/code](https://claude.ai/code) or the Claude mobile app | Your machine (CLI or VS Code) | Run `claude remote-control` | Steering in-progress work from another device |

49| [Channels](/en/channels) | Push events from a chat app like Telegram or Discord, or your own server | Your machine (CLI) | [Install a channel plugin](/en/channels#quickstart) or [build your own](/en/channels-reference) | Reacting to external events like CI failures or chat messages |

50| [Slack](/en/slack) | Mention `@Claude` in a team channel | Anthropic cloud | [Install the Slack app](/en/slack#setting-up-claude-code-in-slack) with [Claude Code on the web](/en/claude-code-on-the-web) enabled | PRs and reviews from team chat |

51| [Scheduled tasks](/en/scheduled-tasks) | Set a schedule | [CLI](/en/scheduled-tasks), [Desktop](/en/desktop-scheduled-tasks), or [cloud](/en/web-scheduled-tasks) | Pick a frequency | Recurring automation like daily reviews |

52 

53If you're not sure where to start, [install the CLI](/en/quickstart) and run it in a project directory. If you'd rather not use a terminal, [Desktop](/en/desktop-quickstart) gives you the same engine with a graphical interface.

54 

55## Related resources

56 

57### Platforms

58 

59* [CLI quickstart](/en/quickstart): install and run your first command in the terminal

60* [Desktop](/en/desktop): visual diff review, parallel sessions, computer use, and Dispatch

61* [VS Code](/en/vs-code): the Claude Code extension inside your editor

62* [JetBrains](/en/jetbrains): the extension for IntelliJ, PyCharm, and other JetBrains IDEs

63* [Claude Code on the web](/en/claude-code-on-the-web): cloud sessions that keep running when you disconnect

64 

65### Integrations

66 

67* [Chrome](/en/chrome): automate browser tasks with your logged-in sessions

68* [Computer use](/en/computer-use): let Claude open apps and control your screen on macOS

69* [GitHub Actions](/en/github-actions): run Claude in your CI pipeline

70* [GitLab CI/CD](/en/gitlab-ci-cd): the same for GitLab

71* [Code Review](/en/code-review): automatic review on every pull request

72* [Slack](/en/slack): send tasks from team chat, get PRs back

73 

74### Remote access

75 

76* [Dispatch](/en/desktop#sessions-from-dispatch): message a task from your phone and it can spawn a Desktop session

77* [Remote Control](/en/remote-control): drive a running session from your phone or browser

78* [Channels](/en/channels): push events from chat apps or your own servers into a session

79* [Scheduled tasks](/en/scheduled-tasks): run prompts on a recurring schedule

Details

1# Plugin marketplaces1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Create and manage plugin marketplaces to distribute Claude Code extensions across teams and communities.5# Create and distribute a plugin marketplace

4 6 

5Plugin marketplaces are catalogs of available plugins that make it easy to discover, install, and manage Claude Code extensions. This guide shows you how to use existing marketplaces and create your own for team distribution.7> Build and host plugin marketplaces to distribute Claude Code extensions across teams and communities.

6 8 

7## Overview9A **plugin marketplace** is a catalog that lets you distribute plugins to others. Marketplaces provide centralized discovery, version tracking, automatic updates, and support for multiple source types (git repositories, local paths, and more). This guide shows you how to create your own marketplace to share plugins with your team or community.

8 10 

9A marketplace is a JSON file that lists available plugins and describes where to find them. Marketplaces provide:11Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/en/discover-plugins).

10 12 

11* **Centralized discovery**: Browse plugins from multiple sources in one place13## Overview

12* **Version management**: Track and update plugin versions automatically

13* **Team distribution**: Share required plugins across your organization

14* **Flexible sources**: Support for git repositories, GitHub repos, local paths, and package managers

15 14 

16### Prerequisites15Creating and distributing a marketplace involves:

17 16 

18* Claude Code installed and running171. **Creating plugins**: build one or more plugins with commands, agents, hooks, MCP servers, or LSP servers. This guide assumes you already have plugins to distribute; see [Create plugins](/en/plugins) for details on how to create them.

19* Basic familiarity with JSON file format182. **Creating a marketplace file**: define a `marketplace.json` that lists your plugins and where to find them (see [Create the marketplace file](#create-the-marketplace-file)).

20* For creating marketplaces: Git repository or local development environment193. **Host the marketplace**: push to GitHub, GitLab, or another git host (see [Host and distribute marketplaces](#host-and-distribute-marketplaces)).

204. **Share with users**: users add your marketplace with `/plugin marketplace add` and install individual plugins (see [Discover and install plugins](/en/discover-plugins)).

21 21 

22## Add and use marketplaces22Once your marketplace is live, you can update it by pushing changes to your repository. Users refresh their local copy with `/plugin marketplace update`.

23 23 

24Add marketplaces using the `/plugin marketplace` commands to access plugins from different sources:24## Walkthrough: create a local marketplace

25 25 

26### Add GitHub marketplaces26This 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```shell Add a GitHub repository containing .claude-plugin/marketplace.json theme={null}28<Steps>

29/plugin marketplace add owner/repo29 <Step title="Create the directory structure">

30```30 ```bash theme={null}

31 mkdir -p my-marketplace/.claude-plugin

32 mkdir -p my-marketplace/plugins/quality-review-plugin/.claude-plugin

33 mkdir -p my-marketplace/plugins/quality-review-plugin/skills/quality-review

34 ```

35 </Step>

31 36 

32### Add Git repositories37 <Step title="Create the skill">

38 Create a `SKILL.md` file that defines what the `/quality-review` skill does.

33 39 

34```shell Add any git repository theme={null}40 ```markdown my-marketplace/plugins/quality-review-plugin/skills/quality-review/SKILL.md theme={null}

35/plugin marketplace add https://gitlab.com/company/plugins.git41 ---

36```42 description: Review code for bugs, security, and performance

43 disable-model-invocation: true

44 ---

37 45 

38### Add local marketplaces for development46 Review the code I've selected or the recent changes for:

47 - Potential bugs or edge cases

48 - Security concerns

49 - Performance issues

50 - Readability improvements

39 51 

40```shell Add local directory containing .claude-plugin/marketplace.json theme={null}52 Be concise and actionable.

41/plugin marketplace add ./my-marketplace53 ```

42```54 </Step>

43 55 

44```shell Add direct path to marketplace.json file theme={null}56 <Step title="Create the plugin manifest">

45/plugin marketplace add ./path/to/marketplace.json57 Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory.

46```

47 

48```shell Add remote marketplace.json via URL theme={null}

49/plugin marketplace add https://url.of/marketplace.json

50```

51 

52### Install plugins from marketplaces

53 

54Once you've added marketplaces, install plugins directly:

55 

56```shell Install from any known marketplace theme={null}

57/plugin install plugin-name@marketplace-name

58```

59 58 

60```shell Browse available plugins interactively theme={null}59 ```json my-marketplace/plugins/quality-review-plugin/.claude-plugin/plugin.json theme={null}

61/plugin60 {

62```61 "name": "quality-review-plugin",

63 62 "description": "Adds a /quality-review skill for quick code reviews",

64### Verify marketplace installation63 "version": "1.0.0"

65 64 }

66After adding a marketplace:65 ```

67 66 </Step>

681. **List marketplaces**: Run `/plugin marketplace list` to confirm it's added

692. **Browse plugins**: Use `/plugin` to see available plugins from your marketplace

703. **Test installation**: Try installing a plugin to verify the marketplace works correctly

71 

72## Configure team marketplaces

73 67 

74Set up automatic marketplace installation for team projects by specifying required marketplaces in `.claude/settings.json`:68 <Step title="Create the marketplace file">

69 Create the marketplace catalog that lists your plugin.

75 70 

76```json theme={null}71 ```json my-marketplace/.claude-plugin/marketplace.json theme={null}

77{72 {

78 "extraKnownMarketplaces": {73 "name": "my-plugins",

79 "team-tools": {74 "owner": {

80 "source": {75 "name": "Your Name"

81 "source": "github",

82 "repo": "your-org/claude-plugins"

83 }

84 },76 },

85 "project-specific": {77 "plugins": [

86 "source": {78 {

87 "source": "git",79 "name": "quality-review-plugin",

88 "url": "https://git.company.com/project-plugins.git"80 "source": "./plugins/quality-review-plugin",

89 }81 "description": "Adds a /quality-review skill for quick code reviews"

90 }82 }

83 ]

91 }84 }

92}85 ```

93```86 </Step>

94 87 

95When team members trust the repository folder, Claude Code automatically installs these marketplaces and any plugins specified in the `enabledPlugins` field.88 <Step title="Add and install">

89 Add the marketplace and install the plugin.

96 90 

97***91 ```shell theme={null}

92 /plugin marketplace add ./my-marketplace

93 /plugin install quality-review-plugin@my-plugins

94 ```

95 </Step>

98 96 

99## Create your own marketplace97 <Step title="Try it out">

98 Select some code in your editor and run your new command.

100 99 

101Build and distribute custom plugin collections for your team or community.100 ```shell theme={null}

101 /quality-review

102 ```

103 </Step>

104</Steps>

102 105 

103### Prerequisites for marketplace creation106To learn more about what plugins can do, including hooks, agents, MCP servers, and LSP servers, see [Plugins](/en/plugins).

104 107 

105* Git repository (GitHub, GitLab, or other git hosting)108<Note>

106* Understanding of JSON file format109 **How plugins are installed**: When users install a plugin, Claude Code copies the plugin directory to a cache location. This means plugins can't reference files outside their directory using paths like `../shared-utils`, because those files won't be copied.

107* One or more plugins to distribute

108 110 

109### Create the marketplace file111 If you need to share files across plugins, use symlinks (which are followed during copying). See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for details.

112</Note>

110 113 

111Create `.claude-plugin/marketplace.json` in your repository root:114## Create the marketplace file

115 

116Create `.claude-plugin/marketplace.json` in your repository root. This file defines your marketplace's name, owner information, and a list of plugins with their sources.

117 

118Each plugin entry needs at minimum a `name` and `source` (where to fetch it from). See the [full schema](#marketplace-schema) below for all available fields.

112 119 

113```json theme={null}120```json theme={null}

114{121{

115 "name": "company-tools",122 "name": "company-tools",

116 "owner": {123 "owner": {

117 "name": "DevTools Team",124 "name": "DevTools Team",

118 "email": "devtools@company.com"125 "email": "devtools@example.com"

119 },126 },

120 "plugins": [127 "plugins": [

121 {128 {


139}146}

140```147```

141 148 

142### Marketplace schema149## Marketplace schema

143 150 

144#### Required fields151### Required fields

145 152 

146| Field | Type | Description |153| Field | Type | Description | Example |

147| :-------- | :----- | :--------------------------------------------- |154| :-------- | :----- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------- |

148| `name` | string | Marketplace identifier (kebab-case, no spaces) |155| `name` | string | Marketplace identifier (kebab-case, no spaces). This is public-facing: users see it when installing plugins (for example, `/plugin install my-tool@your-marketplace`). | `"acme-tools"` |

149| `owner` | object | Marketplace maintainer information |156| `owner` | object | Marketplace maintainer information ([see fields below](#owner-fields)) | |

150| `plugins` | array | List of available plugins |157| `plugins` | array | List of available plugins | See below |

158 

159<Note>

160 **Reserved names**: The following marketplace names are reserved for official Anthropic use and cannot be used by third-party marketplaces: `claude-code-marketplace`, `claude-code-plugins`, `claude-plugins-official`, `anthropic-marketplace`, `anthropic-plugins`, `agent-skills`, `knowledge-work-plugins`, `life-sciences`. Names that impersonate official marketplaces (like `official-claude-plugins` or `anthropic-tools-v2`) are also blocked.

161</Note>

151 162 

152#### Optional metadata163### Owner fields

164 

165| Field | Type | Required | Description |

166| :------ | :----- | :------- | :------------------------------- |

167| `name` | string | Yes | Name of the maintainer or team |

168| `email` | string | No | Contact email for the maintainer |

169 

170### Optional metadata

153 171 

154| Field | Type | Description |172| Field | Type | Description |

155| :--------------------- | :----- | :------------------------------------ |173| :--------------------- | :----- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

156| `metadata.description` | string | Brief marketplace description |174| `metadata.description` | string | Brief marketplace description |

157| `metadata.version` | string | Marketplace version |175| `metadata.version` | string | Marketplace version |

158| `metadata.pluginRoot` | string | Base path for relative plugin sources |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"`) |

159 177 

160### Plugin entries178## Plugin entries

161 179 

162<Note>180Each plugin entry in the `plugins` array describes a plugin and where to find it. You can include any field from the [plugin manifest schema](/en/plugins-reference#plugin-manifest-schema) (like `description`, `version`, `author`, `commands`, `hooks`, etc.), plus these marketplace-specific fields: `source`, `category`, `tags`, and `strict`.

163 Plugin entries are based on the *plugin manifest schema* (with all fields made optional) plus marketplace-specific fields (`source`, `category`, `tags`, `strict`), with `name` being required.

164</Note>

165 181 

166**Required fields:**182### Required fields

167 183 

168| Field | Type | Description |184| Field | Type | Description |

169| :------- | :------------- | :---------------------------------------- |185| :------- | :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

170| `name` | string | Plugin identifier (kebab-case, no spaces) |186| `name` | string | Plugin identifier (kebab-case, no spaces). This is public-facing: users see it when installing (for example, `/plugin install my-plugin@marketplace`). |

171| `source` | string\|object | Where to fetch the plugin from |187| `source` | string\|object | Where to fetch the plugin from (see [Plugin sources](#plugin-sources) below) |

172 188 

173#### Optional plugin fields189### Optional plugin fields

174 190 

175**Standard metadata fields:**191**Standard metadata fields:**

176 192 

177| Field | Type | Description |193| Field | Type | Description |

178| :------------ | :------ | :---------------------------------------------------------------- |194| :------------ | :------ | :-------------------------------------------------------------------------------------------------------------------------------- |

179| `description` | string | Brief plugin description |195| `description` | string | Brief plugin description |

180| `version` | string | Plugin version |196| `version` | string | Plugin version |

181| `author` | object | Plugin author information |197| `author` | object | Plugin author information (`name` required, `email` optional) |

182| `homepage` | string | Plugin homepage or documentation URL |198| `homepage` | string | Plugin homepage or documentation URL |

183| `repository` | string | Source code repository URL |199| `repository` | string | Source code repository URL |

184| `license` | string | SPDX license identifier (e.g., MIT, Apache-2.0) |200| `license` | string | SPDX license identifier (for example, MIT, Apache-2.0) |

185| `keywords` | array | Tags for plugin discovery and categorization |201| `keywords` | array | Tags for plugin discovery and categorization |

186| `category` | string | Plugin category for organization |202| `category` | string | Plugin category for organization |

187| `tags` | array | Tags for searchability |203| `tags` | array | Tags for searchability |

188| `strict` | boolean | Require plugin.json in plugin folder (default: true) <sup>1</sup> |204| `strict` | boolean | Controls whether `plugin.json` is the authority for component definitions (default: true). See [Strict mode](#strict-mode) below. |

189 205 

190**Component configuration fields:**206**Component configuration fields:**

191 207 


195| `agents` | string\|array | Custom paths to agent files |211| `agents` | string\|array | Custom paths to agent files |

196| `hooks` | string\|object | Custom hooks configuration or path to hooks file |212| `hooks` | string\|object | Custom hooks configuration or path to hooks file |

197| `mcpServers` | string\|object | MCP server configurations or path to MCP config |213| `mcpServers` | string\|object | MCP server configurations or path to MCP config |

214| `lspServers` | string\|object | LSP server configurations or path to LSP config |

215 

216## Plugin sources

198 217 

199*<sup>1 - When `strict: true` (default), the plugin must include a `plugin.json` manifest file, and marketplace fields supplement those values. When `strict: false`, the plugin.json is optional. If it's missing, the marketplace entry serves as the complete plugin manifest.</sup>*218Plugin sources tell Claude Code where to fetch each individual plugin listed in your marketplace. These are set in the `source` field of each plugin entry in `marketplace.json`.

200 219 

201### Plugin sources220Once a plugin is cloned or copied into the local machine, it is copied into the local versioned plugin cache at `~/.claude/plugins/cache`.

202 221 

203#### Relative paths222| Source | Type | Fields | Notes |

223| ------------- | ------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |

224| Relative path | `string` (e.g. `"./my-plugin"`) | none | Local directory within the marketplace repo. Must start with `./`. Resolved relative to the marketplace root, not the `.claude-plugin/` directory |

225| `github` | object | `repo`, `ref?`, `sha?` | |

226| `url` | object | `url`, `ref?`, `sha?` | Git URL source |

227| `git-subdir` | object | `url`, `path`, `ref?`, `sha?` | Subdirectory within a git repo. Clones sparsely to minimize bandwidth for monorepos |

228| `npm` | object | `package`, `version?`, `registry?` | Installed via `npm install` |

204 229 

205For plugins in the same repository:230<Note>

231 **Marketplace sources vs plugin sources**: These are different concepts that control different things.

232 

233 * **Marketplace source** — where to fetch the `marketplace.json` catalog itself. Set when users run `/plugin marketplace add` or in `extraKnownMarketplaces` settings. Supports `ref` (branch/tag) but not `sha`.

234 * **Plugin source** — where to fetch an individual plugin listed in the marketplace. Set in the `source` field of each plugin entry inside `marketplace.json`. Supports both `ref` (branch/tag) and `sha` (exact commit).

235 

236 For example, a marketplace hosted at `acme-corp/plugin-catalog` (marketplace source) can list a plugin fetched from `acme-corp/code-formatter` (plugin source). The marketplace source and plugin source point to different repositories and are pinned independently.

237</Note>

238 

239### Relative paths

240 

241For plugins in the same repository, use a path starting with `./`:

206 242 

207```json theme={null}243```json theme={null}

208{244{


211}247}

212```248```

213 249 

214#### GitHub repositories250Paths resolve relative to the marketplace root, which is the directory containing `.claude-plugin/`. In the example above, `./plugins/my-plugin` points to `<repo>/plugins/my-plugin`, even though `marketplace.json` lives at `<repo>/.claude-plugin/marketplace.json`. Do not use `../` to reference paths outside the marketplace root.

251 

252<Note>

253 Relative paths only work when users add your marketplace via Git (GitHub, GitLab, or git URL). If users add your marketplace via a direct URL to the `marketplace.json` file, relative paths will not resolve correctly. For URL-based distribution, use GitHub, npm, or git URL sources instead. See [Troubleshooting](#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.

254</Note>

255 

256### GitHub repositories

215 257 

216```json theme={null}258```json theme={null}

217{259{


223}265}

224```266```

225 267 

226#### Git repositories268You can pin to a specific branch, tag, or commit:

269 

270```json theme={null}

271{

272 "name": "github-plugin",

273 "source": {

274 "source": "github",

275 "repo": "owner/plugin-repo",

276 "ref": "v2.0.0",

277 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

278 }

279}

280```

281 

282| Field | Type | Description |

283| :----- | :----- | :-------------------------------------------------------------------- |

284| `repo` | string | Required. GitHub repository in `owner/repo` format |

285| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

286| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

287 

288### Git repositories

227 289 

228```json theme={null}290```json theme={null}

229{291{


235}297}

236```298```

237 299 

238#### Advanced plugin entries300You can pin to a specific branch, tag, or commit:

301 

302```json theme={null}

303{

304 "name": "git-plugin",

305 "source": {

306 "source": "url",

307 "url": "https://gitlab.com/team/plugin.git",

308 "ref": "main",

309 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

310 }

311}

312```

313 

314| Field | Type | Description |

315| :---- | :----- | :------------------------------------------------------------------------------------------------------------------------------------------------------- |

316| `url` | string | Required. Full git repository URL (`https://` or `git@`). The `.git` suffix is optional, so Azure DevOps and AWS CodeCommit URLs without the suffix work |

317| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

318| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

319 

320### Git subdirectories

321 

322Use `git-subdir` to point to a plugin that lives inside a subdirectory of a git repository. Claude Code uses a sparse, partial clone to fetch only the subdirectory, minimizing bandwidth for large monorepos.

323 

324```json theme={null}

325{

326 "name": "my-plugin",

327 "source": {

328 "source": "git-subdir",

329 "url": "https://github.com/acme-corp/monorepo.git",

330 "path": "tools/claude-plugin"

331 }

332}

333```

334 

335You can pin to a specific branch, tag, or commit:

336 

337```json theme={null}

338{

339 "name": "my-plugin",

340 "source": {

341 "source": "git-subdir",

342 "url": "https://github.com/acme-corp/monorepo.git",

343 "path": "tools/claude-plugin",

344 "ref": "v2.0.0",

345 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

346 }

347}

348```

349 

350The `url` field also accepts a GitHub shorthand (`owner/repo`) or SSH URLs (`git@github.com:owner/repo.git`).

351 

352| Field | Type | Description |

353| :----- | :----- | :------------------------------------------------------------------------------------------------------- |

354| `url` | string | Required. Git repository URL, GitHub `owner/repo` shorthand, or SSH URL |

355| `path` | string | Required. Subdirectory path within the repo containing the plugin (for example, `"tools/claude-plugin"`) |

356| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

357| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

358 

359### npm packages

360 

361Plugins distributed as npm packages are installed using `npm install`. This works with any package on the public npm registry or a private registry your team hosts.

362 

363```json theme={null}

364{

365 "name": "my-npm-plugin",

366 "source": {

367 "source": "npm",

368 "package": "@acme/claude-plugin"

369 }

370}

371```

372 

373To pin to a specific version, add the `version` field:

374 

375```json theme={null}

376{

377 "name": "my-npm-plugin",

378 "source": {

379 "source": "npm",

380 "package": "@acme/claude-plugin",

381 "version": "2.1.0"

382 }

383}

384```

385 

386To install from a private or internal registry, add the `registry` field:

387 

388```json theme={null}

389{

390 "name": "my-npm-plugin",

391 "source": {

392 "source": "npm",

393 "package": "@acme/claude-plugin",

394 "version": "^2.0.0",

395 "registry": "https://npm.example.com"

396 }

397}

398```

399 

400| Field | Type | Description |

401| :--------- | :----- | :------------------------------------------------------------------------------------------- |

402| `package` | string | Required. Package name or scoped package (for example, `@org/plugin`) |

403| `version` | string | Optional. Version or version range (for example, `2.1.0`, `^2.0.0`, `~1.5.0`) |

404| `registry` | string | Optional. Custom npm registry URL. Defaults to the system npm registry (typically npmjs.org) |

239 405 

240Plugin entries can override default component locations and provide additional metadata. Note that `${CLAUDE_PLUGIN_ROOT}` is an environment variable that resolves to the plugin's installation directory (for details see [Environment variables](/en/docs/claude-code/plugins-reference#environment-variables)):406### Advanced plugin entries

407 

408This example shows a plugin entry using many of the optional fields, including custom paths for commands, agents, hooks, and MCP servers:

241 409 

242```json theme={null}410```json theme={null}

243{411{


250 "version": "2.1.0",418 "version": "2.1.0",

251 "author": {419 "author": {

252 "name": "Enterprise Team",420 "name": "Enterprise Team",

253 "email": "enterprise@company.com"421 "email": "enterprise@example.com"

254 },422 },

255 "homepage": "https://docs.company.com/plugins/enterprise-tools",423 "homepage": "https://docs.example.com/plugins/enterprise-tools",

256 "repository": "https://github.com/company/enterprise-plugin",424 "repository": "https://github.com/company/enterprise-plugin",

257 "license": "MIT",425 "license": "MIT",

258 "keywords": ["enterprise", "workflow", "automation"],426 "keywords": ["enterprise", "workflow", "automation"],


262 "./commands/enterprise/",430 "./commands/enterprise/",

263 "./commands/experimental/preview.md"431 "./commands/experimental/preview.md"

264 ],432 ],

265 "agents": [433 "agents": ["./agents/security-reviewer.md", "./agents/compliance-checker.md"],

266 "./agents/security-reviewer.md",

267 "./agents/compliance-checker.md"

268 ],

269 "hooks": {434 "hooks": {

270 "PostToolUse": [435 "PostToolUse": [

271 {436 {

272 "matcher": "Write|Edit",437 "matcher": "Write|Edit",

273 "hooks": [{"type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"}]438 "hooks": [

439 {

440 "type": "command",

441 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"

442 }

443 ]

274 }444 }

275 ]445 ]

276 },446 },


284}454}

285```455```

286 456 

287<Note>457Key things to notice:

288 **Schema relationship**: Plugin entries use the plugin manifest schema with all fields made optional, plus marketplace-specific fields (`source`, `strict`, `category`, `tags`). This means any field valid in a `plugin.json` file can also be used in a marketplace entry. When `strict: false`, the marketplace entry serves as the complete plugin manifest if no `plugin.json` exists. When `strict: true` (default), marketplace fields supplement the plugin's own manifest file.

289</Note>

290 458 

291***459* **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root.

460* **`${CLAUDE_PLUGIN_ROOT}`**: use this variable in hooks and MCP server configs to reference files within the plugin's installation directory. This is necessary because plugins are copied to a cache location when installed. For dependencies or state that should survive plugin updates, use [`${CLAUDE_PLUGIN_DATA}`](/en/plugins-reference#persistent-data-directory) instead.

461* **`strict: false`**: Since this is set to false, the plugin doesn't need its own `plugin.json`. The marketplace entry defines everything. See [Strict mode](#strict-mode) below.

292 462 

293## Host and distribute marketplaces463### Strict mode

464 

465The `strict` field controls whether `plugin.json` is the authority for component definitions (commands, agents, hooks, skills, MCP servers, output styles).

466 

467| Value | Behavior |

468| :--------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |

469| `true` (default) | `plugin.json` is the authority. The marketplace entry can supplement it with additional components, and both sources are merged. |

470| `false` | The marketplace entry is the entire definition. If the plugin also has a `plugin.json` that declares components, that's a conflict and the plugin fails to load. |

471 

472**When to use each mode:**

473 

474* **`strict: true`**: the plugin has its own `plugin.json` and manages its own components. The marketplace entry can add extra commands or hooks on top. This is the default and works for most plugins.

475* **`strict: false`**: the marketplace operator wants full control. The plugin repo provides raw files, and the marketplace entry defines which of those files are exposed as commands, agents, hooks, etc. Useful when the marketplace restructures or curates a plugin's components differently than the plugin author intended.

294 476 

295Choose the best hosting strategy for your plugin distribution needs.477## Host and distribute marketplaces

296 478 

297### Host on GitHub (recommended)479### Host on GitHub (recommended)

298 480 


300 482 

3011. **Create a repository**: Set up a new repository for your marketplace4831. **Create a repository**: Set up a new repository for your marketplace

3022. **Add marketplace file**: Create `.claude-plugin/marketplace.json` with your plugin definitions4842. **Add marketplace file**: Create `.claude-plugin/marketplace.json` with your plugin definitions

3033. **Share with teams**: Team members add with `/plugin marketplace add owner/repo`4853. **Share with teams**: Users add your marketplace with `/plugin marketplace add owner/repo`

304 486 

305**Benefits**: Built-in version control, issue tracking, and team collaboration features.487**Benefits**: Built-in version control, issue tracking, and team collaboration features.

306 488 

307### Host on other git services489### Host on other git services

308 490 

309Any git hosting service works for marketplace distribution, using a URL to an arbitrary git repository.491Any git hosting service works, such as GitLab, Bitbucket, and self-hosted servers. Users add with the full repository URL:

310 

311For example, using GitLab:

312 492 

313```shell theme={null}493```shell theme={null}

314/plugin marketplace add https://gitlab.com/company/plugins.git494/plugin marketplace add https://gitlab.com/company/plugins.git

315```495```

316 496 

317### Use local marketplaces for development497### Private repositories

318 498 

319Test your marketplace locally before distribution:499Claude 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`.

320 500 

321```shell Add local marketplace for testing theme={null}501Background 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:

322/plugin marketplace add ./my-local-marketplace502 

503| Provider | Environment variables | Notes |

504| :-------- | :--------------------------- | :---------------------------------------- |

505| GitHub | `GITHUB_TOKEN` or `GH_TOKEN` | Personal access token or GitHub App token |

506| GitLab | `GITLAB_TOKEN` or `GL_TOKEN` | Personal access token or project token |

507| Bitbucket | `BITBUCKET_TOKEN` | App password or repository access token |

508 

509Set the token in your shell configuration (for example, `.bashrc`, `.zshrc`) or pass it when running Claude Code:

510 

511```bash theme={null}

512export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

323```513```

324 514 

325```shell Test plugin installation theme={null}515<Note>

516 For CI/CD environments, configure the token as a secret environment variable. GitHub Actions automatically provides `GITHUB_TOKEN` for repositories in the same organization.

517</Note>

518 

519### Test locally before distribution

520 

521Test your marketplace locally before sharing:

522 

523```shell theme={null}

524/plugin marketplace add ./my-local-marketplace

326/plugin install test-plugin@my-local-marketplace525/plugin install test-plugin@my-local-marketplace

327```526```

328 527 

329## Manage marketplace operations528For the full range of add commands (GitHub, Git URLs, local paths, remote URLs), see [Add marketplaces](/en/discover-plugins#add-marketplaces).

330 529 

331### List known marketplaces530### Require marketplaces for your team

332 531 

333```shell List all configured marketplaces theme={null}532You can configure your repository so team members are automatically prompted to install your marketplace when they trust the project folder. Add your marketplace to `.claude/settings.json`:

334/plugin marketplace list533 

534```json theme={null}

535{

536 "extraKnownMarketplaces": {

537 "company-tools": {

538 "source": {

539 "source": "github",

540 "repo": "your-org/claude-plugins"

541 }

542 }

543 }

544}

335```545```

336 546 

337Shows all configured marketplaces with their sources and status.547You can also specify which plugins should be enabled by default:

548 

549```json theme={null}

550{

551 "enabledPlugins": {

552 "code-formatter@company-tools": true,

553 "deployment-tools@company-tools": true

554 }

555}

556```

338 557 

339### Update marketplace metadata558For full configuration options, see [Plugin settings](/en/settings#plugin-settings).

559 

560<Note>

561 If you use a local `directory` or `file` source with a relative path, the path resolves against your repository's main checkout. When you run Claude Code from a git worktree, the path still points at the main checkout, so all worktrees share the same marketplace location. Marketplace state is stored once per user in `~/.claude/plugins/known_marketplaces.json`, not per project.

562</Note>

563 

564### Pre-populate plugins for containers

565 

566For container images and CI environments, you can pre-populate a plugins directory at build time so Claude Code starts with marketplaces and plugins already available, without cloning anything at runtime. Set the `CLAUDE_CODE_PLUGIN_SEED_DIR` environment variable to point at this directory.

567 

568To layer multiple seed directories, separate paths with `:` on Unix or `;` on Windows. Claude Code searches each directory in order, and the first seed that contains a given marketplace or plugin cache wins.

569 

570The seed directory mirrors the structure of `~/.claude/plugins`:

340 571 

341```shell Refresh marketplace metadata theme={null}

342/plugin marketplace update marketplace-name

343```572```

573$CLAUDE_CODE_PLUGIN_SEED_DIR/

574 known_marketplaces.json

575 marketplaces/<name>/...

576 cache/<marketplace>/<plugin>/<version>/...

577```

578 

579To build a seed directory, run Claude Code once during image build, install the plugins you need, then copy the resulting `~/.claude/plugins` directory into your image and point `CLAUDE_CODE_PLUGIN_SEED_DIR` at it.

580 

581To skip the copy step, set `CLAUDE_CODE_PLUGIN_CACHE_DIR` to your target seed path during the build so plugins install directly there:

582 

583```bash theme={null}

584CLAUDE_CODE_PLUGIN_CACHE_DIR=/opt/claude-seed claude plugin marketplace add your-org/plugins

585CLAUDE_CODE_PLUGIN_CACHE_DIR=/opt/claude-seed claude plugin install my-tool@your-plugins

586```

587 

588Then set `CLAUDE_CODE_PLUGIN_SEED_DIR=/opt/claude-seed` in your container's runtime environment so Claude Code reads from the seed on startup.

344 589 

345Refreshes plugin listings and metadata from the marketplace source.590At startup, Claude Code registers marketplaces found in the seed's `known_marketplaces.json` into the primary configuration, and uses plugin caches found under `cache/` in place without re-cloning. This works in both interactive mode and non-interactive mode with the `-p` flag.

346 591 

347### Remove a marketplace592Behavior details:

348 593 

349```shell Remove a marketplace theme={null}594* **Read-only**: the seed directory is never written to. Auto-updates are disabled for seed marketplaces since git pull would fail on a read-only filesystem.

350/plugin marketplace remove marketplace-name595* **Seed entries take precedence**: marketplaces declared in the seed overwrite any matching entries in the user's configuration on each startup. To opt out of a seed plugin, use `/plugin disable` rather than removing the marketplace.

596* **Path resolution**: Claude Code locates marketplace content by probing `$CLAUDE_CODE_PLUGIN_SEED_DIR/marketplaces/<name>/` at runtime, not by trusting paths stored inside the seed's JSON. This means the seed works correctly even when mounted at a different path than where it was built.

597* **Mutation is blocked**: running `/plugin marketplace remove` or `/plugin marketplace update` against a seed-managed marketplace fails with guidance to ask your administrator to update the seed image.

598* **Composes with settings**: if `extraKnownMarketplaces` or `enabledPlugins` declare a marketplace that already exists in the seed, Claude Code uses the seed copy instead of cloning.

599 

600### Managed marketplace restrictions

601 

602For organizations requiring strict control over plugin sources, administrators can restrict which plugin marketplaces users are allowed to add using the [`strictKnownMarketplaces`](/en/settings#strictknownmarketplaces) setting in managed settings.

603 

604When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value:

605 

606| Value | Behavior |

607| ------------------- | ---------------------------------------------------------------- |

608| Undefined (default) | No restrictions. Users can add any marketplace |

609| Empty array `[]` | Complete lockdown. Users cannot add any new marketplaces |

610| List of sources | Users can only add marketplaces that match the allowlist exactly |

611 

612#### Common configurations

613 

614Disable all marketplace additions:

615 

616```json theme={null}

617{

618 "strictKnownMarketplaces": []

619}

351```620```

352 621 

353Removes the marketplace from your configuration.622Allow specific marketplaces only:

623 

624```json theme={null}

625{

626 "strictKnownMarketplaces": [

627 {

628 "source": "github",

629 "repo": "acme-corp/approved-plugins"

630 },

631 {

632 "source": "github",

633 "repo": "acme-corp/security-tools",

634 "ref": "v2.0"

635 },

636 {

637 "source": "url",

638 "url": "https://plugins.example.com/marketplace.json"

639 }

640 ]

641}

642```

643 

644Allow all marketplaces from an internal git server using regex pattern matching on the host. This is the recommended approach for [GitHub Enterprise Server](/en/github-enterprise-server#plugin-marketplaces-on-ghes) or self-hosted GitLab instances:

645 

646```json theme={null}

647{

648 "strictKnownMarketplaces": [

649 {

650 "source": "hostPattern",

651 "hostPattern": "^github\\.example\\.com$"

652 }

653 ]

654}

655```

656 

657Allow filesystem-based marketplaces from a specific directory using regex pattern matching on the path:

658 

659```json theme={null}

660{

661 "strictKnownMarketplaces": [

662 {

663 "source": "pathPattern",

664 "pathPattern": "^/opt/approved/"

665 }

666 ]

667}

668```

669 

670Use `".*"` as the `pathPattern` to allow any filesystem path while still controlling network sources with `hostPattern`.

671 

672<Note>

673 `strictKnownMarketplaces` restricts what users can add, but does not register marketplaces on its own. To make allowed marketplaces available automatically without users running `/plugin marketplace add`, pair it with [`extraKnownMarketplaces`](/en/settings#extraknownmarketplaces) in the same `managed-settings.json`. See [Using both together](/en/settings#strictknownmarketplaces).

674</Note>

675 

676#### How restrictions work

677 

678Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.

679 

680The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly:

681 

682* For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist

683* For URL sources: the full URL must match exactly

684* For `hostPattern` sources: the marketplace host is matched against the regex pattern

685* For `pathPattern` sources: the marketplace's filesystem path is matched against the regex pattern

686 

687Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.

688 

689For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).

690 

691### Version resolution and release channels

692 

693Plugin 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`).

694 

695<Warning>

696 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.

697</Warning>

698 

699#### Set up release channels

700 

701To 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).

354 702 

355<Warning>703<Warning>

356 Removing a marketplace will uninstall any plugins you installed from it.704 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.

357</Warning>705</Warning>

358 706 

359***707##### Example

708 

709```json theme={null}

710{

711 "name": "stable-tools",

712 "plugins": [

713 {

714 "name": "code-formatter",

715 "source": {

716 "source": "github",

717 "repo": "acme-corp/code-formatter",

718 "ref": "stable"

719 }

720 }

721 ]

722}

723```

724 

725```json theme={null}

726{

727 "name": "latest-tools",

728 "plugins": [

729 {

730 "name": "code-formatter",

731 "source": {

732 "source": "github",

733 "repo": "acme-corp/code-formatter",

734 "ref": "latest"

735 }

736 }

737 ]

738}

739```

740 

741##### Assign channels to user groups

742 

743Assign each marketplace to the appropriate user group through managed settings. For example, the stable group receives:

744 

745```json theme={null}

746{

747 "extraKnownMarketplaces": {

748 "stable-tools": {

749 "source": {

750 "source": "github",

751 "repo": "acme-corp/stable-tools"

752 }

753 }

754 }

755}

756```

757 

758The early-access group receives `latest-tools` instead:

759 

760```json theme={null}

761{

762 "extraKnownMarketplaces": {

763 "latest-tools": {

764 "source": {

765 "source": "github",

766 "repo": "acme-corp/latest-tools"

767 }

768 }

769 }

770}

771```

360 772 

361## Troubleshooting marketplaces773## Validation and testing

362 774 

363### Common marketplace issues775Test your marketplace before sharing.

364 776 

365#### Marketplace not loading777Validate your marketplace JSON syntax:

778 

779```bash theme={null}

780claude plugin validate .

781```

782 

783Or from within Claude Code:

784 

785```shell theme={null}

786/plugin validate .

787```

788 

789Add the marketplace for testing:

790 

791```shell theme={null}

792/plugin marketplace add ./path/to/marketplace

793```

794 

795Install a test plugin to verify everything works:

796 

797```shell theme={null}

798/plugin install test-plugin@marketplace-name

799```

800 

801For complete plugin testing workflows, see [Test your plugins locally](/en/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/en/plugins-reference).

802 

803## Manage marketplaces from the CLI

804 

805Claude Code provides non-interactive `claude plugin marketplace` subcommands for scripting and automation. These are equivalent to the `/plugin marketplace` commands available inside an interactive session.

806 

807### Plugin marketplace add

808 

809Add a marketplace from a GitHub repository, git URL, remote URL, or local path.

810 

811```bash theme={null}

812claude plugin marketplace add <source> [options]

813```

814 

815**Arguments:**

816 

817* `<source>`: GitHub `owner/repo` shorthand, git URL, remote URL to a `marketplace.json` file, or local directory path. To pin to a branch or tag, append `@ref` to the GitHub shorthand or `#ref` to a git URL

818 

819**Options:**

820 

821| Option | Description | Default |

822| :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- | :------ |

823| `--scope <scope>` | Where to declare the marketplace: `user`, `project`, or `local`. See [Plugin installation scopes](/en/plugins-reference#plugin-installation-scopes) | `user` |

824| `--sparse <paths...>` | Limit checkout to specific directories via git sparse-checkout. Useful for monorepos | |

825 

826Add a marketplace from GitHub using `owner/repo` shorthand:

827 

828```bash theme={null}

829claude plugin marketplace add acme-corp/claude-plugins

830```

831 

832Pin to a specific branch or tag with `@ref`:

833 

834```bash theme={null}

835claude plugin marketplace add acme-corp/claude-plugins@v2.0

836```

837 

838Add from a git URL on a non-GitHub host:

839 

840```bash theme={null}

841claude plugin marketplace add https://gitlab.example.com/team/plugins.git

842```

843 

844Add from a remote URL that serves the `marketplace.json` file directly:

845 

846```bash theme={null}

847claude plugin marketplace add https://example.com/marketplace.json

848```

849 

850Add from a local directory for testing:

851 

852```bash theme={null}

853claude plugin marketplace add ./my-marketplace

854```

855 

856Declare the marketplace at project scope so it is shared with your team via `.claude/settings.json`:

857 

858```bash theme={null}

859claude plugin marketplace add acme-corp/claude-plugins --scope project

860```

861 

862For a monorepo, limit the checkout to the directories that contain plugin content:

863 

864```bash theme={null}

865claude plugin marketplace add acme-corp/monorepo --sparse .claude-plugin plugins

866```

867 

868### Plugin marketplace list

869 

870List all configured marketplaces.

871 

872```bash theme={null}

873claude plugin marketplace list [options]

874```

875 

876**Options:**

877 

878| Option | Description |

879| :------- | :------------- |

880| `--json` | Output as JSON |

881 

882### Plugin marketplace remove

883 

884Remove a configured marketplace. The alias `rm` is also accepted.

885 

886```bash theme={null}

887claude plugin marketplace remove <name>

888```

889 

890**Arguments:**

891 

892* `<name>`: marketplace name to remove, as shown by `claude plugin marketplace list`. This is the `name` from `marketplace.json`, not the source you passed to `add`

893 

894<Warning>

895 Removing a marketplace also uninstalls any plugins you installed from it. To refresh a marketplace without losing installed plugins, use `claude plugin marketplace update` instead.

896</Warning>

897 

898### Plugin marketplace update

899 

900Refresh marketplaces from their sources to retrieve new plugins and version changes.

901 

902```bash theme={null}

903claude plugin marketplace update [name]

904```

905 

906**Arguments:**

907 

908* `[name]`: marketplace name to update, as shown by `claude plugin marketplace list`. Updates all marketplaces if omitted

909 

910Both `remove` and `update` fail when run against a seed-managed marketplace, which is read-only. When updating all marketplaces, seed-managed entries are skipped and other marketplaces still update. To change seed-provided plugins, ask your administrator to update the seed image. See [Pre-populate plugins for containers](#pre-populate-plugins-for-containers).

911 

912## Troubleshooting

913 

914### Marketplace not loading

366 915 

367**Symptoms**: Can't add marketplace or see plugins from it916**Symptoms**: Can't add marketplace or see plugins from it

368 917 


370 919 

371* Verify the marketplace URL is accessible920* Verify the marketplace URL is accessible

372* Check that `.claude-plugin/marketplace.json` exists at the specified path921* Check that `.claude-plugin/marketplace.json` exists at the specified path

373* Ensure JSON syntax is valid using `claude plugin validate`922* Ensure JSON syntax is valid and frontmatter is well-formed using `claude plugin validate` or `/plugin validate`

374* For private repositories, confirm you have access permissions923* For private repositories, confirm you have access permissions

375 924 

376#### Plugin installation failures925### Marketplace validation errors

926 

927Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. The validator checks `plugin.json`, skill/agent/command frontmatter, and `hooks/hooks.json` for syntax and schema errors. Common errors:

928 

929| Error | Cause | Solution |

930| :------------------------------------------------ | :---------------------------------------------- | :--------------------------------------------------------------------------------------------- |

931| `File not found: .claude-plugin/marketplace.json` | Missing manifest | Create `.claude-plugin/marketplace.json` with required fields |

932| `Invalid JSON syntax: Unexpected token...` | JSON syntax error in marketplace.json | Check for missing commas, extra commas, or unquoted strings |

933| `Duplicate plugin name "x" found in marketplace` | Two plugins share the same name | Give each plugin a unique `name` value |

934| `plugins[0].source: Path contains ".."` | Source path contains `..` | Use paths relative to the marketplace root without `..`. See [Relative paths](#relative-paths) |

935| `YAML frontmatter failed to parse: ...` | Invalid YAML in a skill, agent, or command file | Fix the YAML syntax in the frontmatter block. At runtime this file loads with no metadata. |

936| `Invalid JSON syntax: ...` (hooks.json) | Malformed `hooks/hooks.json` | Fix JSON syntax. A malformed `hooks/hooks.json` prevents the entire plugin from loading. |

937 

938**Warnings** (non-blocking):

939 

940* `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array

941* `No marketplace description provided`: add `metadata.description` to help users understand your marketplace

942* `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.

943 

944### Plugin installation failures

377 945 

378**Symptoms**: Marketplace appears but plugin installation fails946**Symptoms**: Marketplace appears but plugin installation fails

379 947 


384* For GitHub sources, ensure repositories are public or you have access952* For GitHub sources, ensure repositories are public or you have access

385* Test plugin sources manually by cloning/downloading953* Test plugin sources manually by cloning/downloading

386 954 

387### Validation and testing955### Private repository authentication fails

388 956 

389Test your marketplace before sharing:957**Symptoms**: Authentication errors when installing plugins from private repositories

390 958 

391```bash Validate marketplace JSON syntax theme={null}959**Solutions**:

392claude plugin validate .

393```

394 960 

395```shell Add marketplace for testing theme={null}961For manual installation and updates:

396/plugin marketplace add ./path/to/marketplace962 

963* Verify you're authenticated with your git provider (for example, run `gh auth status` for GitHub)

964* Check that your credential helper is configured correctly: `git config --global credential.helper`

965* Try cloning the repository manually to verify your credentials work

966 

967For background auto-updates:

968 

969* Set the appropriate token in your environment: `echo $GITHUB_TOKEN`

970* Check that the token has the required permissions (read access to the repository)

971* For GitHub, ensure the token has the `repo` scope for private repositories

972* For GitLab, ensure the token has at least `read_repository` scope

973* Verify the token hasn't expired

974 

975### Marketplace updates fail in offline environments

976 

977**Symptoms**: Marketplace `git pull` fails and Claude Code wipes the existing cache, causing plugins to become unavailable.

978 

979**Cause**: By default, when a `git pull` fails, Claude Code removes the stale clone and attempts to re-clone. In offline or airgapped environments, re-cloning fails the same way, leaving the marketplace directory empty.

980 

981**Solution**: Set `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE=1` to keep the existing cache when the pull fails instead of wiping it:

982 

983```bash theme={null}

984export CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE=1

397```985```

398 986 

399```shell Install test plugin theme={null}987With this variable set, Claude Code retains the stale marketplace clone on `git pull` failure and continues using the last-known-good state. For fully offline deployments where the repository will never be reachable, use [`CLAUDE_CODE_PLUGIN_SEED_DIR`](#pre-populate-plugins-for-containers) to pre-populate the plugins directory at build time instead.

400/plugin install test-plugin@marketplace-name988 

989### Git operations time out

990 

991**Symptoms**: Plugin installation or marketplace updates fail with a timeout error like "Git clone timed out after 120s" or "Git pull timed out after 120s".

992 

993**Cause**: Claude Code uses a 120-second timeout for all git operations, including cloning plugin repositories and pulling marketplace updates. Large repositories or slow network connections may exceed this limit.

994 

995**Solution**: Increase the timeout using the `CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS` environment variable. The value is in milliseconds:

996 

997```bash theme={null}

998export CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS=300000 # 5 minutes

401```999```

402 1000 

403For complete plugin testing workflows, see [Test your plugins locally](/en/docs/claude-code/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/en/docs/claude-code/plugins-reference).1001### Plugins with relative paths fail in URL-based marketplaces

1002 

1003**Symptoms**: Added a marketplace via URL (such as `https://example.com/marketplace.json`), but plugins with relative path sources like `"./plugins/my-plugin"` fail to install with "path not found" errors.

404 1004 

405***1005**Cause**: URL-based marketplaces only download the `marketplace.json` file itself. They do not download plugin files from the server. Relative paths in the marketplace entry reference files on the remote server that were not downloaded.

406 1006 

407## Next steps1007**Solutions**:

408 1008 

409### For marketplace users1009* **Use external sources**: Change plugin entries to use GitHub, npm, or git URL sources instead of relative paths:

1010 ```json theme={null}

1011 { "name": "my-plugin", "source": { "source": "github", "repo": "owner/repo" } }

1012 ```

1013* **Use a Git-based marketplace**: Host your marketplace in a Git repository and add it with the git URL. Git-based marketplaces clone the entire repository, making relative paths work correctly.

410 1014 

411* **Discover community marketplaces**: Search GitHub for Claude Code plugin collections1015### Files not found after installation

412* **Contribute feedback**: Report issues and suggest improvements to marketplace maintainers

413* **Share useful marketplaces**: Help your team discover valuable plugin collections

414 1016 

415### For marketplace creators1017**Symptoms**: Plugin installs but references to files fail, especially files outside the plugin directory

416 1018 

417* **Build plugin collections**: Create themed marketplace around specific use cases1019**Cause**: Plugins are copied to a cache directory rather than used in-place. Paths that reference files outside the plugin's directory (such as `../shared-utils`) won't work because those files aren't copied.

418* **Establish versioning**: Implement clear versioning and update policies

419* **Community engagement**: Gather feedback and maintain active marketplace communities

420* **Documentation**: Provide clear README files explaining your marketplace contents

421 1020 

422### For organizations1021**Solutions**: See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for workarounds including symlinks and directory restructuring.

423 1022 

424* **Private marketplaces**: Set up internal marketplaces for proprietary tools1023For additional debugging tools and common issues, see [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools).

425* **Governance policies**: Establish guidelines for plugin approval and security review

426* **Training resources**: Help teams discover and adopt useful plugins effectively

427 1024 

428## See also1025## See also

429 1026 

430* [Plugins](/en/docs/claude-code/plugins) - Installing and using plugins1027* [Discover and install prebuilt plugins](/en/discover-plugins) - Installing plugins from existing marketplaces

431* [Plugins reference](/en/docs/claude-code/plugins-reference) - Complete technical specifications and schemas1028* [Plugins](/en/plugins) - Creating your own plugins

432* [Plugin development](/en/docs/claude-code/plugins#develop-more-complex-plugins) - Creating your own plugins1029* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas

433* [Settings](/en/docs/claude-code/settings#plugin-configuration) - Plugin configuration options1030* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options

1031* [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions

plugins.md +292 −249

Details

1# Plugins1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Extend Claude Code with custom commands, agents, hooks, Skills, and MCP servers through the plugin system.5# Create plugins

6 

7> Create custom plugins to extend Claude Code with skills, agents, hooks, and MCP servers.

8 

9Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with skills, agents, hooks, and MCP servers.

10 

11Looking to install existing plugins? See [Discover and install plugins](/en/discover-plugins). For complete technical specifications, see [Plugins reference](/en/plugins-reference).

12 

13## When to use plugins vs standalone configuration

14 

15Claude Code supports two ways to add custom skills, agents, and hooks:

16 

17| Approach | Skill names | Best for |

18| :---------------------------------------------------------- | :------------------- | :---------------------------------------------------------------------------------------------- |

19| **Standalone** (`.claude/` directory) | `/hello` | Personal workflows, project-specific customizations, quick experiments |

20| **Plugins** (directories with `.claude-plugin/plugin.json`) | `/plugin-name:hello` | Sharing with teammates, distributing to community, versioned releases, reusable across projects |

21 

22**Use standalone configuration when**:

23 

24* You're customizing Claude Code for a single project

25* The configuration is personal and doesn't need to be shared

26* You're experimenting with skills or hooks before packaging them

27* You want short skill names like `/hello` or `/deploy`

28 

29**Use plugins when**:

30 

31* You want to share functionality with your team or community

32* You need the same skills/agents across multiple projects

33* You want version control and easy updates for your extensions

34* You're distributing through a marketplace

35* You're okay with namespaced skills like `/my-plugin:hello` (namespacing prevents conflicts between plugins)

4 36 

5<Tip>37<Tip>

6 For complete technical specifications and schemas, see [Plugins reference](/en/docs/claude-code/plugins-reference). For marketplace management, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces).38 Start with standalone configuration in `.claude/` for quick iteration, then [convert to a plugin](#convert-existing-configurations-to-plugins) when you're ready to share.

7</Tip>39</Tip>

8 40 

9Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. Install plugins from [marketplaces](/en/docs/claude-code/plugin-marketplaces) to add pre-built commands, agents, hooks, Skills, and MCP servers, or create your own to automate your workflows.

10 

11## Quickstart41## Quickstart

12 42 

13Let's create a simple greeting plugin to get you familiar with the plugin system. We'll build a working plugin that adds a custom command, test it locally, and understand the core concepts.43This quickstart walks you through creating a plugin with a custom skill. You'll create a manifest (the configuration file that defines your plugin), add a skill, and test it locally using the `--plugin-dir` flag.

14 44 

15### Prerequisites45### Prerequisites

16 46 

17* Claude Code installed on your machine47* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code)

18* Basic familiarity with command-line tools48 

49<Note>

50 If you don't see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/en/troubleshooting) for upgrade instructions.

51</Note>

19 52 

20### Create your first plugin53### Create your first plugin

21 54 

22<Steps>55<Steps>

23 <Step title="Create the marketplace structure">

24 ```bash theme={null}

25 mkdir test-marketplace

26 cd test-marketplace

27 ```

28 </Step>

29 

30 <Step title="Create the plugin directory">56 <Step title="Create the plugin directory">

57 Every plugin lives in its own directory containing a manifest and your skills, agents, or hooks. Create one now:

58 

31 ```bash theme={null}59 ```bash theme={null}

32 mkdir my-first-plugin60 mkdir my-first-plugin

33 cd my-first-plugin

34 ```61 ```

35 </Step>62 </Step>

36 63 

37 <Step title="Create the plugin manifest">64 <Step title="Create the plugin manifest">

38 ```bash Create .claude-plugin/plugin.json theme={null}65 The manifest file at `.claude-plugin/plugin.json` defines your plugin's identity: its name, description, and version. Claude Code uses this metadata to display your plugin in the plugin manager.

39 mkdir .claude-plugin66 

40 cat > .claude-plugin/plugin.json << 'EOF'67 Create the `.claude-plugin` directory inside your plugin folder:

68 

69 ```bash theme={null}

70 mkdir my-first-plugin/.claude-plugin

71 ```

72 

73 Then create `my-first-plugin/.claude-plugin/plugin.json` with this content:

74 

75 ```json my-first-plugin/.claude-plugin/plugin.json theme={null}

41 {76 {

42 "name": "my-first-plugin",77 "name": "my-first-plugin",

43 "description": "A simple greeting plugin to learn the basics",78 "description": "A greeting plugin to learn the basics",

44 "version": "1.0.0",79 "version": "1.0.0",

45 "author": {80 "author": {

46 "name": "Your Name"81 "name": "Your Name"

47 }82 }

48 }83 }

49 EOF

50 ```84 ```

85 

86 | Field | Purpose |

87 | :------------ | :----------------------------------------------------------------------------------------------------- |

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. |

90 | `version` | Track releases using [semantic versioning](/en/plugins-reference#version-management). |

91 | `author` | Optional. Helpful for attribution. |

92 

93 For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema).

51 </Step>94 </Step>

52 95 

53 <Step title="Add a custom command">96 <Step title="Add a skill">

54 ```bash Create commands/hello.md theme={null}97 Skills live in the `skills/` directory. Each skill is a folder containing a `SKILL.md` file. The folder name becomes the skill name, prefixed with the plugin's namespace (`hello/` in a plugin named `my-first-plugin` creates `/my-first-plugin:hello`).

55 mkdir commands

56 cat > commands/hello.md << 'EOF'

57 ---

58 description: Greet the user with a personalized message

59 ---

60 98 

61 # Hello Command99 Create a skill directory in your plugin folder:

62 100 

63 Greet the user warmly and ask how you can help them today. Make the greeting personal and encouraging.101 ```bash theme={null}

64 EOF102 mkdir -p my-first-plugin/skills/hello

65 ```103 ```

66 </Step>

67 104 

68 <Step title="Create the marketplace manifest">105 Then create `my-first-plugin/skills/hello/SKILL.md` with this content:

69 ```bash Create marketplace.json theme={null}106 

70 cd ..107 ```markdown my-first-plugin/skills/hello/SKILL.md theme={null}

71 mkdir .claude-plugin108 ---

72 cat > .claude-plugin/marketplace.json << 'EOF'109 description: Greet the user with a friendly message

73 {110 disable-model-invocation: true

74 "name": "test-marketplace",111 ---

75 "owner": {112 

76 "name": "Test User"113 Greet the user warmly and ask how you can help them today.

77 },

78 "plugins": [

79 {

80 "name": "my-first-plugin",

81 "source": "./my-first-plugin",

82 "description": "My first test plugin"

83 }

84 ]

85 }

86 EOF

87 ```114 ```

88 </Step>115 </Step>

89 116 

90 <Step title="Install and test your plugin">117 <Step title="Test your plugin">

91 ```bash Start Claude Code from parent directory theme={null}118 Run Claude Code with the `--plugin-dir` flag to load your plugin:

92 cd ..119 

93 claude120 ```bash theme={null}

121 claude --plugin-dir ./my-first-plugin

94 ```122 ```

95 123 

96 ```shell Add the test marketplace theme={null}124 Once Claude Code starts, try your new skill:

97 /plugin marketplace add ./test-marketplace125 

126 ```shell theme={null}

127 /my-first-plugin:hello

98 ```128 ```

99 129 

100 ```shell Install your plugin theme={null}130 You'll see Claude respond with a greeting. Run `/help` to see your skill listed under the plugin namespace.

101 /plugin install my-first-plugin@test-marketplace131 

132 <Note>

133 **Why namespacing?** Plugin skills are always namespaced (like `/my-first-plugin:hello`) to prevent conflicts when multiple plugins have skills with the same name.

134 

135 To change the namespace prefix, update the `name` field in `plugin.json`.

136 </Note>

137 </Step>

138 

139 <Step title="Add skill arguments">

140 Make your skill dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the skill name.

141 

142 Update your `SKILL.md` file:

143 

144 ```markdown my-first-plugin/skills/hello/SKILL.md theme={null}

145 ---

146 description: Greet the user with a personalized message

147 ---

148 

149 # Hello Skill

150 

151 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.

102 ```152 ```

103 153 

104 Select "Install now". You'll then need to restart Claude Code in order to use the new plugin.154 Run `/reload-plugins` to pick up the changes, then try the skill with your name:

105 155 

106 ```shell Try your new command theme={null}156 ```shell theme={null}

107 /hello157 /my-first-plugin:hello Alex

108 ```158 ```

109 159 

110 You'll see Claude use your greeting command! Check `/help` to see your new command listed.160 Claude will greet you by name. For more on passing arguments to skills, see [Skills](/en/skills#pass-arguments-to-skills).

111 </Step>161 </Step>

112</Steps>162</Steps>

113 163 

114You've successfully created and tested a plugin with these key components:164You've successfully created and tested a plugin with these key components:

115 165 

116* **Plugin manifest** (`.claude-plugin/plugin.json`) - Describes your plugin's metadata166* **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata

117* **Commands directory** (`commands/`) - Contains your custom slash commands167* **Skills directory** (`skills/`): contains your custom skills

118* **Test marketplace** - Allows you to test your plugin locally168* **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior

119 169 

120### Plugin structure overview170<Tip>

171 The `--plugin-dir` flag is useful for development and testing. When you're ready to share your plugin with others, see [Create and distribute a plugin marketplace](/en/plugin-marketplaces).

172</Tip>

121 173 

122Your plugin follows this basic structure:174## Plugin structure overview

123 175 

124```176You've created a plugin with a skill, but plugins can include much more: custom agents, hooks, MCP servers, and LSP servers.

125my-first-plugin/

126├── .claude-plugin/

127│ └── plugin.json # Plugin metadata

128├── commands/ # Custom slash commands (optional)

129│ └── hello.md

130├── agents/ # Custom agents (optional)

131│ └── helper.md

132├── skills/ # Agent Skills (optional)

133│ └── my-skill/

134│ └── SKILL.md

135└── hooks/ # Event handlers (optional)

136 └── hooks.json

137```

138 177 

139**Additional components you can add:**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.

180</Warning>

140 181 

141* **Commands**: Create markdown files in `commands/` directory182| Directory | Location | Purpose |

142* **Agents**: Create agent definitions in `agents/` directory183| :---------------- | :---------- | :----------------------------------------------------------------------------- |

143* **Skills**: Create `SKILL.md` files in `skills/` directory184| `.claude-plugin/` | Plugin root | Contains `plugin.json` manifest (optional if components use default locations) |

144* **Hooks**: Create `hooks/hooks.json` for event handling185| `commands/` | Plugin root | Skills as Markdown files |

145* **MCP servers**: Create `.mcp.json` for external tool integration186| `agents/` | Plugin root | Custom agent definitions |

187| `skills/` | Plugin root | Agent Skills with `SKILL.md` files |

188| `hooks/` | Plugin root | Event handlers in `hooks.json` |

189| `.mcp.json` | Plugin root | MCP server configurations |

190| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |

191| `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 |

146 193 

147<Note>194<Note>

148 **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, and MCP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/docs/claude-code/plugins-reference).195 **Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference).

149</Note>196</Note>

150 197 

151***198## Develop more complex plugins

152 199 

153## Install and manage plugins200Once you're comfortable with basic plugins, you can create more sophisticated extensions.

154 201 

155Learn how to discover, install, and manage plugins to extend your Claude Code capabilities.202### Add Skills to your plugin

156 203 

157### Prerequisites204Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked: Claude automatically uses them based on the task context.

158 205 

159* Claude Code installed and running206Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:

160* Basic familiarity with command-line interfaces207 

208```text theme={null}

209my-plugin/

210├── .claude-plugin/

211│ └── plugin.json

212└── skills/

213 └── code-review/

214 └── SKILL.md

215```

161 216 

162### Add marketplaces217Each `SKILL.md` needs frontmatter with `name` and `description` fields, followed by instructions:

163 218 

164Marketplaces are catalogs of available plugins. Add them to discover and install plugins:219```yaml theme={null}

220---

221name: code-review

222description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.

223---

165 224 

166```shell Add a marketplace theme={null}225When reviewing code, check for:

167/plugin marketplace add your-org/claude-plugins2261. Code organization and structure

2272. Error handling

2283. Security concerns

2294. Test coverage

168```230```

169 231 

170```shell Browse available plugins theme={null}232After installing the plugin, run `/reload-plugins` to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills).

171/plugin

172```

173 233 

174For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces).234### Add LSP servers to your plugin

175 235 

176### Install plugins236<Tip>

237 For common languages like TypeScript, Python, and Rust, install the pre-built LSP plugins from the official marketplace. Create custom LSP plugins only when you need support for languages not already covered.

238</Tip>

177 239 

178#### Via interactive menu (recommended for discovery)240LSP (Language Server Protocol) plugins give Claude real-time code intelligence. If you need to support a language that doesn't have an official LSP plugin, you can create your own by adding an `.lsp.json` file to your plugin:

179 241 

180```shell Open the plugin management interface theme={null}242```json .lsp.json theme={null}

181/plugin243{

244 "go": {

245 "command": "gopls",

246 "args": ["serve"],

247 "extensionToLanguage": {

248 ".go": "go"

249 }

250 }

251}

182```252```

183 253 

184Select "Browse Plugins" to see available options with descriptions, features, and installation options.254Users installing your plugin must have the language server binary installed on their machine.

185 255 

186#### Via direct commands (for quick installation)256For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers).

187 257 

188```shell Install a specific plugin theme={null}258### Ship default settings with your plugin

189/plugin install formatter@your-org

190```

191 259 

192```shell Enable a disabled plugin theme={null}260Plugins can include a `settings.json` file at the plugin root to apply default configuration when the plugin is enabled. Currently, only the `agent` key is supported.

193/plugin enable plugin-name@marketplace-name261 

194```262Setting `agent` activates one of the plugin's [custom agents](/en/sub-agents) as the main thread, applying its system prompt, tool restrictions, and model. This lets a plugin change how Claude Code behaves by default when enabled.

195 263 

196```shell Disable without uninstalling theme={null}264```json settings.json theme={null}

197/plugin disable plugin-name@marketplace-name265{

266 "agent": "security-reviewer"

267}

198```268```

199 269 

200```shell Completely remove a plugin theme={null}270This example activates the `security-reviewer` agent defined in the plugin's `agents/` directory. Settings from `settings.json` take priority over `settings` declared in `plugin.json`. Unknown keys are silently ignored.

201/plugin uninstall plugin-name@marketplace-name271 

272### Organize complex plugins

273 

274For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/plugins-reference#plugin-directory-structure).

275 

276### Test your plugins locally

277 

278Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation.

279 

280```bash theme={null}

281claude --plugin-dir ./my-plugin

202```282```

203 283 

204### Verify installation284When a `--plugin-dir` plugin has the same name as an installed marketplace plugin, the local copy takes precedence for that session. This lets you test changes to a plugin you already have installed without uninstalling it first. Marketplace plugins force-enabled by managed settings are the only exception and cannot be overridden.

205 285 

206After installing a plugin:286As you make changes to your plugin, run `/reload-plugins` to pick up the updates without restarting. This reloads plugins, skills, agents, hooks, plugin MCP servers, and plugin LSP servers. Test your plugin components:

207 287 

2081. **Check available commands**: Run `/help` to see new commands288* Try your skills with `/plugin-name:skill-name`

2092. **Test plugin features**: Try the plugin's commands and features289* Check that agents appear in `/agents`

2103. **Review plugin details**: Use `/plugin` → "Manage Plugins" to see what the plugin provides290* Verify hooks work as expected

211 291 

212## Set up team plugin workflows292<Tip>

293 You can load multiple plugins at once by specifying the flag multiple times:

213 294 

214Configure plugins at the repository level to ensure consistent tooling across your team. When team members trust your repository folder, Claude Code automatically installs specified marketplaces and plugins.295 ```bash theme={null}

296 claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two

297 ```

298</Tip>

215 299 

216**To set up team plugins:**300### Debug plugin issues

217 301 

2181. Add marketplace and plugin configuration to your repository's `.claude/settings.json`302If your plugin isn't working as expected:

2192. Team members trust the repository folder

2203. Plugins install automatically for all team members

221 303 

222For complete instructions including configuration examples, marketplace setup, and rollout best practices, see [Configure team marketplaces](/en/docs/claude-code/plugin-marketplaces#how-to-configure-team-marketplaces).3041. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`

3052. **Test components individually**: Check each command, agent, and hook separately

3063. **Use validation and debugging tools**: See [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques

223 307 

224***308### Share your plugins

225 309 

226## Develop more complex plugins310When your plugin is ready to share:

227 311 

228Once you're comfortable with basic plugins, you can create more sophisticated extensions.3121. **Add documentation**: Include a `README.md` with installation and usage instructions

3132. **Version your plugin**: Use [semantic versioning](/en/plugins-reference#version-management) in your `plugin.json`

3143. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation

3154. **Test with others**: Have team members test the plugin before wider distribution

229 316 

230### Add Skills to your plugin317Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins).

231 318 

232Plugins can include [Agent Skills](/en/docs/claude-code/skills) to extend Claude's capabilities. Skills are model-invoked—Claude autonomously uses them based on the task context.319### Submit your plugin to the official marketplace

233 320 

234To add Skills to your plugin, create a `skills/` directory at your plugin root and add Skill folders with `SKILL.md` files. Plugin Skills are automatically available when the plugin is installed.321To submit a plugin to the official Anthropic marketplace, use one of the in-app submission forms:

235 322 

236For complete Skill authoring guidance, see [Agent Skills](/en/docs/claude-code/skills).323* **Claude.ai**: [claude.ai/settings/plugins/submit](https://claude.ai/settings/plugins/submit)

324* **Console**: [platform.claude.com/plugins/submit](https://platform.claude.com/plugins/submit)

237 325 

238### Organize complex plugins326<Note>

327 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).

328</Note>

239 329 

240For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/docs/claude-code/plugins-reference#plugin-directory-structure).330## Convert existing configurations to plugins

241 331 

242### Test your plugins locally332If you already have skills or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution.

243 333 

244When developing plugins, use a local marketplace to test changes iteratively. This workflow builds on the quickstart pattern and works for plugins of any complexity.334### Migration steps

245 335 

246<Steps>336<Steps>

247 <Step title="Set up your development structure">337 <Step title="Create the plugin structure">

248 Organize your plugin and marketplace for testing:338 Create a new plugin directory:

249 339 

250 ```bash Create directory structure theme={null}340 ```bash theme={null}

251 mkdir dev-marketplace341 mkdir -p my-plugin/.claude-plugin

252 cd dev-marketplace

253 mkdir my-plugin

254 ```342 ```

255 343 

256 This creates:344 Create the manifest file at `my-plugin/.claude-plugin/plugin.json`:

257 

258 ```

259 dev-marketplace/

260 ├── .claude-plugin/marketplace.json (you'll create this)

261 └── my-plugin/ (your plugin under development)

262 ├── .claude-plugin/plugin.json

263 ├── commands/

264 ├── agents/

265 └── hooks/

266 ```

267 </Step>

268 345 

269 <Step title="Create the marketplace manifest">346 ```json my-plugin/.claude-plugin/plugin.json theme={null}

270 ```bash Create marketplace.json theme={null}

271 mkdir .claude-plugin

272 cat > .claude-plugin/marketplace.json << 'EOF'

273 {

274 "name": "dev-marketplace",

275 "owner": {

276 "name": "Developer"

277 },

278 "plugins": [

279 {347 {

280 "name": "my-plugin",348 "name": "my-plugin",

281 "source": "./my-plugin",349 "description": "Migrated from standalone configuration",

282 "description": "Plugin under development"350 "version": "1.0.0"

283 }

284 ]

285 }351 }

286 EOF

287 ```352 ```

288 </Step>353 </Step>

289 354 

290 <Step title="Install and test">355 <Step title="Copy your existing files">

291 ```bash Start Claude Code from parent directory theme={null}356 Copy your existing configurations to the plugin directory:

292 cd ..

293 claude

294 ```

295 357 

296 ```shell Add your development marketplace theme={null}358 ```bash theme={null}

297 /plugin marketplace add ./dev-marketplace359 # Copy commands

298 ```360 cp -r .claude/commands my-plugin/

299 

300 ```shell Install your plugin theme={null}

301 /plugin install my-plugin@dev-marketplace

302 ```

303 361 

304 Test your plugin components:362 # Copy agents (if any)

363 cp -r .claude/agents my-plugin/

305 364 

306 * Try your commands with `/command-name`365 # Copy skills (if any)

307 * Check that agents appear in `/agents`366 cp -r .claude/skills my-plugin/

308 * Verify hooks work as expected367 ```

309 </Step>368 </Step>

310 369 

311 <Step title="Iterate on your plugin">370 <Step title="Migrate hooks">

312 After making changes to your plugin code:371 If you have hooks in your settings, create a hooks directory:

313 372 

314 ```shell Uninstall the current version theme={null}373 ```bash theme={null}

315 /plugin uninstall my-plugin@dev-marketplace374 mkdir my-plugin/hooks

316 ```375 ```

317 376 

318 ```shell Reinstall to test changes theme={null}377 Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`, since the format is the same. The command receives hook input as JSON on stdin, so use `jq` to extract the file path:

319 /plugin install my-plugin@dev-marketplace

320 ```

321 378 

322 Repeat this cycle as you develop and refine your plugin.379 ```json my-plugin/hooks/hooks.json theme={null}

380 {

381 "hooks": {

382 "PostToolUse": [

383 {

384 "matcher": "Write|Edit",

385 "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }]

386 }

387 ]

388 }

389 }

390 ```

323 </Step>391 </Step>

324</Steps>

325 392 

326<Note>393 <Step title="Test your migrated plugin">

327 **For multiple plugins**: Organize plugins in subdirectories like `./plugins/plugin-name` and update your marketplace.json accordingly. See [Plugin sources](/en/docs/claude-code/plugin-marketplaces#plugin-sources) for organization patterns.394 Load your plugin to verify everything works:

328</Note>

329 

330### Debug plugin issues

331 395 

332If your plugin isn't working as expected:396 ```bash theme={null}

333 397 claude --plugin-dir ./my-plugin

3341. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`398 ```

3352. **Test components individually**: Check each command, agent, and hook separately

3363. **Use validation and debugging tools**: See [Debugging and development tools](/en/docs/claude-code/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques

337 399 

338### Share your plugins400 Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly.

401 </Step>

402</Steps>

339 403 

340When your plugin is ready to share:404### What changes when migrating

341 405 

3421. **Add documentation**: Include a README.md with installation and usage instructions406| Standalone (`.claude/`) | Plugin |

3432. **Version your plugin**: Use semantic versioning in your `plugin.json`407| :---------------------------- | :------------------------------- |

3443. **Create or use a marketplace**: Distribute through plugin marketplaces for easy installation408| Only available in one project | Can be shared via marketplaces |

3454. **Test with others**: Have team members test the plugin before wider distribution409| Files in `.claude/commands/` | Files in `plugin-name/commands/` |

410| Hooks in `settings.json` | Hooks in `hooks/hooks.json` |

411| Must manually copy to share | Install with `/plugin install` |

346 412 

347<Note>413<Note>

348 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/docs/claude-code/plugins-reference).414 After migrating, you can remove the original files from `.claude/` to avoid duplicates. The plugin version will take precedence when loaded.

349</Note>415</Note>

350 416 

351***

352 

353## Next steps417## Next steps

354 418 

355Now that you understand Claude Code's plugin system, here are suggested paths for different goals:419Now that you understand Claude Code's plugin system, here are suggested paths for different goals:

356 420 

357### For plugin users421### For plugin users

358 422 

359* **Discover plugins**: Browse community marketplaces for useful tools423* [Discover and install plugins](/en/discover-plugins): browse marketplaces and install plugins

360* **Team adoption**: Set up repository-level plugins for your projects424* [Configure team marketplaces](/en/discover-plugins#configure-team-marketplaces): set up repository-level plugins for your team

361* **Marketplace management**: Learn to manage multiple plugin sources

362* **Advanced usage**: Explore plugin combinations and workflows

363 425 

364### For plugin developers426### For plugin developers

365 427 

366* **Create your first marketplace**: [Plugin marketplaces guide](/en/docs/claude-code/plugin-marketplaces)428* [Create and distribute a marketplace](/en/plugin-marketplaces): package and share your plugins

367* **Advanced components**: Dive deeper into specific plugin components:429* [Plugins reference](/en/plugins-reference): complete technical specifications

368 * [Slash commands](/en/docs/claude-code/slash-commands) - Command development details430* Dive deeper into specific plugin components:

369 * [Subagents](/en/docs/claude-code/sub-agents) - Agent configuration and capabilities431 * [Skills](/en/skills): skill development details

370 * [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities432 * [Subagents](/en/sub-agents): agent configuration and capabilities

371 * [Hooks](/en/docs/claude-code/hooks) - Event handling and automation433 * [Hooks](/en/hooks): event handling and automation

372 * [MCP](/en/docs/claude-code/mcp) - External tool integration434 * [MCP](/en/mcp): external tool integration

373* **Distribution strategies**: Package and share your plugins effectively

374* **Community contribution**: Consider contributing to community plugin collections

375 

376### For team leads and administrators

377 

378* **Repository configuration**: Set up automatic plugin installation for team projects

379* **Plugin governance**: Establish guidelines for plugin approval and security review

380* **Marketplace maintenance**: Create and maintain organization-specific plugin catalogs

381* **Training and documentation**: Help team members adopt plugin workflows effectively

382 

383## See also

384 

385* [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces) - Creating and managing plugin catalogs

386* [Slash commands](/en/docs/claude-code/slash-commands) - Understanding custom commands

387* [Subagents](/en/docs/claude-code/sub-agents) - Creating and using specialized agents

388* [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities

389* [Hooks](/en/docs/claude-code/hooks) - Automating workflows with event handlers

390* [MCP](/en/docs/claude-code/mcp) - Connecting to external tools and services

391* [Settings](/en/docs/claude-code/settings) - Configuration options for plugins

plugins-reference.md +565 −103

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Plugins reference5# Plugins reference

2 6 

3> Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications.7> Complete technical reference for Claude Code plugin system, including schemas, CLI commands, and component specifications.

4 8 

5<Tip>9<Tip>

6 For hands-on tutorials and practical usage, see [Plugins](/en/docs/claude-code/plugins). For plugin management across teams and communities, see [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces).10 Looking to install plugins? See [Discover and install plugins](/en/discover-plugins). For creating plugins, see [Plugins](/en/plugins). For distributing plugins, see [Plugin marketplaces](/en/plugin-marketplaces).

7</Tip>11</Tip>

8 12 

9This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.13This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.

10 14 

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.

16 

11## Plugin components reference17## Plugin components reference

12 18 

13This section documents the five types of components that plugins can provide.19### Skills

14 20 

15### Commands21Plugins add skills to Claude Code, creating `/name` shortcuts that you or Claude can invoke.

16 22 

17Plugins add custom slash commands that integrate seamlessly with Claude Code's command system.23**Location**: `skills/` or `commands/` directory in plugin root

18 24 

19**Location**: `commands/` directory in plugin root25**File format**: Skills are directories with `SKILL.md`; commands are simple markdown files

26 

27**Skill structure**:

20 28 

21**File format**: Markdown files with frontmatter29```text theme={null}

30skills/

31├── pdf-processor/

32│ ├── SKILL.md

33│ ├── reference.md (optional)

34│ └── scripts/ (optional)

35└── code-reviewer/

36 └── SKILL.md

37```

38 

39**Integration behavior**:

40 

41* Skills and commands are automatically discovered when the plugin is installed

42* Claude can invoke them automatically based on task context

43* Skills can include supporting files alongside SKILL.md

22 44 

23For complete details on plugin command structure, invocation patterns, and features, see [Plugin commands](/en/docs/claude-code/slash-commands#plugin-commands).45For complete details, see [Skills](/en/skills).

24 46 

25### Agents47### Agents

26 48 


34 56 

35```markdown theme={null}57```markdown theme={null}

36---58---

37description: What this agent specializes in59name: agent-name

38capabilities: ["task1", "task2", "task3"]60description: What this agent specializes in and when Claude should invoke it

61model: sonnet

62effort: medium

63maxTurns: 20

64disallowedTools: Write, Edit

39---65---

40 66 

41# Agent Name67Detailed system prompt for the agent describing its role, expertise, and behavior.

42 

43Detailed description of the agent's role, expertise, and when Claude should invoke it.

44 

45## Capabilities

46- Specific task the agent excels at

47- Another specialized capability

48- When to use this agent vs others

49 

50## Context and examples

51Provide examples of when this agent should be used and what kinds of problems it solves.

52```68```

53 69 

70Plugin agents support `name`, `description`, `model`, `effort`, `maxTurns`, `tools`, `disallowedTools`, `skills`, `memory`, `background`, and `isolation` frontmatter fields. The only valid `isolation` value is `"worktree"`. For security reasons, `hooks`, `mcpServers`, and `permissionMode` are not supported for plugin-shipped agents.

71 

54**Integration points**:72**Integration points**:

55 73 

56* Agents appear in the `/agents` interface74* Agents appear in the `/agents` interface


58* Agents can be invoked manually by users76* Agents can be invoked manually by users

59* Plugin agents work alongside built-in Claude agents77* Plugin agents work alongside built-in Claude agents

60 78 

61### Skills79For complete details, see [Subagents](/en/sub-agents).

62 

63Plugins can provide Agent Skills that extend Claude's capabilities. Skills are model-invoked—Claude autonomously decides when to use them based on the task context.

64 

65**Location**: `skills/` directory in plugin root

66 

67**File format**: Directories containing `SKILL.md` files with frontmatter

68 

69**Skill structure**:

70 

71```

72skills/

73├── pdf-processor/

74│ ├── SKILL.md

75│ ├── reference.md (optional)

76│ └── scripts/ (optional)

77└── code-reviewer/

78 └── SKILL.md

79```

80 

81**Integration behavior**:

82 

83* Plugin Skills are automatically discovered when the plugin is installed

84* Claude autonomously invokes Skills based on matching task context

85* Skills can include supporting files alongside SKILL.md

86 

87For SKILL.md format and complete Skill authoring guidance, see:

88 

89* [Use Skills in Claude Code](/en/docs/claude-code/skills)

90* [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview#skill-structure)

91 80 

92### Hooks81### Hooks

93 82 


117}106}

118```107```

119 108 

120**Available events**:109Plugin hooks respond to the same lifecycle events as [user-defined hooks](/en/hooks):

121 110 

122* `PreToolUse`: Before Claude uses any tool111| Event | When it fires |

123* `PostToolUse`: After Claude uses any tool112| :------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------- |

124* `UserPromptSubmit`: When user submits a prompt113| `SessionStart` | When a session begins or resumes |

125* `Notification`: When Claude Code sends notifications114| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

126* `Stop`: When Claude attempts to stop115| `PreToolUse` | Before a tool call executes. Can block it |

127* `SubagentStop`: When a subagent attempts to stop116| `PermissionRequest` | When a permission dialog appears |

128* `SessionStart`: At the beginning of sessions117| `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 |

129* `SessionEnd`: At the end of sessions118| `PostToolUse` | After a tool call succeeds |

130* `PreCompact`: Before conversation history is compacted119| `PostToolUseFailure` | After a tool call fails |

120| `Notification` | When Claude Code sends a notification |

121| `SubagentStart` | When a subagent is spawned |

122| `SubagentStop` | When a subagent finishes |

123| `TaskCreated` | When a task is being created via `TaskCreate` |

124| `TaskCompleted` | When a task is being marked as completed |

125| `Stop` | When Claude finishes responding |

126| `StopFailure` | When the turn ends due to an API error. Output and exit code are ignored |

127| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

128| `InstructionsLoaded` | When a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. Fires at session start and when files are lazily loaded during a session |

129| `ConfigChange` | When a configuration file changes during a session |

130| `CwdChanged` | When the working directory changes, for example when Claude executes a `cd` command. Useful for reactive environment management with tools like direnv |

131| `FileChanged` | When a watched file changes on disk. The `matcher` field specifies which filenames to watch |

132| `WorktreeCreate` | When a worktree is being created via `--worktree` or `isolation: "worktree"`. Replaces default git behavior |

133| `WorktreeRemove` | When a worktree is being removed, either at session exit or when a subagent finishes |

134| `PreCompact` | Before context compaction |

135| `PostCompact` | After context compaction completes |

136| `Elicitation` | When an MCP server requests user input during a tool call |

137| `ElicitationResult` | After a user responds to an MCP elicitation, before the response is sent back to the server |

138| `SessionEnd` | When a session terminates |

131 139 

132**Hook types**:140**Hook types**:

133 141 

134* `command`: Execute shell commands or scripts142* `command`: execute shell commands or scripts

135* `validation`: Validate file contents or project state143* `http`: send the event JSON as a POST request to a URL

136* `notification`: Send alerts or status updates144* `prompt`: evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context)

145* `agent`: run an agentic verifier with tools for complex verification tasks

137 146 

138### MCP servers147### MCP servers

139 148 


171* Server capabilities integrate seamlessly with Claude's existing tools180* Server capabilities integrate seamlessly with Claude's existing tools

172* Plugin servers can be configured independently of user MCP servers181* Plugin servers can be configured independently of user MCP servers

173 182 

183### LSP servers

184 

185<Tip>

186 Looking to use LSP plugins? Install them from the official marketplace: search for "lsp" in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace.

187</Tip>

188 

189Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase.

190 

191LSP integration provides:

192 

193* **Instant diagnostics**: Claude sees errors and warnings immediately after each edit

194* **Code navigation**: go to definition, find references, and hover information

195* **Language awareness**: type information and documentation for code symbols

196 

197**Location**: `.lsp.json` in plugin root, or inline in `plugin.json`

198 

199**Format**: JSON configuration mapping language server names to their configurations

200 

201**`.lsp.json` file format**:

202 

203```json theme={null}

204{

205 "go": {

206 "command": "gopls",

207 "args": ["serve"],

208 "extensionToLanguage": {

209 ".go": "go"

210 }

211 }

212}

213```

214 

215**Inline in `plugin.json`**:

216 

217```json theme={null}

218{

219 "name": "my-plugin",

220 "lspServers": {

221 "go": {

222 "command": "gopls",

223 "args": ["serve"],

224 "extensionToLanguage": {

225 ".go": "go"

226 }

227 }

228 }

229}

230```

231 

232**Required fields:**

233 

234| Field | Description |

235| :-------------------- | :------------------------------------------- |

236| `command` | The LSP binary to execute (must be in PATH) |

237| `extensionToLanguage` | Maps file extensions to language identifiers |

238 

239**Optional fields:**

240 

241| Field | Description |

242| :---------------------- | :-------------------------------------------------------- |

243| `args` | Command-line arguments for the LSP server |

244| `transport` | Communication transport: `stdio` (default) or `socket` |

245| `env` | Environment variables to set when starting the server |

246| `initializationOptions` | Options passed to the server during initialization |

247| `settings` | Settings passed via `workspace/didChangeConfiguration` |

248| `workspaceFolder` | Workspace folder path for the server |

249| `startupTimeout` | Max time to wait for server startup (milliseconds) |

250| `shutdownTimeout` | Max time to wait for graceful shutdown (milliseconds) |

251| `restartOnCrash` | Whether to automatically restart the server if it crashes |

252| `maxRestarts` | Maximum number of restart attempts before giving up |

253 

254<Warning>

255 **You must install the language server binary separately.** LSP plugins configure how Claude Code connects to a language server, but they don't include the server itself. If you see `Executable not found in $PATH` in the `/plugin` Errors tab, install the required binary for your language.

256</Warning>

257 

258**Available LSP plugins:**

259 

260| Plugin | Language server | Install command |

261| :--------------- | :------------------------- | :----------------------------------------------------------------------------------------- |

262| `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` |

264| `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |

265 

266Install the language server first, then install the plugin from the marketplace.

267 

268***

269 

270## Plugin installation scopes

271 

272When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:

273 

274| Scope | Settings file | Use case |

275| :-------- | :---------------------------------------------- | :------------------------------------------------------- |

276| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |

277| `project` | `.claude/settings.json` | Team plugins shared via version control |

278| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |

279| `managed` | [Managed settings](/en/settings#settings-files) | Managed plugins (read-only, update only) |

280 

281Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/en/settings#configuration-scopes).

282 

174***283***

175 284 

176## Plugin manifest schema285## Plugin manifest schema

177 286 

178The `plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.287The `.claude-plugin/plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.

288 

289The manifest is optional. If omitted, Claude Code auto-discovers components in [default locations](#file-locations-reference) and derives the plugin name from the directory name. Use a manifest when you need to provide metadata or custom component paths.

179 290 

180### Complete schema291### Complete schema

181 292 


195 "keywords": ["keyword1", "keyword2"],306 "keywords": ["keyword1", "keyword2"],

196 "commands": ["./custom/commands/special.md"],307 "commands": ["./custom/commands/special.md"],

197 "agents": "./custom/agents/",308 "agents": "./custom/agents/",

309 "skills": "./custom/skills/",

198 "hooks": "./config/hooks.json",310 "hooks": "./config/hooks.json",

199 "mcpServers": "./mcp-config.json"311 "mcpServers": "./mcp-config.json",

312 "outputStyles": "./styles/",

313 "lspServers": "./.lsp.json"

200}314}

201```315```

202 316 

203### Required fields317### Required fields

204 318 

319If you include a manifest, `name` is the only required field.

320 

205| Field | Type | Description | Example |321| Field | Type | Description | Example |

206| :----- | :----- | :---------------------------------------- | :------------------- |322| :----- | :----- | :---------------------------------------- | :------------------- |

207| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |323| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |

208 324 

325This name is used for namespacing components. For example, in the UI, the

326agent `agent-creator` for the plugin with name `plugin-dev` will appear as

327`plugin-dev:agent-creator`.

328 

209### Metadata fields329### Metadata fields

210 330 

211| Field | Type | Description | Example |331| Field | Type | Description | Example |

212| :------------ | :----- | :---------------------------------- | :------------------------------------------------- |332| :------------ | :----- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------- |

213| `version` | string | Semantic version | `"2.1.0"` |333| `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"` |

214| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |334| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |

215| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |335| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |

216| `homepage` | string | Documentation URL | `"https://docs.example.com"` |336| `homepage` | string | Documentation URL | `"https://docs.example.com"` |


221### Component path fields341### Component path fields

222 342 

223| Field | Type | Description | Example |343| Field | Type | Description | Example |

224| :----------- | :------------- | :----------------------------------- | :------------------------------------- |344| :------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- |

225| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |345| `commands` | string\|array | Custom command files/directories (replaces default `commands/`) | `"./custom/cmd.md"` or `["./cmd1.md"]` |

226| `agents` | string\|array | Additional agent files | `"./custom/agents/"` |346| `agents` | string\|array | Custom agent files (replaces default `agents/`) | `"./custom/agents/reviewer.md"` |

227| `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` |347| `skills` | string\|array | Custom skill directories (replaces default `skills/`) | `"./custom/skills/"` |

228| `mcpServers` | string\|object | MCP config path or inline config | `"./mcp.json"` |348| `hooks` | string\|array\|object | Hook config paths or inline config | `"./my-extra-hooks.json"` |

349| `mcpServers` | string\|array\|object | MCP config paths or inline config | `"./my-extra-mcp-config.json"` |

350| `outputStyles` | string\|array | Custom output style files/directories (replaces default `output-styles/`) | `"./styles/"` |

351| `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"` |

352| `userConfig` | object | User-configurable values prompted at enable time. See [User configuration](#user-configuration) | See below |

353| `channels` | array | Channel declarations for message injection (Telegram, Slack, Discord style). See [Channels](#channels) | See below |

354 

355### User configuration

356 

357The `userConfig` field declares values that Claude Code prompts the user for when the plugin is enabled. Use this instead of requiring users to hand-edit `settings.json`.

358 

359```json theme={null}

360{

361 "userConfig": {

362 "api_endpoint": {

363 "description": "Your team's API endpoint",

364 "sensitive": false

365 },

366 "api_token": {

367 "description": "API authentication token",

368 "sensitive": true

369 }

370 }

371}

372```

373 

374Keys 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.

375 

376Non-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.

377 

378### Channels

379 

380The `channels` field lets a plugin declare one or more message channels that inject content into the conversation. Each channel binds to an MCP server that the plugin provides.

381 

382```json theme={null}

383{

384 "channels": [

385 {

386 "server": "telegram",

387 "userConfig": {

388 "bot_token": { "description": "Telegram bot token", "sensitive": true },

389 "owner_id": { "description": "Your Telegram user ID", "sensitive": false }

390 }

391 }

392 ]

393}

394```

395 

396The `server` field is required and must match a key in the plugin's `mcpServers`. The optional per-channel `userConfig` uses the same schema as the top-level field, letting the plugin prompt for bot tokens or owner IDs when the plugin is enabled.

229 397 

230### Path behavior rules398### Path behavior rules

231 399 

232**Important**: Custom paths supplement default directories - they don't replace them.400For `commands`, `agents`, `skills`, and `outputStyles`, custom paths replace the default directory. If the manifest specifies `commands`, the default `commands/` directory is not scanned. [Hooks](#hooks), [MCP servers](#mcp-servers), and [LSP servers](#lsp-servers) have different semantics for handling multiple sources.

233 401 

234* If `commands/` exists, it's loaded in addition to custom command paths402* All paths must be relative to the plugin root and start with `./`

235* All paths must be relative to plugin root and start with `./`403* Components from custom paths use the same naming and namespacing rules

236* Commands from custom paths use the same naming and namespacing rules404* Multiple paths can be specified as arrays

237* Multiple paths can be specified as arrays for flexibility405* To keep the default directory and add more paths for commands, agents, skills, or output styles, include the default in your array: `"commands": ["./commands/", "./extras/deploy.md"]`

238 406 

239**Path examples**:407**Path examples**:

240 408 


253 421 

254### Environment variables422### Environment variables

255 423 

256**`${CLAUDE_PLUGIN_ROOT}`**: Contains the absolute path to your plugin directory. Use this in hooks, MCP servers, and scripts to ensure correct paths regardless of installation location.424Claude 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.

425 

426**`${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.

427 

428**`${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.

257 429 

258```json theme={null}430```json theme={null}

259{431{


272}444}

273```445```

274 446 

447#### Persistent data directory

448 

449The `${CLAUDE_PLUGIN_DATA}` directory resolves to `~/.claude/plugins/data/{id}/`, where `{id}` is the plugin identifier with characters outside `a-z`, `A-Z`, `0-9`, `_`, and `-` replaced by `-`. For a plugin installed as `formatter@my-marketplace`, the directory is `~/.claude/plugins/data/formatter-my-marketplace/`.

450 

451A common use is installing language dependencies once and reusing them across sessions and plugin updates. Because the data directory outlives any single plugin version, a check for directory existence alone cannot detect when an update changes the plugin's dependency manifest. The recommended pattern compares the bundled manifest against a copy in the data directory and reinstalls when they differ.

452 

453This `SessionStart` hook installs `node_modules` on the first run and again whenever a plugin update includes a changed `package.json`:

454 

455```json theme={null}

456{

457 "hooks": {

458 "SessionStart": [

459 {

460 "hooks": [

461 {

462 "type": "command",

463 "command": "diff -q \"${CLAUDE_PLUGIN_ROOT}/package.json\" \"${CLAUDE_PLUGIN_DATA}/package.json\" >/dev/null 2>&1 || (cd \"${CLAUDE_PLUGIN_DATA}\" && cp \"${CLAUDE_PLUGIN_ROOT}/package.json\" . && npm install) || rm -f \"${CLAUDE_PLUGIN_DATA}/package.json\""

464 }

465 ]

466 }

467 ]

468 }

469}

470```

471 

472The `diff` exits nonzero when the stored copy is missing or differs from the bundled one, covering both first run and dependency-changing updates. If `npm install` fails, the trailing `rm` removes the copied manifest so the next session retries.

473 

474Scripts bundled in `${CLAUDE_PLUGIN_ROOT}` can then run against the persisted `node_modules`:

475 

476```json theme={null}

477{

478 "mcpServers": {

479 "routines": {

480 "command": "node",

481 "args": ["${CLAUDE_PLUGIN_ROOT}/server.js"],

482 "env": {

483 "NODE_PATH": "${CLAUDE_PLUGIN_DATA}/node_modules"

484 }

485 }

486 }

487}

488```

489 

490The data directory is deleted automatically when you uninstall the plugin from the last scope where it is installed. The `/plugin` interface shows the directory size and prompts before deleting. The CLI deletes by default; pass [`--keep-data`](#plugin-uninstall) to preserve it.

491 

492***

493 

494## Plugin caching and file resolution

495 

496Plugins are specified in one of two ways:

497 

498* Through `claude --plugin-dir`, for the duration of a session.

499* Through a marketplace, installed for future sessions.

500 

501For 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.

502 

503### Path traversal limitations

504 

505Installed plugins cannot reference files outside their directory. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache.

506 

507### Working with external dependencies

508 

509If your plugin needs to access files outside its directory, you can create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process:

510 

511```bash theme={null}

512# Inside your plugin directory

513ln -s /path/to/shared-utils ./shared-utils

514```

515 

516The symlinked content will be copied into the plugin cache. This provides flexibility while maintaining the security benefits of the caching system.

517 

275***518***

276 519 

277## Plugin directory structure520## Plugin directory structure


280 523 

281A complete plugin follows this structure:524A complete plugin follows this structure:

282 525 

283```526```text theme={null}

284enterprise-plugin/527enterprise-plugin/

285├── .claude-plugin/ # Metadata directory528├── .claude-plugin/ # Metadata directory (optional)

286│ └── plugin.json # Required: plugin manifest529│ └── plugin.json # plugin manifest

287├── commands/ # Default command location530├── commands/ # Default command location

288│ ├── status.md531│ ├── status.md

289│ └── logs.md532│ └── logs.md


297│ └── pdf-processor/540│ └── pdf-processor/

298│ ├── SKILL.md541│ ├── SKILL.md

299│ └── scripts/542│ └── scripts/

543├── output-styles/ # Output style definitions

544│ └── terse.md

300├── hooks/ # Hook configurations545├── hooks/ # Hook configurations

301│ ├── hooks.json # Main hook config546│ ├── hooks.json # Main hook config

302│ └── security-hooks.json # Additional hooks547│ └── security-hooks.json # Additional hooks

548├── bin/ # Plugin executables added to PATH

549│ └── my-tool # Invokable as bare command in Bash tool

550├── settings.json # Default settings for the plugin

303├── .mcp.json # MCP server definitions551├── .mcp.json # MCP server definitions

552├── .lsp.json # LSP server configurations

304├── scripts/ # Hook and utility scripts553├── scripts/ # Hook and utility scripts

305│ ├── security-scan.sh554│ ├── security-scan.sh

306│ ├── format-code.py555│ ├── format-code.py


310```559```

311 560 

312<Warning>561<Warning>

313 The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.562 The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, output-styles/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.

314</Warning>563</Warning>

315 564 

316### File locations reference565### File locations reference

317 566 

318| Component | Default Location | Purpose |567| Component | Default Location | Purpose |

319| :-------------- | :--------------------------- | :------------------------------- |568| :---------------- | :--------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |

320| **Manifest** | `.claude-plugin/plugin.json` | Required metadata file |569| **Manifest** | `.claude-plugin/plugin.json` | Plugin metadata and configuration (optional) |

321| **Commands** | `commands/` | Slash command markdown files |570| **Commands** | `commands/` | Skill Markdown files (legacy; use `skills/` for new skills) |

322| **Agents** | `agents/` | Subagent markdown files |571| **Agents** | `agents/` | Subagent Markdown files |

323| **Skills** | `skills/` | Agent Skills with SKILL.md files |572| **Skills** | `skills/` | Skills with `<name>/SKILL.md` structure |

573| **Output styles** | `output-styles/` | Output style definitions |

324| **Hooks** | `hooks/hooks.json` | Hook configuration |574| **Hooks** | `hooks/hooks.json` | Hook configuration |

325| **MCP servers** | `.mcp.json` | MCP server definitions |575| **MCP servers** | `.mcp.json` | MCP server definitions |

576| **LSP servers** | `.lsp.json` | Language server configurations |

577| **Executables** | `bin/` | Executables added to the Bash tool's `PATH`. Files here are invokable as bare commands in any Bash tool call while the plugin is enabled |

578| **Settings** | `settings.json` | Default configuration applied when the plugin is enabled. Only [`agent`](/en/sub-agents) settings are currently supported |

326 579 

327***580***

328 581 

329## Debugging and development tools582## CLI commands reference

330 583 

331### Debugging commands584Claude Code provides CLI commands for non-interactive plugin management, useful for scripting and automation.

332 585 

333Use `claude --debug` to see plugin loading details:586### plugin install

587 

588Install a plugin from available marketplaces.

589 

590```bash theme={null}

591claude plugin install <plugin> [options]

592```

593 

594**Arguments:**

595 

596* `<plugin>`: Plugin name or `plugin-name@marketplace-name` for a specific marketplace

597 

598**Options:**

599 

600| Option | Description | Default |

601| :-------------------- | :------------------------------------------------ | :------ |

602| `-s, --scope <scope>` | Installation scope: `user`, `project`, or `local` | `user` |

603| `-h, --help` | Display help for command | |

604 

605Scope determines which settings file the installed plugin is added to. For example, `--scope project` writes to `enabledPlugins` in .claude/settings.json, making the plugin available to everyone who clones the project repository.

606 

607**Examples:**

608 

609```bash theme={null}

610# Install to user scope (default)

611claude plugin install formatter@my-marketplace

612 

613# Install to project scope (shared with team)

614claude plugin install formatter@my-marketplace --scope project

615 

616# Install to local scope (gitignored)

617claude plugin install formatter@my-marketplace --scope local

618```

619 

620### plugin uninstall

621 

622Remove an installed plugin.

623 

624```bash theme={null}

625claude plugin uninstall <plugin> [options]

626```

627 

628**Arguments:**

629 

630* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

631 

632**Options:**

633 

634| Option | Description | Default |

635| :-------------------- | :---------------------------------------------------------------------------- | :------ |

636| `-s, --scope <scope>` | Uninstall from scope: `user`, `project`, or `local` | `user` |

637| `--keep-data` | Preserve the plugin's [persistent data directory](#persistent-data-directory) | |

638| `-h, --help` | Display help for command | |

639 

640**Aliases:** `remove`, `rm`

641 

642By 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.

643 

644### plugin enable

645 

646Enable a disabled plugin.

647 

648```bash theme={null}

649claude plugin enable <plugin> [options]

650```

651 

652**Arguments:**

653 

654* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

655 

656**Options:**

657 

658| Option | Description | Default |

659| :-------------------- | :--------------------------------------------- | :------ |

660| `-s, --scope <scope>` | Scope to enable: `user`, `project`, or `local` | `user` |

661| `-h, --help` | Display help for command | |

662 

663### plugin disable

664 

665Disable a plugin without uninstalling it.

334 666 

335```bash theme={null}667```bash theme={null}

336claude --debug668claude plugin disable <plugin> [options]

337```669```

338 670 

671**Arguments:**

672 

673* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

674 

675**Options:**

676 

677| Option | Description | Default |

678| :-------------------- | :---------------------------------------------- | :------ |

679| `-s, --scope <scope>` | Scope to disable: `user`, `project`, or `local` | `user` |

680| `-h, --help` | Display help for command | |

681 

682### plugin update

683 

684Update a plugin to the latest version.

685 

686```bash theme={null}

687claude plugin update <plugin> [options]

688```

689 

690**Arguments:**

691 

692* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

693 

694**Options:**

695 

696| Option | Description | Default |

697| :-------------------- | :-------------------------------------------------------- | :------ |

698| `-s, --scope <scope>` | Scope to update: `user`, `project`, `local`, or `managed` | `user` |

699| `-h, --help` | Display help for command | |

700 

701***

702 

703## Debugging and development tools

704 

705### Debugging commands

706 

707Use `claude --debug` to see plugin loading details:

708 

339This shows:709This shows:

340 710 

341* Which plugins are being loaded711* Which plugins are being loaded


346### Common issues716### Common issues

347 717 

348| Issue | Cause | Solution |718| Issue | Cause | Solution |

349| :--------------------- | :------------------------------ | :--------------------------------------------------- |719| :---------------------------------- | :------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- |

350| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax |720| Plugin not loading | Invalid `plugin.json` | Run `claude plugin validate` or `/plugin validate` to check `plugin.json`, skill/agent/command frontmatter, and `hooks/hooks.json` for syntax and schema errors |

351| Commands not appearing | Wrong directory structure | Ensure `commands/` at root, not in `.claude-plugin/` |721| Commands not appearing | Wrong directory structure | Ensure `commands/` at root, not in `.claude-plugin/` |

352| Hooks not firing | Script not executable | Run `chmod +x script.sh` |722| Hooks not firing | Script not executable | Run `chmod +x script.sh` |

353| MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths |723| MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths |

354| Path errors | Absolute paths used | All paths must be relative and start with `./` |724| Path errors | Absolute paths used | All paths must be relative and start with `./` |

725| LSP `Executable not found in $PATH` | Language server not installed | Install the binary (e.g., `npm install -g typescript-language-server typescript`) |

726 

727### Example error messages

728 

729**Manifest validation errors**:

730 

731* `Invalid JSON syntax: Unexpected token } in JSON at position 142`: check for missing commas, extra commas, or unquoted strings

732* `Plugin has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: name: Required`: a required field is missing

733* `Plugin has a corrupt manifest file at .claude-plugin/plugin.json. JSON parse error: ...`: JSON syntax error

734 

735**Plugin loading errors**:

736 

737* `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`: command path exists but contains no valid command files

738* `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`: the `source` path in marketplace.json points to a non-existent directory

739* `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`: remove duplicate component definitions or remove `strict: false` in marketplace entry

740 

741### Hook troubleshooting

742 

743**Hook script not executing**:

744 

7451. Check the script is executable: `chmod +x ./scripts/your-script.sh`

7462. Verify the shebang line: First line should be `#!/bin/bash` or `#!/usr/bin/env bash`

7473. Check the path uses `${CLAUDE_PLUGIN_ROOT}`: `"command": "${CLAUDE_PLUGIN_ROOT}/scripts/your-script.sh"`

7484. Test the script manually: `./scripts/your-script.sh`

749 

750**Hook not triggering on expected events**:

751 

7521. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse`

7532. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations

7543. Confirm the hook type is valid: `command`, `http`, `prompt`, or `agent`

755 

756### MCP server troubleshooting

757 

758**Server not starting**:

759 

7601. Check the command exists and is executable

7612. Verify all paths use `${CLAUDE_PLUGIN_ROOT}` variable

7623. Check the MCP server logs: `claude --debug` shows initialization errors

7634. Test the server manually outside of Claude Code

764 

765**Server tools not appearing**:

766 

7671. Ensure the server is properly configured in `.mcp.json` or `plugin.json`

7682. Verify the server implements the MCP protocol correctly

7693. Check for connection timeouts in debug output

770 

771### Directory structure mistakes

772 

773**Symptoms**: Plugin loads but components (commands, agents, hooks) are missing.

774 

775**Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`.

776 

777```text theme={null}

778my-plugin/

779├── .claude-plugin/

780│ └── plugin.json ← Only manifest here

781├── commands/ ← At root level

782├── agents/ ← At root level

783└── hooks/ ← At root level

784```

785 

786If your components are inside `.claude-plugin/`, move them to the plugin root.

787 

788**Debug checklist**:

789 

7901. Run `claude --debug` and look for "loading plugin" messages

7912. Check that each component directory is listed in the debug output

7923. Verify file permissions allow reading the plugin files

355 793 

356***794***

357 795 


362Follow semantic versioning for plugin releases:800Follow semantic versioning for plugin releases:

363 801 

364```json theme={null}802```json theme={null}

803{

804 "name": "my-plugin",

805 "version": "2.1.0"

806}

807```

808 

809**Version format**: `MAJOR.MINOR.PATCH`

810 

811* **MAJOR**: Breaking changes (incompatible API changes)

812* **MINOR**: New features (backward-compatible additions)

813* **PATCH**: Bug fixes (backward-compatible fixes)

814 

815**Best practices**:

816 

817* Start at `1.0.0` for your first stable release

818* Update the version in `plugin.json` before distributing changes

819* Document changes in a `CHANGELOG.md` file

820* Use pre-release versions like `2.0.0-beta.1` for testing

821 

822<Warning>

823 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.

824 

825 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`.

826</Warning>

827 

828***

365 829 

366## See also830## See also

367 831 

368- [Plugins](/en/docs/claude-code/plugins) - Tutorials and practical usage832* [Plugins](/en/plugins) - Tutorials and practical usage

369- [Plugin marketplaces](/en/docs/claude-code/plugin-marketplaces) - Creating and managing marketplaces833* [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces

370- [Slash commands](/en/docs/claude-code/slash-commands) - Command development details834* [Skills](/en/skills) - Skill development details

371- [Subagents](/en/docs/claude-code/sub-agents) - Agent configuration and capabilities835* [Subagents](/en/sub-agents) - Agent configuration and capabilities

372- [Agent Skills](/en/docs/claude-code/skills) - Extend Claude's capabilities836* [Hooks](/en/hooks) - Event handling and automation

373- [Hooks](/en/docs/claude-code/hooks) - Event handling and automation837* [MCP](/en/mcp) - External tool integration

374- [MCP](/en/docs/claude-code/mcp) - External tool integration838* [Settings](/en/settings) - Configuration options for plugins

375- [Settings](/en/docs/claude-code/settings) - Configuration options for plugins

376```

quickstart.md +111 −96

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Quickstart5# Quickstart

2 6 

3> Welcome to Claude Code!7> Welcome to Claude Code!

4 8 

5This quickstart guide will have you using AI-powered coding assistance in just a few minutes. By the end, you'll understand how to use Claude Code for common development tasks.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.

12 

13<Experiment flag="quickstart-install-configurator" treatment={<InstallConfigurator />} />

6 14 

7## Before you begin15## Before you begin

8 16 

9Make sure you have:17Make sure you have:

10 18 

11* A terminal or command prompt open19* A terminal or command prompt open

20 * If you've never used the terminal before, check out the [terminal guide](/en/terminal-guide)

12* A code project to work with21* A code project to work with

13* A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account22* A [Claude subscription](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq) (Pro, Max, Team, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/en/third-party-integrations)

23 

24<Note>

25 This guide covers the terminal CLI. Claude Code is also available on the [web](https://claude.ai/code), as a [desktop app](/en/desktop), in [VS Code](/en/vs-code) and [JetBrains IDEs](/en/jetbrains), in [Slack](/en/slack), and in CI/CD with [GitHub Actions](/en/github-actions) and [GitLab](/en/gitlab-ci-cd). See [all interfaces](/en/overview#use-claude-code-everywhere).

26</Note>

14 27 

15## Step 1: Install Claude Code28## Step 1: Install Claude Code

16 29 


18 31 

19<Tabs>32<Tabs>

20 <Tab title="Native Install (Recommended)">33 <Tab title="Native Install (Recommended)">

21 **Homebrew (macOS, Linux):**

22 

23 ```sh theme={null}

24 brew install --cask claude-code

25 ```

26 

27 **macOS, Linux, WSL:**34 **macOS, Linux, WSL:**

28 35 

29 ```bash theme={null}36 ```bash theme={null}


41 ```batch theme={null}48 ```batch theme={null}

42 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd49 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

43 ```50 ```

51 

52 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. Use the PowerShell command above instead. Your prompt shows `PS C:\` when you're in PowerShell.

53 

54 **Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it.

55 

56 <Info>

57 Native installations automatically update in the background to keep you on the latest version.

58 </Info>

44 </Tab>59 </Tab>

45 60 

46 <Tab title="NPM">61 <Tab title="Homebrew">

47 If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/):62 ```bash theme={null}

63 brew install --cask claude-code

64 ```

65 

66 <Info>

67 Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

68 </Info>

69 </Tab>

48 70 

49 ```sh theme={null}71 <Tab title="WinGet">

50 npm install -g @anthropic-ai/claude-code72 ```powershell theme={null}

73 winget install Anthropic.ClaudeCode

51 ```74 ```

75 

76 <Info>

77 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

78 </Info>

52 </Tab>79 </Tab>

53</Tabs>80</Tabs>

54 81 


66# Follow the prompts to log in with your account93# Follow the prompts to log in with your account

67```94```

68 95 

69You can log in using either account type:96You can log in using any of these account types:

70 

71* [Claude.ai](https://claude.ai) (subscription plans - recommended)

72* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits)

73 97 

74Once logged in, your credentials are stored and you won't need to log in again.98* [Claude Pro, Max, Team, or Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login) (recommended)

99* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits). On first login, a "Claude Code" workspace is automatically created in the Console for centralized cost tracking.

100* [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) (enterprise cloud providers)

75 101 

76<Note>102Once logged in, your credentials are stored and you won't need to log in again. To switch accounts later, use the `/login` command.

77 When you first authenticate Claude Code with your Claude Console account, a workspace called "Claude Code" is automatically created for you. This workspace provides centralized cost tracking and management for all Claude Code usage in your organization.

78</Note>

79 

80<Note>

81 You can have both account types under the same email address. If you need to log in again or switch accounts, use the `/login` command within Claude Code.

82</Note>

83 103 

84## Step 3: Start your first session104## Step 3: Start your first session

85 105 


93You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.113You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.

94 114 

95<Tip>115<Tip>

96 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/docs/claude-code/iam#credential-management).116 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/authentication#credential-management).

97</Tip>117</Tip>

98 118 

99## Step 4: Ask your first question119## Step 4: Ask your first question

100 120 

101Let's start with understanding your codebase. Try one of these commands:121Let's start with understanding your codebase. Try one of these commands:

102 122 

103```123```text theme={null}

104> what does this project do?124what does this project do?

105```125```

106 126 

107Claude will analyze your files and provide a summary. You can also ask more specific questions:127Claude will analyze your files and provide a summary. You can also ask more specific questions:

108 128 

109```129```text theme={null}

110> what technologies does this project use?130what technologies does this project use?

111```131```

112 132 

113```133```text theme={null}

114> where is the main entry point?134where is the main entry point?

115```135```

116 136 

117```137```text theme={null}

118> explain the folder structure138explain the folder structure

119```139```

120 140 

121You can also ask Claude about its own capabilities:141You can also ask Claude about its own capabilities:

122 142 

123```143```text theme={null}

124> what can Claude Code do?144what can Claude Code do?

125```145```

126 146 

127```147```text theme={null}

128> how do I use slash commands in Claude Code?148how do I create custom skills in Claude Code?

129```149```

130 150 

131```151```text theme={null}

132> can Claude Code work with Docker?152can Claude Code work with Docker?

133```153```

134 154 

135<Note>155<Note>

136 Claude Code reads your files as needed - you don't have to manually add context. Claude also has access to its own documentation and can answer questions about its features and capabilities.156 Claude Code reads your project files as needed. You don't have to manually add context.

137</Note>157</Note>

138 158 

139## Step 5: Make your first code change159## Step 5: Make your first code change

140 160 

141Now let's make Claude Code do some actual coding. Try a simple task:161Now let's make Claude Code do some actual coding. Try a simple task:

142 162 

143```163```text theme={null}

144> add a hello world function to the main file164add a hello world function to the main file

145```165```

146 166 

147Claude Code will:167Claude Code will:


159 179 

160Claude Code makes Git operations conversational:180Claude Code makes Git operations conversational:

161 181 

162```182```text theme={null}

163> what files have I changed?183what files have I changed?

164```184```

165 185 

166```186```text theme={null}

167> commit my changes with a descriptive message187commit my changes with a descriptive message

168```188```

169 189 

170You can also prompt for more complex Git operations:190You can also prompt for more complex Git operations:

171 191 

172```192```text theme={null}

173> create a new branch called feature/quickstart193create a new branch called feature/quickstart

174```194```

175 195 

176```196```text theme={null}

177> show me the last 5 commits197show me the last 5 commits

178```198```

179 199 

180```200```text theme={null}

181> help me resolve merge conflicts201help me resolve merge conflicts

182```202```

183 203 

184## Step 7: Fix a bug or add a feature204## Step 7: Fix a bug or add a feature


187 207 

188Describe what you want in natural language:208Describe what you want in natural language:

189 209 

190```210```text theme={null}

191> add input validation to the user registration form211add input validation to the user registration form

192```212```

193 213 

194Or fix existing issues:214Or fix existing issues:

195 215 

196```216```text theme={null}

197> there's a bug where users can submit empty forms - fix it217there's a bug where users can submit empty forms - fix it

198```218```

199 219 

200Claude Code will:220Claude Code will:


210 230 

211**Refactor code**231**Refactor code**

212 232 

213```233```text theme={null}

214> refactor the authentication module to use async/await instead of callbacks234refactor the authentication module to use async/await instead of callbacks

215```235```

216 236 

217**Write tests**237**Write tests**

218 238 

219```239```text theme={null}

220> write unit tests for the calculator functions240write unit tests for the calculator functions

221```241```

222 242 

223**Update documentation**243**Update documentation**

224 244 

225```245```text theme={null}

226> update the README with installation instructions246update the README with installation instructions

227```247```

228 248 

229**Code review**249**Code review**

230 250 

231```251```text theme={null}

232> review my changes and suggest improvements252review my changes and suggest improvements

233```253```

234 254 

235<Tip>255<Tip>

236 **Remember**: Claude Code is your AI pair programmer. Talk to it like you would a helpful colleague - describe what you want to achieve, and it will help you get there.256 Talk to Claude like you would a helpful colleague. Describe what you want to achieve, and it will help you get there.

237</Tip>257</Tip>

238 258 

239## Essential commands259## Essential commands


241Here are the most important commands for daily use:261Here are the most important commands for daily use:

242 262 

243| Command | What it does | Example |263| Command | What it does | Example |

244| ------------------- | --------------------------------- | ----------------------------------- |264| ------------------- | ------------------------------------------------------ | ----------------------------------- |

245| `claude` | Start interactive mode | `claude` |265| `claude` | Start interactive mode | `claude` |

246| `claude "task"` | Run a one-time task | `claude "fix the build error"` |266| `claude "task"` | Run a one-time task | `claude "fix the build error"` |

247| `claude -p "query"` | Run one-off query, then exit | `claude -p "explain this function"` |267| `claude -p "query"` | Run one-off query, then exit | `claude -p "explain this function"` |

248| `claude -c` | Continue most recent conversation | `claude -c` |268| `claude -c` | Continue most recent conversation in current directory | `claude -c` |

249| `claude -r` | Resume a previous conversation | `claude -r` |269| `claude -r` | Resume a previous conversation | `claude -r` |

250| `claude commit` | Create a Git commit | `claude commit` |270| `/clear` | Clear conversation history | `/clear` |

251| `/clear` | Clear conversation history | `> /clear` |271| `/help` | Show available commands | `/help` |

252| `/help` | Show available commands | `> /help` |272| `exit` or Ctrl+D | Exit Claude Code | `exit` |

253| `exit` or Ctrl+C | Exit Claude Code | `> exit` |

254 273 

255See the [CLI reference](/en/docs/claude-code/cli-reference) for a complete list of commands.274See the [CLI reference](/en/cli-reference) for a complete list of commands.

256 275 

257## Pro tips for beginners276## Pro tips for beginners

258 277 

278For more, see [best practices](/en/best-practices) and [common workflows](/en/common-workflows).

279 

259<AccordionGroup>280<AccordionGroup>

260 <Accordion title="Be specific with your requests">281 <Accordion title="Be specific with your requests">

261 Instead of: "fix the bug"282 Instead of: "fix the bug"


266 <Accordion title="Use step-by-step instructions">287 <Accordion title="Use step-by-step instructions">

267 Break complex tasks into steps:288 Break complex tasks into steps:

268 289 

269 ```290 ```text theme={null}

270 > 1. create a new database table for user profiles291 1. create a new database table for user profiles

271 ```292 2. create an API endpoint to get and update user profiles

272 293 3. build a webpage that allows users to see and edit their information

273 ```

274 > 2. create an API endpoint to get and update user profiles

275 ```

276 

277 ```

278 > 3. build a webpage that allows users to see and edit their information

279 ```294 ```

280 </Accordion>295 </Accordion>

281 296 

282 <Accordion title="Let Claude explore first">297 <Accordion title="Let Claude explore first">

283 Before making changes, let Claude understand your code:298 Before making changes, let Claude understand your code:

284 299 

285 ```300 ```text theme={null}

286 > analyze the database schema301 analyze the database schema

287 ```302 ```

288 303 

289 ```304 ```text theme={null}

290 > build a dashboard showing products that are most frequently returned by our UK customers305 build a dashboard showing products that are most frequently returned by our UK customers

291 ```306 ```

292 </Accordion>307 </Accordion>

293 308 


295 * Press `?` to see all available keyboard shortcuts310 * Press `?` to see all available keyboard shortcuts

296 * Use Tab for command completion311 * Use Tab for command completion

297 * Press ↑ for command history312 * Press ↑ for command history

298 * Type `/` to see all slash commands313 * Type `/` to see all commands and skills

299 </Accordion>314 </Accordion>

300</AccordionGroup>315</AccordionGroup>

301 316 


303 318 

304Now that you've learned the basics, explore more advanced features:319Now that you've learned the basics, explore more advanced features:

305 320 

306<CardGroup cols={3}>321<CardGroup cols={2}>

307 <Card title="Common workflows" icon="graduation-cap" href="/en/docs/claude-code/common-workflows">322 <Card title="How Claude Code works" icon="microchip" href="/en/how-claude-code-works">

308 Step-by-step guides for common tasks323 Understand the agentic loop, built-in tools, and how Claude Code interacts with your project

309 </Card>324 </Card>

310 325 

311 <Card title="CLI reference" icon="terminal" href="/en/docs/claude-code/cli-reference">326 <Card title="Best practices" icon="star" href="/en/best-practices">

312 Master all commands and options327 Get better results with effective prompting and project setup

313 </Card>328 </Card>

314 329 

315 <Card title="Configuration" icon="gear" href="/en/docs/claude-code/settings">330 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">

316 Customize Claude Code for your workflow331 Step-by-step guides for common tasks

317 </Card>332 </Card>

318 333 

319 <Card title="Claude Code on the web" icon="cloud" href="/en/docs/claude-code/claude-code-on-the-web">334 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">

320 Run tasks asynchronously in the cloud335 Customize with CLAUDE.md, skills, hooks, MCP, and more

321 </Card>336 </Card>

322</CardGroup>337</CardGroup>

323 338 

remote-control.md +205 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Continue local sessions from any device with Remote Control

6 

7> Continue a local Claude Code session from your phone, tablet, or any browser using Remote Control. Works with claude.ai/code and the Claude mobile app.

8 

9<Note>

10 Remote Control is available on all plans. 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>

12 

13Remote Control connects [claude.ai/code](https://claude.ai/code) or the Claude app for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) and [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude) to a Claude Code session running on your machine. Start a task at your desk, then pick it up from your phone on the couch or a browser on another computer.

14 

15When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so nothing moves to the cloud. With Remote Control you can:

16 

17* **Use your full local environment remotely**: your filesystem, [MCP servers](/en/mcp), tools, and project configuration all stay available

18* **Work from both surfaces at once**: the conversation stays in sync across all connected devices, so you can send messages from your terminal, browser, and phone interchangeably

19* **Survive interruptions**: if your laptop sleeps or your network drops, the session reconnects automatically when your machine comes back online

20 

21Unlike [Claude Code on the web](/en/claude-code-on-the-web), which runs on cloud infrastructure, Remote Control sessions run directly on your machine and interact with your local filesystem. The web and mobile interfaces are just a window into that local session.

22 

23<Note>

24 Remote Control requires Claude Code v2.1.51 or later. Check your version with `claude --version`.

25</Note>

26 

27This page covers setup, how to start and connect to sessions, and how Remote Control compares to Claude Code on the web.

28 

29## Requirements

30 

31Before using Remote Control, confirm that your environment meets these conditions:

32 

33* **Subscription**: available on Pro, Max, Team, and Enterprise plans. API keys are not supported. On Team and Enterprise, an admin must first enable the Remote Control toggle in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code).

34* **Authentication**: run `claude` and use `/login` to sign in through claude.ai if you haven't already.

35* **Workspace trust**: run `claude` in your project directory at least once to accept the workspace trust dialog.

36 

37## Start a Remote Control session

38 

39You can start a dedicated Remote Control server, start an interactive session with Remote Control enabled, or connect a session that's already running.

40 

41<Tabs>

42 <Tab title="Server mode">

43 Navigate to your project directory and run:

44 

45 ```bash theme={null}

46 claude remote-control

47 ```

48 

49 The process stays running in your terminal in server mode, waiting for remote connections. It displays a session URL you can use to [connect from another device](#connect-from-another-device), and you can press spacebar to show a QR code for quick access from your phone. While a remote session is active, the terminal shows connection status and tool activity.

50 

51 Available flags:

52 

53 | Flag | Description |

54 | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

55 | `--name "My Project"` | Set a custom session title visible in the session list at claude.ai/code. |

56 | `--spawn <mode>` | How concurrent sessions are created. Press `w` at runtime to toggle.<br />• `same-dir` (default): all sessions share the current working directory, so they can conflict if editing the same files.<br />• `worktree`: each on-demand session gets its own [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Requires a git repository. |

57 | `--capacity <N>` | Maximum number of concurrent sessions. Default is 32. |

58 | `--verbose` | Show detailed connection and session logs. |

59 | `--sandbox` / `--no-sandbox` | Enable or disable [sandboxing](/en/sandboxing) for filesystem and network isolation. Off by default. |

60 </Tab>

61 

62 <Tab title="Interactive session">

63 To start a normal interactive Claude Code session with Remote Control enabled, use the `--remote-control` flag (or `--rc`):

64 

65 ```bash theme={null}

66 claude --remote-control

67 ```

68 

69 Optionally pass a name for the session:

70 

71 ```bash theme={null}

72 claude --remote-control "My Project"

73 ```

74 

75 This gives you a full interactive session in your terminal that you can also control from claude.ai or the Claude app. Unlike `claude remote-control` (server mode), you can type messages locally while the session is also available remotely.

76 </Tab>

77 

78 <Tab title="From an existing session">

79 If you're already in a Claude Code session and want to continue it remotely, use the `/remote-control` (or `/rc`) command:

80 

81 ```text theme={null}

82 /remote-control

83 ```

84 

85 Pass a name as an argument to set a custom session title:

86 

87 ```text theme={null}

88 /remote-control My Project

89 ```

90 

91 This starts a Remote Control session that carries over your current conversation history and displays a session URL and QR code you can use to [connect from another device](#connect-from-another-device). The `--verbose`, `--sandbox`, and `--no-sandbox` flags are not available with this command.

92 </Tab>

93</Tabs>

94 

95### Connect from another device

96 

97Once a Remote Control session is active, you have a few ways to connect from another device:

98 

99* **Open the session URL** in any browser to go directly to the session on [claude.ai/code](https://claude.ai/code). Both `claude remote-control` and `/remote-control` display this URL in the terminal.

100* **Scan the QR code** shown alongside the session URL to open it directly in the Claude app. With `claude remote-control`, press spacebar to toggle the QR code display.

101* **Open [claude.ai/code](https://claude.ai/code) or the Claude app** and find the session by name in the session list. Remote Control sessions show a computer icon with a green status dot when online.

102 

103The remote session title is chosen in this order:

104 

1051. The name you passed to `--name`, `--remote-control`, or `/remote-control`

1062. The title you set with `/rename`

1073. The last meaningful message in existing conversation history

1084. Your first prompt once you send one

109 

110If the environment already has an active session, you'll be asked whether to continue it or start a new one.

111 

112If you don't have the Claude app yet, use the `/mobile` command inside Claude Code to display a download QR code for [iOS](https://apps.apple.com/us/app/claude-by-anthropic/id6473753684) or [Android](https://play.google.com/store/apps/details?id=com.anthropic.claude).

113 

114### Enable Remote Control for all sessions

115 

116By default, Remote Control only activates when you explicitly run `claude remote-control`, `claude --remote-control`, or `/remote-control`. To enable it automatically for every interactive session, run `/config` inside Claude Code and set **Enable Remote Control for all sessions** to `true`. Set it back to `false` to disable.

117 

118With this setting on, each interactive Claude Code process registers one remote session. If you run multiple instances, each one gets its own environment and session. To run multiple concurrent sessions from a single process, use server mode with `--spawn` instead.

119 

120## Connection and security

121 

122Your local Claude Code session makes outbound HTTPS requests only and never opens inbound ports on your machine. When you start Remote Control, it registers with the Anthropic API and polls for work. When you connect from another device, the server routes messages between the web or mobile client and your local session over a streaming connection.

123 

124All traffic travels through the Anthropic API over TLS, the same transport security as any Claude Code session. The connection uses multiple short-lived credentials, each scoped to a single purpose and expiring independently.

125 

126## Remote Control vs Claude Code on the web

127 

128Remote Control and [Claude Code on the web](/en/claude-code-on-the-web) both use the claude.ai/code interface. The key difference is where the session runs: Remote Control executes on your machine, so your local MCP servers, tools, and project configuration stay available. Claude Code on the web executes in Anthropic-managed cloud infrastructure.

129 

130Use 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.

131 

132## Limitations

133 

134* **One remote session per interactive process**: outside of server mode, each Claude Code instance supports one remote session at a time. Use server mode with `--spawn` to run multiple concurrent sessions from a single process.

135* **Terminal must stay open**: Remote Control runs as a local process. If you close the terminal or stop the `claude` process, the session ends. Run `claude remote-control` again to start a new one.

136* **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.

137* **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.

138 

139## Troubleshooting

140 

141### "Remote Control requires a claude.ai subscription"

142 

143You're not authenticated with a claude.ai account. Run `claude auth login` and choose the claude.ai option. If `ANTHROPIC_API_KEY` is set in your environment, unset it first.

144 

145### "Remote Control requires a full-scope login token"

146 

147You're authenticated with a long-lived token from `claude setup-token` or the `CLAUDE_CODE_OAUTH_TOKEN` environment variable. These tokens are limited to inference-only and cannot establish Remote Control sessions. Run `claude auth login` to authenticate with a full-scope session token instead.

148 

149### "Unable to determine your organization for Remote Control eligibility"

150 

151Your cached account information is stale or incomplete. Run `claude auth login` to refresh it.

152 

153### "Remote Control is not yet enabled for your account"

154 

155The eligibility check can fail with certain environment variables present:

156 

157* `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or `DISABLE_TELEMETRY`: unset them and try again.

158* `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY`: Remote Control requires claude.ai authentication and does not work with third-party providers.

159 

160If none of these are set, run `/logout` then `/login` to refresh.

161 

162### "Remote Control is disabled by your organization's policy"

163 

164This error has three distinct causes. Run `/status` first to see which login method and subscription you're using.

165 

166* **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.

167* **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.

168* **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.

169 

170### "Remote credentials fetch failed"

171 

172Claude Code could not obtain a short-lived credential from the Anthropic API to establish the connection. Re-run with `--verbose` to see the full error:

173 

174```bash theme={null}

175claude remote-control --verbose

176```

177 

178Common causes:

179 

180* Not signed in: run `claude` and use `/login` to authenticate with your claude.ai account. API key authentication is not supported for Remote Control.

181* Network or proxy issue: a firewall or proxy may be blocking the outbound HTTPS request. Remote Control requires access to the Anthropic API on port 443.

182* Session creation failed: if you also see `Session creation failed — see debug log`, the failure happened earlier in setup. Check that your subscription is active.

183 

184## Choose the right approach

185 

186Claude Code offers several ways to work when you're not at your terminal. They differ in what triggers the work, where Claude runs, and how much you need to set up.

187 

188| | Trigger | Claude runs on | Setup | Best for |

189| :--------------------------------------------- | :--------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------ |

190| [Dispatch](/en/desktop#sessions-from-dispatch) | Message a task from the Claude mobile app | Your machine (Desktop) | [Pair the mobile app with Desktop](https://support.claude.com/en/articles/13947068) | Delegating work while you're away, minimal setup |

191| [Remote Control](/en/remote-control) | Drive a running session from [claude.ai/code](https://claude.ai/code) or the Claude mobile app | Your machine (CLI or VS Code) | Run `claude remote-control` | Steering in-progress work from another device |

192| [Channels](/en/channels) | Push events from a chat app like Telegram or Discord, or your own server | Your machine (CLI) | [Install a channel plugin](/en/channels#quickstart) or [build your own](/en/channels-reference) | Reacting to external events like CI failures or chat messages |

193| [Slack](/en/slack) | Mention `@Claude` in a team channel | Anthropic cloud | [Install the Slack app](/en/slack#setting-up-claude-code-in-slack) with [Claude Code on the web](/en/claude-code-on-the-web) enabled | PRs and reviews from team chat |

194| [Scheduled tasks](/en/scheduled-tasks) | Set a schedule | [CLI](/en/scheduled-tasks), [Desktop](/en/desktop-scheduled-tasks), or [cloud](/en/web-scheduled-tasks) | Pick a frequency | Recurring automation like daily reviews |

195 

196## Related resources

197 

198* [Claude Code on the web](/en/claude-code-on-the-web): run sessions in Anthropic-managed cloud environments instead of on your machine

199* [Ultraplan](/en/ultraplan): launch a cloud planning session from your terminal and review the plan in your browser

200* [Channels](/en/channels): forward Telegram, Discord, or iMessage into a session so Claude reacts to messages while you're away

201* [Dispatch](/en/desktop#sessions-from-dispatch): message a task from your phone and it can spawn a Desktop session to handle it

202* [Authentication](/en/authentication): set up `/login` and manage credentials for claude.ai

203* [CLI reference](/en/cli-reference): full list of flags and commands including `claude remote-control`

204* [Security](/en/security): how Remote Control sessions fit into the Claude Code security model

205* [Data usage](/en/data-usage): what data flows through the Anthropic API during local and remote sessions

sandboxing.md +138 −19

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Sandboxing5# Sandboxing

2 6 

3> Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution.7> Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution.


38* **Blocked access**: Cannot modify files outside the current working directory without explicit permission42* **Blocked access**: Cannot modify files outside the current working directory without explicit permission

39* **Configurable**: Define custom allowed and denied paths through settings43* **Configurable**: Define custom allowed and denied paths through settings

40 44 

45You can grant write access to additional paths using `sandbox.filesystem.allowWrite` in your settings. These restrictions are enforced at the OS level (Seatbelt on macOS, bubblewrap on Linux), so they apply to all subprocess commands, including tools like `kubectl`, `terraform`, and `npm`, not just Claude's file tools.

46 

41### Network isolation47### Network isolation

42 48 

43Network access is controlled through a proxy server running outside the sandbox:49Network access is controlled through a proxy server running outside the sandbox:

44 50 

45* **Domain restrictions**: Only approved domains can be accessed51* **Domain restrictions**: Only approved domains can be accessed

46* **User confirmation**: New domain requests trigger permission prompts52* **User confirmation**: New domain requests trigger permission prompts (unless [`allowManagedDomainsOnly`](/en/settings#sandbox-settings) is enabled, which blocks non-allowed domains automatically)

47* **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic53* **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic

48* **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands54* **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands

49 55 


51 57 

52The sandboxed bash tool leverages operating system security primitives:58The sandboxed bash tool leverages operating system security primitives:

53 59 

54* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation

55* **macOS**: Uses Seatbelt for sandbox enforcement60* **macOS**: Uses Seatbelt for sandbox enforcement

61* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation

62* **WSL2**: Uses bubblewrap, same as Linux

63 

64WSL1 is not supported because bubblewrap requires kernel features only available in WSL2.

56 65 

57These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries.66These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries.

58 67 

59## Getting started68## Getting started

60 69 

70### Prerequisites

71 

72On **macOS**, sandboxing works out of the box using the built-in Seatbelt framework.

73 

74On **Linux and WSL2**, install the required packages first:

75 

76<Tabs>

77 <Tab title="Ubuntu/Debian">

78 ```bash theme={null}

79 sudo apt-get install bubblewrap socat

80 ```

81 </Tab>

82 

83 <Tab title="Fedora">

84 ```bash theme={null}

85 sudo dnf install bubblewrap socat

86 ```

87 </Tab>

88</Tabs>

89 

61### Enable sandboxing90### Enable sandboxing

62 91 

63You can enable sandboxing by running the `/sandbox` slash command:92You can enable sandboxing by running the `/sandbox` command:

64 93 

94```text theme={null}

95/sandbox

65```96```

66> /sandbox

67```

68 97 

69This activates the sandboxed bash tool with default settings, allowing access to your current working directory while blocking access to sensitive system locations.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.

99 

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.

101 

102### Sandbox modes

103 

104Claude Code offers two sandbox modes:

105 

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.

107 

108**Regular permissions mode**: All bash commands go through the standard permission flow, even when sandboxed. This provides more control but requires more approvals.

109 

110In both modes, the sandbox enforces the same filesystem and network restrictions. The difference is only in whether sandboxed commands are auto-approved or require explicit permission.

111 

112<Info>

113 Auto-allow mode works independently of your permission mode setting. Even if you're not in "accept edits" mode, sandboxed bash commands will run automatically when auto-allow is enabled. This means bash commands that modify files within the sandbox boundaries will execute without prompting, even when file edit tools would normally require approval.

114</Info>

70 115 

71### Configure sandboxing116### Configure sandboxing

72 117 

73Customize sandbox behavior through your `settings.json` file. See [Settings](/en/docs/claude-code/settings#sandbox-settings) for complete configuration reference.118Customize sandbox behavior through your `settings.json` file. See [Settings](/en/settings#sandbox-settings) for complete configuration reference.

119 

120#### Granting subprocess write access to specific paths

121 

122By default, sandboxed commands can only write to the current working directory. If subprocess commands like `kubectl`, `terraform`, or `npm` need to write outside the project directory, use `sandbox.filesystem.allowWrite` to grant access to specific paths:

123 

124```json theme={null}

125{

126 "sandbox": {

127 "enabled": true,

128 "filesystem": {

129 "allowWrite": ["~/.kube", "/tmp/build"]

130 }

131 }

132}

133```

134 

135These paths are enforced at the OS level, so all commands running inside the sandbox, including their child processes, respect them. This is the recommended approach when a tool needs write access to a specific location, rather than excluding the tool from the sandbox entirely with `excludedCommands`.

136 

137When `allowWrite` (or `denyWrite`/`denyRead`/`allowRead`) is defined in multiple [settings scopes](/en/settings#settings-precedence), the arrays are **merged**, meaning paths from every scope are combined, not replaced. For example, if managed settings allow writes to `/opt/company-tools` and a user adds `~/.kube` in their personal settings, both paths are included in the final sandbox configuration. This means users and projects can extend the list without duplicating or overriding paths set by higher-priority scopes.

138 

139Path prefixes control how paths are resolved:

140 

141| Prefix | Meaning | Example |

142| :---------------- | :------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |

143| `/` | Absolute path from filesystem root | `/tmp/build` stays `/tmp/build` |

144| `~/` | Relative to home directory | `~/.kube` becomes `$HOME/.kube` |

145| `./` or no prefix | Relative to the project root for project settings, or to `~/.claude` for user settings | `./output` in `.claude/settings.json` resolves to `<project-root>/output` |

146 

147The older `//path` prefix for absolute paths still works. If you previously used single-slash `/path` expecting project-relative resolution, switch to `./path`. This syntax differs from [Read and Edit permission rules](/en/permissions#read-and-edit), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is an absolute path.

148 

149You can also deny write or read access using `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead`. These are merged with any paths from `Edit(...)` and `Read(...)` permission rules. To re-allow reading specific paths within a denied region, use `sandbox.filesystem.allowRead`, which takes precedence over `denyRead`. When `allowManagedReadPathsOnly` is enabled in managed settings, only managed `allowRead` entries are respected; user, project, and local `allowRead` entries are ignored. `denyRead` still merges from all sources.

150 

151For example, to block reading from the entire home directory while still allowing reads from the current project, add this to your project's `.claude/settings.json`:

152 

153```json theme={null}

154{

155 "sandbox": {

156 "enabled": true,

157 "filesystem": {

158 "denyRead": ["~/"],

159 "allowRead": ["."]

160 }

161 }

162}

163```

164 

165The `.` in `allowRead` resolves to the project root because this configuration lives in project settings. If you placed the same configuration in `~/.claude/settings.json`, `.` would resolve to `~/.claude` instead, and project files would remain blocked by the `denyRead` rule.

74 166 

75<Tip>167<Tip>

76 Not all commands are compatible with sandboxing out of the box. Some notes that may help you make the most out of the sandbox:168 Not all commands are compatible with sandboxing out of the box. Some notes that may help you make the most out of the sandbox:

77 169 

78 * Many CLI tools require accessing certain hosts. As you use these tools, they will request permission to access certain hosts. Granting permission will allow them to access these hosts now and in the future, enabling them to safely execute inside the sandbox.170 * Many CLI tools require accessing certain hosts. As you use these tools, they will request permission to access certain hosts. Granting permission will allow them to access these hosts now and in the future, enabling them to safely execute inside the sandbox.

79 * `watchman` is incompatible with running in the sandbox. If you're running `jest`, consider using `jest --no-watchman`171 * `watchman` is incompatible with running in the sandbox. If you're running `jest`, consider using `jest --no-watchman`

80 * `docker` is incompatible with running in the sandbox. Consider specifying `docker` in `excludedCommands` to force it to run outside of the sandbox.172 * `docker` is incompatible with running in the sandbox. Consider specifying `docker *` in `excludedCommands` to force it to run outside of the sandbox.

81</Tip>173</Tip>

82 174 

83<Note>175<Note>

84 Claude Code includes an intentional escape hatch mechanism that allows commands to run outside the sandbox when necessary. When a command fails due to sandbox restrictions (such as network connectivity issues or incompatible tools), Claude is prompted to analyze the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. Commands that use this parameter go through the normal Claude Code permissions flow requiring user permission to execute. This allows Claude Code to handle edge cases where certain tools or network operations cannot function within sandbox constraints.176 Claude Code includes an intentional escape hatch mechanism that allows commands to run outside the sandbox when necessary. When a command fails due to sandbox restrictions (such as network connectivity issues or incompatible tools), Claude is prompted to analyze the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. Commands that use this parameter go through the normal Claude Code permissions flow requiring user permission to execute. This allows Claude Code to handle edge cases where certain tools or network operations cannot function within sandbox constraints.

85 177 

86 You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](/en/docs/claude-code/settings#sandbox-settings). When disabled, the `dangerouslyDisableSandbox` parameter is completely ignored and all commands must run sandboxed or be explicitly listed in `excludedCommands`.178 You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](/en/settings#sandbox-settings). When disabled, the `dangerouslyDisableSandbox` parameter is completely ignored and all commands must run sandboxed or be explicitly listed in `excludedCommands`.

87</Note>179</Note>

88 180 

89## Security benefits181## Security benefits


96 188 

97* Cannot modify critical config files such as `~/.bashrc`189* Cannot modify critical config files such as `~/.bashrc`

98* Cannot modify system-level files in `/bin/`190* Cannot modify system-level files in `/bin/`

99* Cannot read files that are denied in your [Claude permission settings](/en/docs/claude-code/iam#configuring-permissions)191* Cannot read files that are denied in your [Claude permission settings](/en/permissions#manage-permissions)

100 192 

101**Network protection:**193**Network protection:**

102 194 


141 233 

142* 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.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.

143* Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files.235* Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files.

144* Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used incases where additional isolation is otherwise enforced.236* Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used in cases where additional isolation is otherwise enforced.

237 

238## How sandboxing relates to permissions

239 

240Sandboxing and [permissions](/en/permissions) are complementary security layers that work together:

241 

242* **Permissions** control which tools Claude Code can use and are evaluated before any tool runs. They apply to all tools: Bash, Read, Edit, WebFetch, MCP, and others.

243* **Sandboxing** provides OS-level enforcement that restricts what Bash commands can access at the filesystem and network level. It applies only to Bash commands and their child processes.

244 

245Filesystem and network restrictions are configured through both sandbox settings and permission rules:

246 

247* Use `sandbox.filesystem.allowWrite` to grant subprocess write access to paths outside the working directory

248* Use `sandbox.filesystem.denyWrite` and `sandbox.filesystem.denyRead` to block subprocess access to specific paths

249* Use `sandbox.filesystem.allowRead` to re-allow reading specific paths within a `denyRead` region

250* Use `Read` and `Edit` deny rules to block access to specific files or directories

251* Use `WebFetch` allow/deny rules to control domain access

252* Use sandbox `allowedDomains` to control which domains Bash commands can reach

253 

254Paths from both `sandbox.filesystem` settings and permission rules are merged together into the final sandbox configuration.

255 

256This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios, including sandbox-specific examples. Use these as starting points and adjust them to fit your needs.

145 257 

146## Advanced usage258## Advanced usage

147 259 


169 281 

170The sandboxed bash tool works alongside:282The sandboxed bash tool works alongside:

171 283 

172* **IAM policies**: Combine with [permission settings](/en/docs/claude-code/iam) for defense-in-depth284* **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth

173* **Development containers**: Use with [devcontainers](/en/docs/claude-code/devcontainer) for additional isolation285* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation

174* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/docs/claude-code/settings#settings-precedence)286* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)

175 287 

176## Best practices288## Best practices

177 289 


195 307 

196* **Performance overhead**: Minimal, but some filesystem operations may be slightly slower308* **Performance overhead**: Minimal, but some filesystem operations may be slightly slower

197* **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox309* **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox

198* **Platform support**: Currently supports Linux and macOS; Windows support planned310* **Platform support**: Supports macOS, Linux, and WSL2. WSL1 is not supported. Native Windows support is planned.

311 

312## What sandboxing does not cover

313 

314The sandbox isolates Bash subprocesses. Other tools operate under different boundaries:

315 

316* **Built-in file tools**: Read, Edit, and Write use the permission system directly rather than running through the sandbox. See [permissions](/en/permissions).

317* **Computer use**: when Claude opens apps and controls your screen, it runs on your actual desktop rather than in an isolated environment. Per-app permission prompts gate each application. See [computer use in the CLI](/en/computer-use) or [computer use in Desktop](/en/desktop#let-claude-use-your-computer).

199 318 

200## See also319## See also

201 320 

202* [Security](/en/docs/claude-code/security) - Comprehensive security features and best practices321* [Security](/en/security) - Comprehensive security features and best practices

203* [IAM](/en/docs/claude-code/iam) - Permission configuration and access control322* [Permissions](/en/permissions) - Permission configuration and access control

204* [Settings](/en/docs/claude-code/settings) - Complete configuration reference323* [Settings](/en/settings) - Complete configuration reference

205* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line options including `-sb`324* [CLI reference](/en/cli-reference) - Command-line options

scheduled-tasks.md +157 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Run prompts on a schedule

6 

7> Use /loop and the cron scheduling tools to run prompts repeatedly, poll for status, or set one-time reminders within a Claude Code session.

8 

9<Note>

10 Scheduled tasks require Claude Code v2.1.72 or later. Check your version with `claude --version`.

11</Note>

12 

13Scheduled tasks let Claude re-run a prompt automatically on an interval. Use them to poll a deployment, babysit a PR, check back on a long-running build, or remind yourself to do something later in the session. 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 

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 [Cloud](/en/web-scheduled-tasks) or [Desktop](/en/desktop-scheduled-tasks) scheduled tasks, or [GitHub Actions](/en/github-actions).

16 

17## Compare scheduling options

18 

19Claude Code offers three ways to schedule recurring work:

20 

21| | [Cloud](/en/web-scheduled-tasks) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |

22| :------------------------- | :------------------------------- | :------------------------------------- | :----------------------------- |

23| Runs on | Anthropic cloud | Your machine | Your machine |

24| Requires machine on | No | Yes | Yes |

25| Requires open session | No | No | Yes |

26| Persistent across restarts | Yes | Yes | No (session-scoped) |

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 |

29| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |

30| Customizable schedule | Via `/schedule` in the CLI | Yes | Yes |

31| Minimum interval | 1 hour | 1 minute | 1 minute |

32 

33<Tip>

34 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.

35</Tip>

36 

37## Schedule a recurring prompt with /loop

38 

39The `/loop` [bundled skill](/en/skills#bundled-skills) is the quickest way to schedule a recurring prompt. Pass an optional interval and a prompt, and Claude sets up a cron job that fires in the background while the session stays open.

40 

41```text theme={null}

42/loop 5m check if the deployment finished and tell me what happened

43```

44 

45Claude parses the interval, converts it to a cron expression, schedules the job, and confirms the cadence and job ID.

46 

47### Interval syntax

48 

49Intervals are optional. You can lead with them, trail with them, or leave them out entirely.

50 

51| Form | Example | Parsed interval |

52| :---------------------- | :------------------------------------ | :--------------------------- |

53| Leading token | `/loop 30m check the build` | every 30 minutes |

54| Trailing `every` clause | `/loop check the build every 2 hours` | every 2 hours |

55| No interval | `/loop check the build` | defaults to every 10 minutes |

56 

57Supported units are `s` for seconds, `m` for minutes, `h` for hours, and `d` for days. Seconds are rounded up to the nearest minute since cron has one-minute granularity. Intervals that don't divide evenly into their unit, such as `7m` or `90m`, are rounded to the nearest clean interval and Claude tells you what it picked.

58 

59### Loop over another command

60 

61The scheduled prompt can itself be a command or skill invocation. This is useful for re-running a workflow you've already packaged.

62 

63```text theme={null}

64/loop 20m /review-pr 1234

65```

66 

67Each time the job fires, Claude runs `/review-pr 1234` as if you had typed it.

68 

69## Set a one-time reminder

70 

71For 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.

72 

73```text theme={null}

74remind me at 3pm to push the release branch

75```

76 

77```text theme={null}

78in 45 minutes, check whether the integration tests passed

79```

80 

81Claude pins the fire time to a specific minute and hour using a cron expression and confirms when it will fire.

82 

83## Manage scheduled tasks

84 

85Ask Claude in natural language to list or cancel tasks, or reference the underlying tools directly.

86 

87```text theme={null}

88what scheduled tasks do I have?

89```

90 

91```text theme={null}

92cancel the deploy check job

93```

94 

95Under the hood, Claude uses these tools:

96 

97| Tool | Purpose |

98| :----------- | :-------------------------------------------------------------------------------------------------------------- |

99| `CronCreate` | Schedule a new task. Accepts a 5-field cron expression, the prompt to run, and whether it recurs or fires once. |

100| `CronList` | List all scheduled tasks with their IDs, schedules, and prompts. |

101| `CronDelete` | Cancel a task by ID. |

102 

103Each scheduled task has an 8-character ID you can pass to `CronDelete`. A session can hold up to 50 scheduled tasks at once.

104 

105## How scheduled tasks run

106 

107The scheduler checks every second for due tasks and enqueues them at low priority. A scheduled prompt fires between your turns, not while Claude is mid-response. If Claude is busy when a task comes due, the prompt waits until the current turn ends.

108 

109All times are interpreted in your local timezone. A cron expression like `0 9 * * *` means 9am wherever you're running Claude Code, not UTC.

110 

111### Jitter

112 

113To avoid every session hitting the API at the same wall-clock moment, the scheduler adds a small deterministic offset to fire times:

114 

115* Recurring tasks fire up to 10% of their period late, capped at 15 minutes. An hourly job might fire anywhere from `:00` to `:06`.

116* One-shot tasks scheduled for the top or bottom of the hour fire up to 90 seconds early.

117 

118The 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.

119 

120### Seven-day expiry

121 

122Recurring tasks automatically expire 7 days after creation. The task fires one final time, then deletes itself. This bounds how long a forgotten loop can run. If you need a recurring task to last longer, cancel and recreate it before it expires, or use [Cloud scheduled tasks](/en/web-scheduled-tasks) or [Desktop scheduled tasks](/en/desktop-scheduled-tasks) for durable scheduling.

123 

124## Cron expression reference

125 

126`CronCreate` accepts standard 5-field cron expressions: `minute hour day-of-month month day-of-week`. All fields support wildcards (`*`), single values (`5`), steps (`*/15`), ranges (`1-5`), and comma-separated lists (`1,15,30`).

127 

128| Example | Meaning |

129| :------------- | :--------------------------- |

130| `*/5 * * * *` | Every 5 minutes |

131| `0 * * * *` | Every hour on the hour |

132| `7 * * * *` | Every hour at 7 minutes past |

133| `0 9 * * *` | Every day at 9am local |

134| `0 9 * * 1-5` | Weekdays at 9am local |

135| `30 14 15 3 *` | March 15 at 2:30pm local |

136 

137Day-of-week uses `0` or `7` for Sunday through `6` for Saturday. Extended syntax like `L`, `W`, `?`, and name aliases such as `MON` or `JAN` is not supported.

138 

139When both day-of-month and day-of-week are constrained, a date matches if either field matches. This follows standard vixie-cron semantics.

140 

141## Disable scheduled tasks

142 

143Set `CLAUDE_CODE_DISABLE_CRON=1` in your environment to disable the scheduler entirely. The cron tools and `/loop` become unavailable, and any already-scheduled tasks stop firing. See [Environment variables](/en/env-vars) for the full list of disable flags.

144 

145## Limitations

146 

147Session-scoped scheduling has inherent constraints:

148 

149* Tasks only fire while Claude Code is running and idle. Closing the terminal or letting the session exit cancels everything.

150* 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.

151* No persistence across restarts. Restarting Claude Code clears all session-scoped tasks.

152 

153For cron-driven automation that needs to run unattended:

154 

155* [Cloud scheduled tasks](/en/web-scheduled-tasks): run on Anthropic-managed infrastructure

156* [GitHub Actions](/en/github-actions): use a `schedule` trigger in CI

157* [Desktop scheduled tasks](/en/desktop-scheduled-tasks): run locally on your machine

sdk/migration-guide.md +0 −327 deleted

File DeletedView Diff

1# Migrate to Claude Agent SDK

2 

3> Guide for migrating the Claude Code TypeScript and Python SDKs to the Claude Agent SDK

4 

5## Overview

6 

7The Claude Code SDK has been renamed to the **Claude Agent SDK** and its documentation has been reorganized. This change reflects the SDK's broader capabilities for building AI agents beyond just coding tasks.

8 

9## What's Changed

10 

11| Aspect | Old | New |

12| :------------------------- | :----------------------------- | :------------------------------- |

13| **Package Name (TS/JS)** | `@anthropic-ai/claude-code` | `@anthropic-ai/claude-agent-sdk` |

14| **Python Package** | `claude-code-sdk` | `claude-agent-sdk` |

15| **Documentation Location** | Claude Code docs → SDK section | API Guide → Agent SDK section |

16 

17<Note>

18 **Documentation Changes:** The Agent SDK documentation has moved from the Claude Code docs to the API Guide under a dedicated [Agent SDK](/en/api/agent-sdk/overview) section. The Claude Code docs now focus on the CLI tool and automation features.

19</Note>

20 

21## Migration Steps

22 

23### For TypeScript/JavaScript Projects

24 

25**1. Uninstall the old package:**

26 

27```bash theme={null}

28npm uninstall @anthropic-ai/claude-code

29```

30 

31**2. Install the new package:**

32 

33```bash theme={null}

34npm install @anthropic-ai/claude-agent-sdk

35```

36 

37**3. Update your imports:**

38 

39Change all imports from `@anthropic-ai/claude-code` to `@anthropic-ai/claude-agent-sdk`:

40 

41```typescript theme={null}

42// Before

43import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-code";

44 

45// After

46import {

47 query,

48 tool,

49 createSdkMcpServer,

50} from "@anthropic-ai/claude-agent-sdk";

51```

52 

53**4. Update package.json dependencies:**

54 

55If you have the package listed in your `package.json`, update it:

56 

57```json theme={null}

58// Before

59{

60 "dependencies": {

61 "@anthropic-ai/claude-code": "^1.0.0"

62 }

63}

64 

65// After

66{

67 "dependencies": {

68 "@anthropic-ai/claude-agent-sdk": "^0.1.0"

69 }

70}

71```

72 

73That's it! No other code changes are required.

74 

75### For Python Projects

76 

77**1. Uninstall the old package:**

78 

79```bash theme={null}

80pip uninstall claude-code-sdk

81```

82 

83**2. Install the new package:**

84 

85```bash theme={null}

86pip install claude-agent-sdk

87```

88 

89**3. Update your imports:**

90 

91Change all imports from `claude_code_sdk` to `claude_agent_sdk`:

92 

93```python theme={null}

94# Before

95from claude_code_sdk import query, ClaudeCodeOptions

96 

97# After

98from claude_agent_sdk import query, ClaudeAgentOptions

99```

100 

101**4. Update type names:**

102 

103Change `ClaudeCodeOptions` to `ClaudeAgentOptions`:

104 

105```python theme={null}

106# Before

107from claude_agent_sdk import query, ClaudeCodeOptions

108 

109options = ClaudeCodeOptions(

110 model="claude-sonnet-4-5"

111)

112 

113# After

114from claude_agent_sdk import query, ClaudeAgentOptions

115 

116options = ClaudeAgentOptions(

117 model="claude-sonnet-4-5"

118)

119```

120 

121**5. Review [breaking changes](#breaking-changes)**

122 

123Make any code changes needed to complete the migration.

124 

125## Breaking changes

126 

127<Warning>

128 To improve isolation and explicit configuration, Claude Agent SDK v0.1.0 introduces breaking changes for users migrating from Claude Code SDK. Review this section carefully before migrating.

129</Warning>

130 

131### Python: ClaudeCodeOptions renamed to ClaudeAgentOptions

132 

133**What changed:** The Python SDK type `ClaudeCodeOptions` has been renamed to `ClaudeAgentOptions`.

134 

135**Migration:**

136 

137```python theme={null}

138# BEFORE (v0.0.x)

139from claude_agent_sdk import query, ClaudeCodeOptions

140 

141options = ClaudeCodeOptions(

142 model="claude-sonnet-4-5",

143 permission_mode="acceptEdits"

144)

145 

146# AFTER (v0.1.0)

147from claude_agent_sdk import query, ClaudeAgentOptions

148 

149options = ClaudeAgentOptions(

150 model="claude-sonnet-4-5",

151 permission_mode="acceptEdits"

152)

153```

154 

155**Why this changed:** The type name now matches the "Claude Agent SDK" branding and provides consistency across the SDK's naming conventions.

156 

157### System prompt no longer default

158 

159**What changed:** The SDK no longer uses Claude Code's system prompt by default.

160 

161**Migration:**

162 

163<CodeGroup>

164 ```typescript TypeScript theme={null}

165 // BEFORE (v0.0.x) - Used Claude Code's system prompt by default

166 const result = query({ prompt: "Hello" });

167 

168 // AFTER (v0.1.0) - Uses empty system prompt by default

169 // To get the old behavior, explicitly request Claude Code's preset:

170 const result = query({

171 prompt: "Hello",

172 options: {

173 systemPrompt: { type: "preset", preset: "claude_code" }

174 }

175 });

176 

177 // Or use a custom system prompt:

178 const result = query({

179 prompt: "Hello",

180 options: {

181 systemPrompt: "You are a helpful coding assistant"

182 }

183 });

184 ```

185 

186 ```python Python theme={null}

187 # BEFORE (v0.0.x) - Used Claude Code's system prompt by default

188 async for message in query(prompt="Hello"):

189 print(message)

190 

191 # AFTER (v0.1.0) - Uses empty system prompt by default

192 # To get the old behavior, explicitly request Claude Code's preset:

193 from claude_agent_sdk import query, ClaudeAgentOptions

194 

195 async for message in query(

196 prompt="Hello",

197 options=ClaudeAgentOptions(

198 system_prompt={"type": "preset", "preset": "claude_code"} # Use the preset

199 )

200 ):

201 print(message)

202 

203 # Or use a custom system prompt:

204 async for message in query(

205 prompt="Hello",

206 options=ClaudeAgentOptions(

207 system_prompt="You are a helpful coding assistant"

208 )

209 ):

210 print(message)

211 ```

212</CodeGroup>

213 

214**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.

215 

216### Settings Sources No Longer Loaded by Default

217 

218**What changed:** The SDK no longer reads from filesystem settings (CLAUDE.md, settings.json, slash commands, etc.) by default.

219 

220**Migration:**

221 

222<CodeGroup>

223 ```typescript TypeScript theme={null}

224 // BEFORE (v0.0.x) - Loaded all settings automatically

225 const result = query({ prompt: "Hello" });

226 // Would read from:

227 // - ~/.claude/settings.json (user)

228 // - .claude/settings.json (project)

229 // - .claude/settings.local.json (local)

230 // - CLAUDE.md files

231 // - Custom slash commands

232 

233 // AFTER (v0.1.0) - No settings loaded by default

234 // To get the old behavior:

235 const result = query({

236 prompt: "Hello",

237 options: {

238 settingSources: ["user", "project", "local"]

239 }

240 });

241 

242 // Or load only specific sources:

243 const result = query({

244 prompt: "Hello",

245 options: {

246 settingSources: ["project"] // Only project settings

247 }

248 });

249 ```

250 

251 ```python Python theme={null}

252 # BEFORE (v0.0.x) - Loaded all settings automatically

253 async for message in query(prompt="Hello"):

254 print(message)

255 # Would read from:

256 # - ~/.claude/settings.json (user)

257 # - .claude/settings.json (project)

258 # - .claude/settings.local.json (local)

259 # - CLAUDE.md files

260 # - Custom slash commands

261 

262 # AFTER (v0.1.0) - No settings loaded by default

263 # To get the old behavior:

264 from claude_agent_sdk import query, ClaudeAgentOptions

265 

266 async for message in query(

267 prompt="Hello",

268 options=ClaudeAgentOptions(

269 setting_sources=["user", "project", "local"]

270 )

271 ):

272 print(message)

273 

274 # Or load only specific sources:

275 async for message in query(

276 prompt="Hello",

277 options=ClaudeAgentOptions(

278 setting_sources=["project"] # Only project settings

279 )

280 ):

281 print(message)

282 ```

283</CodeGroup>

284 

285**Why this changed:** Ensures SDK applications have predictable behavior independent of local filesystem configurations. This is especially important for:

286 

287* **CI/CD environments** - Consistent behavior without local customizations

288* **Deployed applications** - No dependency on filesystem settings

289* **Testing** - Isolated test environments

290* **Multi-tenant systems** - Prevent settings leakage between users

291 

292<Note>

293 **Backward compatibility:** If your application relied on filesystem settings (custom slash commands, CLAUDE.md instructions, etc.), add `settingSources: ['user', 'project', 'local']` to your options.

294</Note>

295 

296## Why the Rename?

297 

298The Claude Code SDK was originally designed for coding tasks, but it has evolved into a powerful framework for building all types of AI agents. The new name "Claude Agent SDK" better reflects its capabilities:

299 

300* Building business agents (legal assistants, finance advisors, customer support)

301* Creating specialized coding agents (SRE bots, security reviewers, code review agents)

302* Developing custom agents for any domain with tool use, MCP integration, and more

303 

304## Getting Help

305 

306If you encounter any issues during migration:

307 

308**For TypeScript/JavaScript:**

309 

3101. Check that all imports are updated to use `@anthropic-ai/claude-agent-sdk`

3112. Verify your package.json has the new package name

3123. Run `npm install` to ensure dependencies are updated

313 

314**For Python:**

315 

3161. Check that all imports are updated to use `claude_agent_sdk`

3172. Verify your requirements.txt or pyproject.toml has the new package name

3183. Run `pip install claude-agent-sdk` to ensure the package is installed

319 

320See the [Troubleshooting](/en/docs/claude-code/troubleshooting) guide for common issues.

321 

322## Next Steps

323 

324* Explore the [Agent SDK Overview](/en/api/agent-sdk/overview) to learn about available features

325* Check out the [TypeScript SDK Reference](/en/api/agent-sdk/typescript) for detailed API documentation

326* Review the [Python SDK Reference](/en/api/agent-sdk/python) for Python-specific documentation

327* Learn about [Custom Tools](/en/api/agent-sdk/custom-tools) and [MCP Integration](/en/api/agent-sdk/mcp)

security.md +22 −15

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Security5# Security

2 6 

3> Learn about Claude Code's security safeguards and best practices for safe usage.7> Learn about Claude Code's security safeguards and best practices for safe usage.


14 18 

15We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.19We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.

16 20 

17For detailed permission configuration, see [Identity and Access Management](/en/docs/claude-code/iam).21For detailed permission configuration, see [Permissions](/en/permissions).

18 22 

19### Built-in protections23### Built-in protections

20 24 

21To mitigate risks in agentic systems:25To mitigate risks in agentic systems:

22 26 

23* **Sandboxed bash tool**: [Sandbox](/en/docs/claude-code/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

24* **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

25* **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

26* **Accept Edits mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects30* **Accept Edits mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects


38* **Permission system**: Sensitive operations require explicit approval42* **Permission system**: Sensitive operations require explicit approval

39* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request43* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request

40* **Input sanitization**: Prevents command injection by processing user inputs44* **Input sanitization**: Prevents command injection by processing user inputs

41* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/docs/claude-code/iam#tool-specific-permission-rules)45* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/permissions#tool-specific-permission-rules)

42 46 

43### Privacy safeguards47### Privacy safeguards

44 48 


59* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted63* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted

60* **Fail-closed matching**: Unmatched commands default to requiring manual approval64* **Fail-closed matching**: Unmatched commands default to requiring manual approval

61* **Natural language descriptions**: Complex bash commands include explanations for user understanding65* **Natural language descriptions**: Complex bash commands include explanations for user understanding

62* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/docs/claude-code/iam#credential-management)66* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/authentication#credential-management)

63 67 

64<Warning>68<Warning>

65 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.69 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.


712. Avoid piping untrusted content directly to Claude752. Avoid piping untrusted content directly to Claude

723. Verify proposed changes to critical files763. Verify proposed changes to critical files

734. Use virtual machines (VMs) to run scripts and make tool calls, especially when interacting with external web services774. Use virtual machines (VMs) to run scripts and make tool calls, especially when interacting with external web services

745. Report suspicious behavior with `/bug`785. Report suspicious behavior with `/feedback`

75 79 

76<Warning>80<Warning>

77 While these protections significantly reduce risk, no system is completely81 While these protections significantly reduce risk, no system is completely


87 91 

88## IDE security92## IDE security

89 93 

90See [here](/en/docs/claude-code/ide-integrations#security) for more information on the security of running Claude Code in an IDE.94See [VS Code security and privacy](/en/vs-code#security-and-privacy) for more information on running Claude Code in an IDE.

91 95 

92## Cloud execution security96## Cloud execution security

93 97 

94When using [Claude Code on the web](/en/docs/claude-code/claude-code-on-the-web), additional security controls are in place:98When using [Claude Code on the web](/en/claude-code-on-the-web), additional security controls are in place:

95 99 

96* **Isolated virtual machines**: Each cloud session runs in an isolated, Anthropic-managed VM100* **Isolated virtual machines**: Each cloud session runs in an isolated, Anthropic-managed VM

97* **Network access controls**: Network access is limited by default and can be configured to be disabled or allow only specific domains101* **Network access controls**: Network access is limited by default and can be configured to be disabled or allow only specific domains


100* **Audit logging**: All operations in cloud environments are logged for compliance and audit purposes104* **Audit logging**: All operations in cloud environments are logged for compliance and audit purposes

101* **Automatic cleanup**: Cloud environments are automatically terminated after session completion105* **Automatic cleanup**: Cloud environments are automatically terminated after session completion

102 106 

103For more details on cloud execution, see [Claude Code on the web](/en/docs/claude-code/claude-code-on-the-web).107For more details on cloud execution, see [Claude Code on the web](/en/claude-code-on-the-web).

108 

109[Remote Control](/en/remote-control) sessions work differently: the web interface connects to a Claude Code process running on your local machine. All code execution and file access stays local, and the same data that flows during any local Claude Code session travels through the Anthropic API over TLS. No cloud VMs or sandboxing are involved. The connection uses multiple short-lived, narrowly scoped credentials, each limited to a specific purpose and expiring independently, to limit the blast radius of any single compromised credential.

104 110 

105## Security best practices111## Security best practices

106 112 


108 114 

109* Review all suggested changes before approval115* Review all suggested changes before approval

110* Use project-specific permission settings for sensitive repositories116* Use project-specific permission settings for sensitive repositories

111* Consider using [devcontainers](/en/docs/claude-code/devcontainer) for additional isolation117* Consider using [devcontainers](/en/devcontainer) for additional isolation

112* Regularly audit your permission settings with `/permissions`118* Regularly audit your permission settings with `/permissions`

113 119 

114### Team security120### Team security

115 121 

116* Use [enterprise managed policies](/en/docs/claude-code/iam#enterprise-managed-policy-settings) to enforce organizational standards122* Use [managed settings](/en/settings#settings-files) to enforce organizational standards

117* Share approved permission configurations through version control123* Share approved permission configurations through version control

118* Train team members on security best practices124* Train team members on security best practices

119* Monitor Claude Code usage through [OpenTelemetry metrics](/en/docs/claude-code/monitoring-usage)125* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)

126* Audit or block settings changes during sessions with [`ConfigChange` hooks](/en/hooks#configchange)

120 127 

121### Reporting security issues128### Reporting security issues

122 129 


129 136 

130## Related resources137## Related resources

131 138 

132* [Sandboxing](/en/docs/claude-code/sandboxing) - Filesystem and network isolation for bash commands139* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands

133* [Identity and Access Management](/en/docs/claude-code/iam) - Configure permissions and access controls140* [Permissions](/en/permissions) - Configure permissions and access controls

134* [Monitoring usage](/en/docs/claude-code/monitoring-usage) - Track and audit Claude Code activity141* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity

135* [Development containers](/en/docs/claude-code/devcontainer) - Secure, isolated environments142* [Development containers](/en/devcontainer) - Secure, isolated environments

136* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance143* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance

server-managed-settings.md +208 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Configure server-managed settings (public beta)

6 

7> Centrally configure Claude Code for your organization through server-delivered settings, without requiring device management infrastructure.

8 

9Server-managed settings allow administrators to centrally configure Claude Code through a web-based interface on Claude.ai. Claude Code clients automatically receive these settings when users authenticate with their organization credentials.

10 

11This approach is designed for organizations that do not have device management infrastructure in place, or need to manage settings for users on unmanaged devices.

12 

13<Note>

14 Server-managed settings are in public beta and available for [Claude for Teams](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=server_settings_teams#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales?utm_source=claude_code\&utm_medium=docs\&utm_content=server_settings_enterprise) customers. Features may evolve before general availability.

15</Note>

16 

17## Requirements

18 

19To use server-managed settings, you need:

20 

21* Claude for Teams or Claude for Enterprise plan

22* Claude Code version 2.1.38 or later for Claude for Teams, or version 2.1.30 or later for Claude for Enterprise

23* Network access to `api.anthropic.com`

24 

25## Choose between server-managed and endpoint-managed settings

26 

27Claude Code supports two approaches for centralized configuration. Server-managed settings deliver configuration from Anthropic's servers. [Endpoint-managed settings](/en/settings#settings-files) are deployed directly to devices through native OS policies (macOS managed preferences, Windows registry) or managed settings files.

28 

29| Approach | Best for | Security model |

30| :----------------------------------------------------------- | :------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- |

31| **Server-managed settings** | Organizations without MDM, or users on unmanaged devices | Settings delivered from Anthropic's servers at authentication time |

32| **[Endpoint-managed settings](/en/settings#settings-files)** | Organizations with MDM or endpoint management | Settings deployed to devices via MDM configuration profiles, registry policies, or managed settings files |

33 

34If your devices are enrolled in an MDM or endpoint management solution, endpoint-managed settings provide stronger security guarantees because the settings file can be protected from user modification at the OS level.

35 

36## Configure server-managed settings

37 

38<Steps>

39 <Step title="Open the admin console">

40 In [Claude.ai](https://claude.ai), navigate to **Admin Settings > Claude Code > Managed settings**.

41 </Step>

42 

43 <Step title="Define your settings">

44 Add your configuration as JSON. All [settings available in `settings.json`](/en/settings#available-settings) are supported, including [hooks](/en/hooks), [environment variables](/en/env-vars), and [managed-only settings](/en/permissions#managed-only-settings) like `allowManagedPermissionRulesOnly`.

45 

46 This example enforces a permission deny list, prevents users from bypassing permissions, and restricts permission rules to those defined in managed settings:

47 

48 ```json theme={null}

49 {

50 "permissions": {

51 "deny": [

52 "Bash(curl *)",

53 "Read(./.env)",

54 "Read(./.env.*)",

55 "Read(./secrets/**)"

56 ],

57 "disableBypassPermissionsMode": "disable"

58 },

59 "allowManagedPermissionRulesOnly": true

60 }

61 ```

62 

63 Hooks use the same format as in `settings.json`.

64 

65 This example runs an audit script after every file edit across the organization:

66 

67 ```json theme={null}

68 {

69 "hooks": {

70 "PostToolUse": [

71 {

72 "matcher": "Edit|Write",

73 "hooks": [

74 { "type": "command", "command": "/usr/local/bin/audit-edit.sh" }

75 ]

76 }

77 ]

78 }

79 }

80 ```

81 

82 To configure the [auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode) classifier so it knows which repos, buckets, and domains your organization trusts:

83 

84 ```json theme={null}

85 {

86 "autoMode": {

87 "environment": [

88 "Source control: github.example.com/acme-corp and all repos under it",

89 "Trusted cloud buckets: s3://acme-build-artifacts, gs://acme-ml-datasets",

90 "Trusted internal domains: *.corp.example.com"

91 ]

92 }

93 }

94 ```

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.

97 </Step>

98 

99 <Step title="Save and deploy">

100 Save your changes. Claude Code clients receive the updated settings on their next startup or hourly polling cycle.

101 </Step>

102</Steps>

103 

104### Verify settings delivery

105 

106To confirm that settings are being applied, ask a user to restart Claude Code. If the configuration includes settings that trigger the [security approval dialog](#security-approval-dialogs), the user sees a prompt describing the managed settings on startup. You can also verify that managed permission rules are active by having a user run `/permissions` to view their effective permission rules.

107 

108### Access control

109 

110The following roles can manage server-managed settings:

111 

112* **Primary Owner**

113* **Owner**

114 

115Restrict access to trusted personnel, as settings changes apply to all users in the organization.

116 

117### Managed-only settings

118 

119Most [settings keys](/en/settings#available-settings) work in any scope. A handful of keys are only read from managed settings and have no effect when placed in user or project settings files. See [managed-only settings](/en/permissions#managed-only-settings) for the full list. Any setting not on that list can still be placed in managed settings and takes the highest precedence.

120 

121### Current limitations

122 

123Server-managed settings have the following limitations during the beta period:

124 

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.

127 

128## Settings delivery

129 

130### Settings precedence

131 

132Server-managed settings and [endpoint-managed settings](/en/settings#settings-files) both occupy the highest tier in the Claude Code [settings hierarchy](/en/settings#settings-precedence). No other settings level can override them, including command line arguments.

133 

134Within the managed tier, the first source that delivers a non-empty configuration wins. Server-managed settings are checked first, then endpoint-managed settings. Sources do not merge: if server-managed settings deliver any keys at all, endpoint-managed settings are ignored entirely. If server-managed settings deliver nothing, endpoint-managed settings apply.

135 

136If you clear your server-managed configuration in the admin console with the intent of falling back to an endpoint-managed plist or registry policy, be aware that [cached settings](#fetch-and-caching-behavior) persist on client machines until the next successful fetch. Run `/status` to see which managed source is active.

137 

138### Fetch and caching behavior

139 

140Claude Code fetches settings from Anthropic's servers at startup and polls for updates hourly during active sessions.

141 

142**First launch without cached settings:**

143 

144* Claude Code fetches settings asynchronously

145* If the fetch fails, Claude Code continues without managed settings

146* There is a brief window before settings load where restrictions are not yet enforced

147 

148**Subsequent launches with cached settings:**

149 

150* Cached settings apply immediately at startup

151* Claude Code fetches fresh settings in the background

152* Cached settings persist through network failures

153 

154Claude Code applies settings updates automatically without a restart, except for advanced settings like OpenTelemetry configuration, which require a full restart to take effect.

155 

156### Security approval dialogs

157 

158Certain settings that could pose security risks require explicit user approval before being applied:

159 

160* **Shell command settings**: settings that execute shell commands

161* **Custom environment variables**: variables not in the known safe allowlist

162* **Hook configurations**: any hook definition

163 

164When these settings are present, users see a security dialog explaining what is being configured. Users must approve to proceed. If a user rejects the settings, Claude Code exits.

165 

166<Note>

167 In non-interactive mode with the `-p` flag, Claude Code skips security dialogs and applies settings without user approval.

168</Note>

169 

170## Platform availability

171 

172Server-managed settings require a direct connection to `api.anthropic.com` and are not available when using third-party model providers:

173 

174* Amazon Bedrock

175* Google Vertex AI

176* Microsoft Foundry

177* Custom API endpoints via `ANTHROPIC_BASE_URL` or [LLM gateways](/en/llm-gateway)

178 

179## Audit logging

180 

181Audit log events for settings changes are available through the compliance API or audit log export. Contact your Anthropic account team for access.

182 

183Audit events include the type of action performed, the account and device that performed the action, and references to the previous and new values.

184 

185## Security considerations

186 

187Server-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.

188 

189| Scenario | Behavior |

190| :----------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |

191| User edits the cached settings file | Tampered file applies at startup, but correct settings restore on the next server fetch |

192| User deletes the cached settings file | First-launch behavior occurs: settings fetch asynchronously with a brief unenforced window |

193| API is unavailable | Cached settings apply if available, otherwise managed settings are not enforced until the next successful fetch |

194| User authenticates with a different organization | Settings are not delivered for accounts outside the managed organization |

195| User sets a non-default `ANTHROPIC_BASE_URL` | Server-managed settings are bypassed when using third-party API providers |

196 

197To detect runtime configuration changes, use [`ConfigChange` hooks](/en/hooks#configchange) to log modifications or block unauthorized changes before they take effect.

198 

199For stronger enforcement guarantees, use [endpoint-managed settings](/en/settings#settings-files) on devices enrolled in an MDM solution.

200 

201## See also

202 

203Related pages for managing Claude Code configuration:

204 

205* [Settings](/en/settings): complete configuration reference including all available settings

206* [Endpoint-managed settings](/en/settings#settings-files): managed settings deployed to devices by IT

207* [Authentication](/en/authentication): set up user access to Claude Code

208* [Security](/en/security): security safeguards and best practices

settings.md +663 −174

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Claude Code settings5# Claude Code settings

2 6 

3> Configure Claude Code with global and project-level settings, and environment variables.7> Configure Claude Code with global and project-level settings, and environment variables.

4 8 

5Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL, which opens a tabbed Settings interface where you can view status information and modify configuration options.9Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL, which opens a tabbed Settings interface where you can view status information and modify configuration options.

6 10 

11## Configuration scopes

12 

13Claude Code uses a **scope system** to determine where configurations apply and who they're shared with. Understanding scopes helps you decide how to configure Claude Code for personal use, team collaboration, or enterprise deployment.

14 

15### Available scopes

16 

17| Scope | Location | Who it affects | Shared with team? |

18| :---------- | :--------------------------------------------------------------------------------- | :----------------------------------- | :--------------------- |

19| **Managed** | Server-managed settings, plist / registry, or system-level `managed-settings.json` | All users on the machine | Yes (deployed by IT) |

20| **User** | `~/.claude/` directory | You, across all projects | No |

21| **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |

22| **Local** | `.claude/settings.local.json` | You, in this repository only | No (gitignored) |

23 

24### When to use each scope

25 

26**Managed scope** is for:

27 

28* Security policies that must be enforced organization-wide

29* Compliance requirements that can't be overridden

30* Standardized configurations deployed by IT/DevOps

31 

32**User scope** is best for:

33 

34* Personal preferences you want everywhere (themes, editor settings)

35* Tools and plugins you use across all projects

36* API keys and authentication (stored securely)

37 

38**Project scope** is best for:

39 

40* Team-shared settings (permissions, hooks, MCP servers)

41* Plugins the whole team should have

42* Standardizing tooling across collaborators

43 

44**Local scope** is best for:

45 

46* Personal overrides for a specific project

47* Testing configurations before sharing with the team

48* Machine-specific settings that won't work for others

49 

50### How scopes interact

51 

52When the same setting is configured in multiple scopes, more specific scopes take precedence:

53 

541. **Managed** (highest) - can't be overridden by anything

552. **Command line arguments** - temporary session overrides

563. **Local** - overrides project and user settings

574. **Project** - overrides user settings

585. **User** (lowest) - applies when nothing else specifies the setting

59 

60For example, if a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked.

61 

62### What uses scopes

63 

64Scopes apply to many Claude Code features:

65 

66| Feature | User location | Project location | Local location |

67| :-------------- | :------------------------ | :--------------------------------- | :----------------------------- |

68| **Settings** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |

69| **Subagents** | `~/.claude/agents/` | `.claude/agents/` | None |

70| **MCP servers** | `~/.claude.json` | `.mcp.json` | `~/.claude.json` (per-project) |

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` |

73 

74***

75 

7## Settings files76## Settings files

8 77 

9The `settings.json` file is our official mechanism for configuring Claude78The `settings.json` file is the official mechanism for configuring Claude

10Code through hierarchical settings:79Code through hierarchical settings:

11 80 

12* **User settings** are defined in `~/.claude/settings.json` and apply to all81* **User settings** are defined in `~/.claude/settings.json` and apply to all


14* **Project settings** are saved in your project directory:83* **Project settings** are saved in your project directory:

15 * `.claude/settings.json` for settings that are checked into source control and shared with your team84 * `.claude/settings.json` for settings that are checked into source control and shared with your team

16 * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.85 * `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.

17* For enterprise deployments of Claude Code, we also support **enterprise86* **Managed settings**: For organizations that need centralized control, Claude Code supports multiple delivery mechanisms for managed settings. All use the same JSON format and cannot be overridden by user or project settings:

18 managed policy settings**. These take precedence over user and project87 

19 settings. System administrators can deploy policies to:88 * **Server-managed settings**: delivered from Anthropic's servers via the Claude.ai admin console. See [server-managed settings](/en/server-managed-settings).

20 * macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`89 * **MDM/OS-level policies**: delivered through native device management on macOS and Windows:

21 * Linux and WSL: `/etc/claude-code/managed-settings.json`90 * macOS: `com.anthropic.claudecode` managed preferences domain (deployed via configuration profiles in Jamf, Kandji, or other MDM tools)

22 * Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`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)

23* Enterprise deployments can also configure **managed MCP servers** that override92 * Windows (user-level): `HKCU\SOFTWARE\Policies\ClaudeCode` (lowest policy priority, only used when no admin-level source exists)

24 user-configured servers. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration):93 * **File-based**: `managed-settings.json` and `managed-mcp.json` deployed to system directories:

25 * macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`94 

26 * Linux and WSL: `/etc/claude-code/managed-mcp.json`95 * macOS: `/Library/Application Support/ClaudeCode/`

27 * Windows: `C:\ProgramData\ClaudeCode\managed-mcp.json`96 * Linux and WSL: `/etc/claude-code/`

97 * Windows: `C:\Program Files\ClaudeCode\`

98 

99 <Warning>

100 The legacy Windows path `C:\ProgramData\ClaudeCode\managed-settings.json` is no longer supported as of v2.1.75. Administrators who deployed settings to that location must migrate files to `C:\Program Files\ClaudeCode\managed-settings.json`.

101 </Warning>

102 

103 File-based managed settings also support a drop-in directory at `managed-settings.d/` in the same system directory alongside `managed-settings.json`. This lets separate teams deploy independent policy fragments without coordinating edits to a single file.

104 

105 Following the systemd convention, `managed-settings.json` is merged first as the base, then all `*.json` files in the drop-in directory are sorted alphabetically and merged on top. Later files override earlier ones for scalar values; arrays are concatenated and de-duplicated; objects are deep-merged. Hidden files starting with `.` are ignored.

106 

107 Use numeric prefixes to control merge order, for example `10-telemetry.json` and `20-security.json`.

108 

109 See [managed settings](/en/permissions#managed-only-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details.

110 

111 <Note>

112 Managed deployments can also restrict **plugin marketplace additions** using

113 `strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).

114 </Note>

115* **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`.

116 

117<Note>

118 Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.

119</Note>

28 120 

29```JSON Example settings.json theme={null}121```JSON Example settings.json theme={null}

30{122{

123 "$schema": "https://json.schemastore.org/claude-code-settings.json",

31 "permissions": {124 "permissions": {

32 "allow": [125 "allow": [

33 "Bash(npm run lint)",126 "Bash(npm run lint)",

34 "Bash(npm run test:*)",127 "Bash(npm run test *)",

35 "Read(~/.zshrc)"128 "Read(~/.zshrc)"

36 ],129 ],

37 "deny": [130 "deny": [

38 "Bash(curl:*)",131 "Bash(curl *)",

39 "Read(./.env)",132 "Read(./.env)",

40 "Read(./.env.*)",133 "Read(./.env.*)",

41 "Read(./secrets/**)"134 "Read(./secrets/**)"


44 "env": {137 "env": {

45 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",138 "CLAUDE_CODE_ENABLE_TELEMETRY": "1",

46 "OTEL_METRICS_EXPORTER": "otlp"139 "OTEL_METRICS_EXPORTER": "otlp"

47 }140 },

141 "companyAnnouncements": [

142 "Welcome to Acme Corp! Review our code guidelines at docs.acme.com",

143 "Reminder: Code reviews required for all PRs",

144 "New security policy in effect"

145 ]

48}146}

49```147```

50 148 

149The `$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.

150 

51### Available settings151### Available settings

52 152 

53`settings.json` supports a number of options:153`settings.json` supports a number of options:

54 154 

55| Key | Description | Example |155| Key | Description | Example |

56| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |156| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |

157| `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"` |

158| `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" }]` |

159| `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/*"]` |

160| `allowedMcpServers` | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Managed MCP configuration](/en/mcp#managed-mcp-configuration) | `[{ "serverName": "github" }]` |

161| `allowManagedHooksOnly` | (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See [Hook configuration](#hook-configuration) | `true` |

162| `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` |

163| `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` |

164| `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` |

57| `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` |165| `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` |

58| `cleanupPeriodDays` | How long to locally retain chat transcripts based on last activity date (default: 30 days) | `20` |166| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |

59| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |167| `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"` |

60| `includeCoAuthoredBy` | Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |168| `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"]}` |

61| `permissions` | See table below for structure of permissions. | |169| `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"` |

62| `hooks` | Configure custom commands to run before or after tool executions. See [hooks documentation](hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` |170| `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"]` |

63| `disableAllHooks` | Disable all [hooks](hooks) | `true` |171| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |

64| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` |172| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |

65| `statusLine` | Configure a custom status line to display context. See [statusLine documentation](statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |173| `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" }]` |

66| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](output-styles) | `"Explanatory"` |174| `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` |

67| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |175| `cleanupPeriodDays` | Sessions inactive for longer 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 in non-interactive mode (`-p`), use the `--no-session-persistence` flag or the `persistSession: false` SDK option; there is no interactive-mode equivalent. | `20` |

68| `forceLoginOrgUUID` | Specify the UUID of an organization to automatically select it during login, bypassing the organization selection step. Requires `forceLoginMethod` to be set | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` |176| `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"]` |

177| `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"` |

178| `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" }]` |

179| `disableAllHooks` | Disable all [hooks](/en/hooks) and any custom [status line](/en/statusline) | `true` |

180| `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"` |

181| `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"` |

182| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |

183| `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"` |

69| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |184| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |

70| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |185| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |

71| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |186| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |

72| `useEnterpriseMcpConfigOnly` | When set in managed-settings.json, restricts MCP servers to only those defined in managed-mcp.json. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration) | `true` |187| `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` |

73| `allowedMcpServers` | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration) | `[{ "serverName": "github" }]` |188| `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` |

74| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including enterprise servers. Denylist takes precedence over allowlist. See [Enterprise MCP configuration](/en/docs/claude-code/mcp#enterprise-mcp-configuration) | `[{ "serverName": "filesystem" }]` |189| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |

75| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/docs/claude-code/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |190| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |

76| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/docs/claude-code/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |191| `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"]` |

192| `hooks` | Configure custom commands to run at lifecycle events. See [hooks documentation](/en/hooks) for format | See [hooks](/en/hooks) |

193| `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"]` |

194| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |

195| `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` |

196| `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"` |

197| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-6"` |

198| `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:..."}` |

199| `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` |

200| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/en/output-styles) | `"Explanatory"` |

201| `permissions` | See table below for structure of permissions. | |

202| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |

203| `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"` |

204| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |

205| `respectGitignore` | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions | `false` |

206| `showClearContextOnPlanAccept` | Show the "clear context" option on the plan accept screen. Defaults to `false`. Set to `true` to restore the option | `true` |

207| `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` |

208| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |

209| `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"] }` |

210| `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"]}` |

211| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |

212| `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" }]` |

213| `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` |

214| `voiceEnabled` | Enable push-to-talk [voice dictation](/en/voice-dictation). Written automatically when you run `/voice`. Requires a Claude.ai account | `true` |

215 

216### Global config settings

217 

218These settings are stored in `~/.claude.json` rather than `settings.json`. Adding them to `settings.json` will trigger a schema validation error.

219 

220| Key | Description | Example |

221| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------- |

222| `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` |

223| `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` |

224| `editorMode` | Key binding mode for the input prompt: `"normal"` or `"vim"`. Default: `"normal"`. Written automatically when you run `/vim`. Appears in `/config` as **Key binding mode** | `"vim"` |

225| `showTurnDuration` | Show turn duration messages after responses, e.g. "Cooked for 1m 6s". Default: `true`. Appears in `/config` as **Show turn duration** | `false` |

226| `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` |

227| `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"` |

228 

229### Worktree settings

230 

231Configure how `--worktree` creates and manages git worktrees. Use these settings to reduce disk usage and startup time in large monorepos.

232 

233| Key | Description | Example |

234| :---------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |

235| `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"]` |

236| `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"]` |

237 

238To 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.

77 239 

78### Permission settings240### Permission settings

79 241 

80| Keys | Description | Example |242| Keys | Description | Example |

81| :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |243| :---------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |

82| `allow` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to allow tool use. **Note:** Bash rules use prefix matching, not regex | `[ "Bash(git diff:*)" ]` |244| `allow` | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details | `[ "Bash(git diff *)" ]` |

83| `ask` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to ask for confirmation upon tool use. | `[ "Bash(git push:*)" ]` |245| `ask` | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below | `[ "Bash(git push *)" ]` |

84| `deny` | Array of [permission rules](/en/docs/claude-code/iam#configuring-permissions) to deny tool use. Use this to also exclude sensitive files from Claude Code access. **Note:** Bash patterns are prefix matches and can be bypassed (see [Bash permission limitations](/en/docs/claude-code/iam#tool-specific-permission-rules)) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` |246| `deny` | Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. See [Permission rule syntax](#permission-rule-syntax) and [Bash permission limitations](/en/permissions#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl *)", "Read(./.env)", "Read(./secrets/**)" ]` |

85| `additionalDirectories` | Additional [working directories](iam#working-directories) that Claude has access to | `[ "../docs/" ]` |247| `additionalDirectories` | Additional [working directories](/en/permissions#working-directories) for file access. Most `.claude/` configuration is [not discovered](/en/permissions#additional-directories-grant-file-access-not-configuration) from these directories | `[ "../docs/" ]` |

86| `defaultMode` | Default [permission mode](iam#permission-modes) when opening Claude Code | `"acceptEdits"` |248| `defaultMode` | Default [permission mode](/en/permission-modes) when opening Claude Code. Valid values: `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`. The `--permission-mode` CLI flag overrides this setting for a single session | `"acceptEdits"` |

87| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed policy settings](iam#enterprise-managed-policy-settings) | `"disable"` |249| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. Typically placed in [managed settings](/en/permissions#managed-settings) to enforce organizational policy, but works from any scope | `"disable"` |

250| `skipDangerousModePermissionPrompt` | Skip the confirmation prompt shown before entering bypass permissions mode via `--dangerously-skip-permissions` or `defaultMode: "bypassPermissions"`. Ignored when set in project settings (`.claude/settings.json`) to prevent untrusted repositories from auto-bypassing the prompt | `true` |

88 251 

89### Sandbox settings252### Permission rule syntax

253 

254Permission rules follow the format `Tool` or `Tool(specifier)`. Rules are evaluated in order: deny rules first, then ask, then allow. The first matching rule wins.

255 

256Quick examples:

90 257 

91Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/docs/claude-code/sandboxing) for details.258| Rule | Effect |

259| :----------------------------- | :--------------------------------------- |

260| `Bash` | Matches all Bash commands |

261| `Bash(npm run *)` | Matches commands starting with `npm run` |

262| `Read(./.env)` | Matches reading the `.env` file |

263| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

92 264 

93**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.265For the complete rule syntax reference, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Agent rules, and security limitations of Bash patterns, see [Permission rule syntax](/en/permissions#permission-rule-syntax).

266 

267### Sandbox settings

268 

269Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/en/sandboxing) for details.

94 270 

95| Keys | Description | Example |271| Keys | Description | Example |

96| :-------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------ |272| :------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ |

97| `enabled` | Enable bash sandboxing (macOS/Linux only). Default: false | `true` |273| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |

274| `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` |

98| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |275| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |

99| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |276| `excludedCommands` | Commands that should run outside of the sandbox | `["docker *"]` |

100| `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` |277| `allowUnsandboxedCommands` | Allow commands to run outside the sandbox via the `dangerouslyDisableSandbox` parameter. When set to `false`, the `dangerouslyDisableSandbox` escape hatch is completely disabled and all commands must run sandboxed (or be in `excludedCommands`). Useful for enterprise policies that require strict sandboxing. Default: true | `false` |

278| `filesystem.allowWrite` | Additional paths where sandboxed commands can write. Arrays are merged across all settings scopes: user, project, and managed paths are combined, not replaced. Also merged with paths from `Edit(...)` allow permission rules. See [path prefixes](#sandbox-path-prefixes) below. | `["/tmp/build", "~/.kube"]` |

279| `filesystem.denyWrite` | Paths where sandboxed commands cannot write. Arrays are merged across all settings scopes. Also merged with paths from `Edit(...)` deny permission rules. | `["/etc", "/usr/local/bin"]` |

280| `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"]` |

281| `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. | `["."]` |

282| `filesystem.allowManagedReadPathsOnly` | (Managed settings only) Only `filesystem.allowRead` paths from managed settings are respected. `denyRead` still merges from all sources. Default: false | `true` |

101| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |283| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |

102| `network.allowLocalBinding` | Allow binding to localhost ports (MacOS only). Default: false | `true` |284| `network.allowAllUnixSockets` | Allow all Unix socket connections in sandbox. Default: false | `true` |

285| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |

286| `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` |

287| `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` |

103| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |288| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |

104| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |289| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |

105| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux only). **Reduces security.** Default: false | `true` |290| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |

291| `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` |

292 

293#### Sandbox path prefixes

294 

295Paths in `filesystem.allowWrite`, `filesystem.denyWrite`, `filesystem.denyRead`, and `filesystem.allowRead` support these prefixes:

296 

297| Prefix | Meaning | Example |

298| :---------------- | :------------------------------------------------------------------------------------- | :------------------------------------------------------------------------ |

299| `/` | Absolute path from filesystem root | `/tmp/build` stays `/tmp/build` |

300| `~/` | Relative to home directory | `~/.kube` becomes `$HOME/.kube` |

301| `./` or no prefix | Relative to the project root for project settings, or to `~/.claude` for user settings | `./output` in `.claude/settings.json` resolves to `<project-root>/output` |

302 

303The older `//path` prefix for absolute paths still works. If you previously used single-slash `/path` expecting project-relative resolution, switch to `./path`. This syntax differs from [Read and Edit permission rules](/en/permissions#read-and-edit), which use `//path` for absolute and `/path` for project-relative. Sandbox filesystem paths use standard conventions: `/tmp/build` is an absolute path.

106 304 

107**Configuration example:**305**Configuration example:**

108 306 


111 "sandbox": {309 "sandbox": {

112 "enabled": true,310 "enabled": true,

113 "autoAllowBashIfSandboxed": true,311 "autoAllowBashIfSandboxed": true,

114 "excludedCommands": ["docker"],312 "excludedCommands": ["docker *"],

313 "filesystem": {

314 "allowWrite": ["/tmp/build", "~/.kube"],

315 "denyRead": ["~/.aws/credentials"]

316 },

115 "network": {317 "network": {

318 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],

116 "allowUnixSockets": [319 "allowUnixSockets": [

117 "/var/run/docker.sock"320 "/var/run/docker.sock"

118 ],321 ],

119 "allowLocalBinding": true322 "allowLocalBinding": true

120 }323 }

121 },

122 "permissions": {

123 "deny": [

124 "Read(.envrc)",

125 "Read(~/.aws/**)"

126 ]

127 }324 }

128}325}

129```326```

130 327 

131**Filesystem access** is controlled via Read/Edit permissions:328**Filesystem and network restrictions** can be configured in two ways that are merged together:

329 

330* **`sandbox.filesystem` settings** (shown above): Control paths at the OS-level sandbox boundary. These restrictions apply to all subprocess commands (e.g., `kubectl`, `terraform`, `npm`), not just Claude's file tools.

331* **Permission rules**: Use `Edit` allow/deny rules to control Claude's file tool access, `Read` deny rules to block reads, and `WebFetch` allow/deny rules to control network domains. Paths from these rules are also merged into the sandbox configuration.

332 

333### Attribution settings

132 334 

133* Read deny rules block file reads in sandbox335Claude Code adds attribution to git commits and pull requests. These are configured separately:

134* Edit allow rules permit file writes (in addition to the defaults, e.g. the current working directory)

135* Edit deny rules block writes within allowed paths

136 336 

137**Network access** is controlled via WebFetch permissions:337* Commits use [git trailers](https://git-scm.com/docs/git-interpret-trailers) (like `Co-Authored-By`) by default, which can be customized or disabled

338* Pull request descriptions are plain text

138 339 

139* WebFetch allow rules permit network domains340| Keys | Description |

140* WebFetch deny rules block network domains341| :------- | :----------------------------------------------------------------------------------------- |

342| `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution |

343| `pr` | Attribution for pull request descriptions. Empty string hides pull request attribution |

344 

345**Default commit attribution:**

346 

347```text theme={null}

348🤖 Generated with [Claude Code](https://claude.com/claude-code)

349 

350 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

351```

352 

353**Default pull request attribution:**

354 

355```text theme={null}

356🤖 Generated with [Claude Code](https://claude.com/claude-code)

357```

358 

359**Example:**

360 

361```json theme={null}

362{

363 "attribution": {

364 "commit": "Generated with AI\n\nCo-Authored-By: AI <ai@example.com>",

365 "pr": ""

366 }

367}

368```

369 

370<Note>

371 The `attribution` setting takes precedence over the deprecated `includeCoAuthoredBy` setting. To hide all attribution, set `commit` and `pr` to empty strings.

372</Note>

373 

374### File suggestion settings

375 

376Configure a custom command for `@` file path autocomplete. The built-in file suggestion uses fast filesystem traversal, but large monorepos may benefit from project-specific indexing such as a pre-built file index or custom tooling.

377 

378```json theme={null}

379{

380 "fileSuggestion": {

381 "type": "command",

382 "command": "~/.claude/file-suggestion.sh"

383 }

384}

385```

386 

387The command runs with the same environment variables as [hooks](/en/hooks), including `CLAUDE_PROJECT_DIR`. It receives JSON via stdin with a `query` field:

388 

389```json theme={null}

390{"query": "src/comp"}

391```

392 

393Output newline-separated file paths to stdout (currently limited to 15):

394 

395```text theme={null}

396src/components/Button.tsx

397src/components/Modal.tsx

398src/components/Form.tsx

399```

400 

401**Example:**

402 

403```bash theme={null}

404#!/bin/bash

405query=$(cat | jq -r '.query')

406your-repo-file-index --query "$query" | head -20

407```

408 

409### Hook configuration

410 

411These settings control which hooks are allowed to run and what HTTP hooks can access. The `allowManagedHooksOnly` setting can only be configured in [managed settings](#settings-files). The URL and env var allowlists can be set at any settings level and merge across sources.

412 

413**Behavior when `allowManagedHooksOnly` is `true`:**

414 

415* Managed hooks and SDK hooks are loaded

416* User hooks, project hooks, and plugin hooks are blocked

417 

418**Restrict HTTP hook URLs:**

419 

420Limit 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.

421 

422```json theme={null}

423{

424 "allowedHttpHookUrls": ["https://hooks.example.com/*", "http://localhost:*"]

425}

426```

427 

428**Restrict HTTP hook environment variables:**

429 

430Limit which environment variable names HTTP hooks can interpolate into header values. Each hook's effective `allowedEnvVars` is the intersection of its own list and this setting.

431 

432```json theme={null}

433{

434 "httpHookAllowedEnvVars": ["MY_TOKEN", "HOOK_SECRET"]

435}

436```

141 437 

142### Settings precedence438### Settings precedence

143 439 

144Settings are applied in order of precedence (highest to lowest):440Settings apply in order of precedence. From highest to lowest:

145 441 

1461. **Enterprise managed policies** (`managed-settings.json`)4421. **Managed settings** ([server-managed](/en/server-managed-settings), [MDM/OS-level policies](#configuration-scopes), or [managed settings](/en/settings#settings-files))

147 * Deployed by IT/DevOps443 * Policies deployed by IT through server delivery, MDM configuration profiles, registry policies, or managed settings files

148 * Cannot be overridden444 * Cannot be overridden by any other level, including command line arguments

445 * 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.

149 446 

1502. **Command line arguments**4472. **Command line arguments**

151 * Temporary overrides for a specific session448 * Temporary overrides for a specific session


1595. **User settings** (`~/.claude/settings.json`)4565. **User settings** (`~/.claude/settings.json`)

160 * Personal global settings457 * Personal global settings

161 458 

162This hierarchy ensures that enterprise security policies are always enforced while still allowing teams and individuals to customize their experience.459This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience. The same precedence applies whether you run Claude Code from the CLI, the [VS Code extension](/en/vs-code), or a [JetBrains IDE](/en/jetbrains).

460 

461For example, if your user settings allow `Bash(npm run *)` but a project's shared settings deny it, the project setting takes precedence and the command is blocked.

462 

463<Note>

464 **Array settings merge across scopes.** When the same array-valued setting (such as `sandbox.filesystem.allowWrite` or `permissions.allow`) appears in multiple scopes, the arrays are **concatenated and deduplicated**, not replaced. This means lower-priority scopes can add entries without overriding those set by higher-priority scopes, and vice versa. For example, if managed settings set `allowWrite` to `["/opt/company-tools"]` and a user adds `["~/.kube"]`, both paths are included in the final configuration.

465</Note>

466 

467### Verify active settings

468 

469Run `/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.

163 470 

164### Key points about the configuration system471### Key points about the configuration system

165 472 

166* **Memory files (CLAUDE.md)**: Contain instructions and context that Claude loads at startup473* **Memory files (`CLAUDE.md`)**: Contain instructions and context that Claude loads at startup

167* **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior474* **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior

168* **Slash commands**: Custom commands that can be invoked during a session with `/command-name`475* **Skills**: Custom prompts that can be invoked with `/skill-name` or loaded by Claude automatically

169* **MCP servers**: Extend Claude Code with additional tools and integrations476* **MCP servers**: Extend Claude Code with additional tools and integrations

170* **Precedence**: Higher-level configurations (Enterprise) override lower-level ones (User/Project)477* **Precedence**: Higher-level configurations (Managed) override lower-level ones (User/Project)

171* **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones478* **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones

172 479 

173### System prompt availability480### System prompt

174 481 

175<Note>482Claude Code's internal system prompt is not published. To add custom instructions, use `CLAUDE.md` files or the `--append-system-prompt` flag.

176 Unlike for claude.ai, we do not publish Claude Code's internal system prompt on this website. Use CLAUDE.md files or `--append-system-prompt` to add custom instructions to Claude Code's behavior.

177</Note>

178 483 

179### Excluding sensitive files484### Excluding sensitive files

180 485 

181To prevent Claude Code from accessing files containing sensitive information (e.g., API keys, secrets, environment files), use the `permissions.deny` setting in your `.claude/settings.json` file:486To prevent Claude Code from accessing files containing sensitive information like API keys, secrets, and environment files, use the `permissions.deny` setting in your `.claude/settings.json` file:

182 487 

183```json theme={null}488```json theme={null}

184{489{


194}499}

195```500```

196 501 

197This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns will be completely invisible to Claude Code, preventing any accidental exposure of sensitive data.502This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns are excluded from file discovery and search results, and read operations on these files are denied.

198 503 

199## Subagent configuration504## Subagent configuration

200 505 


203* **User subagents**: `~/.claude/agents/` - Available across all your projects508* **User subagents**: `~/.claude/agents/` - Available across all your projects

204* **Project subagents**: `.claude/agents/` - Specific to your project and can be shared with your team509* **Project subagents**: `.claude/agents/` - Specific to your project and can be shared with your team

205 510 

206Subagent files define specialized AI assistants with custom prompts and tool permissions. Learn more about creating and using subagents in the [subagents documentation](/en/docs/claude-code/sub-agents).511Subagent files define specialized AI assistants with custom prompts and tool permissions. Learn more about creating and using subagents in the [subagents documentation](/en/sub-agents).

207 512 

208## Plugin configuration513## Plugin configuration

209 514 

210Claude Code supports a plugin system that lets you extend functionality with custom commands, agents, hooks, and MCP servers. Plugins are distributed through marketplaces and can be configured at both user and repository levels.515Claude Code supports a plugin system that lets you extend functionality with skills, agents, hooks, and MCP servers. Plugins are distributed through marketplaces and can be configured at both user and repository levels.

211 516 

212### Plugin settings517### Plugin settings

213 518 


216```json theme={null}521```json theme={null}

217{522{

218 "enabledPlugins": {523 "enabledPlugins": {

219 "formatter@company-tools": true,524 "formatter@acme-tools": true,

220 "deployer@company-tools": true,525 "deployer@acme-tools": true,

221 "analyzer@security-plugins": false526 "analyzer@security-plugins": false

222 },527 },

223 "extraKnownMarketplaces": {528 "extraKnownMarketplaces": {

224 "company-tools": {529 "acme-tools": {

225 "source": "github",530 "source": "github",

226 "repo": "company/claude-plugins"531 "repo": "acme-corp/claude-plugins"

227 }532 }

228 }533 }

229}534}


238* **User settings** (`~/.claude/settings.json`): Personal plugin preferences543* **User settings** (`~/.claude/settings.json`): Personal plugin preferences

239* **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team544* **Project settings** (`.claude/settings.json`): Project-specific plugins shared with team

240* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)545* **Local settings** (`.claude/settings.local.json`): Per-machine overrides (not committed)

546* **Managed settings** (`managed-settings.json`): Organization-wide policy overrides that block installation at all scopes and hide the plugin from the marketplace

241 547 

242**Example**:548**Example**:

243 549 


267```json theme={null}573```json theme={null}

268{574{

269 "extraKnownMarketplaces": {575 "extraKnownMarketplaces": {

270 "company-tools": {576 "acme-tools": {

271 "source": {577 "source": {

272 "source": "github",578 "source": "github",

273 "repo": "company-org/claude-plugins"579 "repo": "acme-corp/claude-plugins"

274 }580 }

275 },581 },

276 "security-plugins": {582 "security-plugins": {

277 "source": {583 "source": {

278 "source": "git",584 "source": "git",

279 "url": "https://git.company.com/security/plugins.git"585 "url": "https://git.example.com/security/plugins.git"

280 }586 }

281 }587 }

282 }588 }


288* `github`: GitHub repository (uses `repo`)594* `github`: GitHub repository (uses `repo`)

289* `git`: Any git URL (uses `url`)595* `git`: Any git URL (uses `url`)

290* `directory`: Local filesystem path (uses `path`, for development only)596* `directory`: Local filesystem path (uses `path`, for development only)

597* `hostPattern`: regex pattern to match marketplace hosts (uses `hostPattern`)

598* `settings`: inline marketplace declared directly in settings.json without a separate hosted repository (uses `name` and `plugins`)

599 

600Use `source: 'settings'` to declare a small set of plugins inline without setting up a hosted marketplace repository. Plugins listed here must reference external sources such as GitHub or npm. You still need to enable each plugin separately in `enabledPlugins`.

601 

602```json theme={null}

603{

604 "extraKnownMarketplaces": {

605 "team-tools": {

606 "source": {

607 "source": "settings",

608 "name": "team-tools",

609 "plugins": [

610 {

611 "name": "code-formatter",

612 "source": {

613 "source": "github",

614 "repo": "acme-corp/code-formatter"

615 }

616 }

617 ]

618 }

619 }

620 }

621}

622```

623 

624#### `strictKnownMarketplaces`

625 

626**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.

627 

628**Managed settings file locations**:

629 

630* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`

631* **Linux and WSL**: `/etc/claude-code/managed-settings.json`

632* **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json`

633 

634**Key characteristics**:

635 

636* Only available in managed settings (`managed-settings.json`)

637* Cannot be overridden by user or project settings (highest precedence)

638* Enforced BEFORE network/filesystem operations (blocked sources never execute)

639* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching

640 

641**Allowlist behavior**:

642 

643* `undefined` (default): No restrictions - users can add any marketplace

644* Empty array `[]`: Complete lockdown - users cannot add any new marketplaces

645* List of sources: Users can only add marketplaces that match exactly

646 

647**All supported source types**:

648 

649The allowlist supports multiple marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host.

650 

6511. **GitHub repositories**:

652 

653```json theme={null}

654{ "source": "github", "repo": "acme-corp/approved-plugins" }

655{ "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }

656{ "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" }

657```

658 

659Fields: `repo` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)

660 

6612. **Git repositories**:

662 

663```json theme={null}

664{ "source": "git", "url": "https://gitlab.example.com/tools/plugins.git" }

665{ "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" }

666{ "source": "git", "url": "ssh://git@git.example.com/plugins.git", "ref": "v3.1", "path": "approved" }

667```

668 

669Fields: `url` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)

670 

6713. **URL-based marketplaces**:

672 

673```json theme={null}

674{ "source": "url", "url": "https://plugins.example.com/marketplace.json" }

675{ "source": "url", "url": "https://cdn.example.com/marketplace.json", "headers": { "Authorization": "Bearer ${TOKEN}" } }

676```

677 

678Fields: `url` (required), `headers` (optional: HTTP headers for authenticated access)

679 

680<Note>

681 URL-based marketplaces only download the `marketplace.json` file. They do not download plugin files from the server. Plugins in URL-based marketplaces must use external sources (GitHub, npm, or git URLs) rather than relative paths. For plugins with relative paths, use a Git-based marketplace instead. See [Troubleshooting](/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.

682</Note>

683 

6844. **NPM packages**:

685 

686```json theme={null}

687{ "source": "npm", "package": "@acme-corp/claude-plugins" }

688{ "source": "npm", "package": "@acme-corp/approved-marketplace" }

689```

690 

691Fields: `package` (required, supports scoped packages)

692 

6935. **File paths**:

694 

695```json theme={null}

696{ "source": "file", "path": "/usr/local/share/claude/acme-marketplace.json" }

697{ "source": "file", "path": "/opt/acme-corp/plugins/marketplace.json" }

698```

699 

700Fields: `path` (required: absolute path to marketplace.json file)

701 

7026. **Directory paths**:

703 

704```json theme={null}

705{ "source": "directory", "path": "/usr/local/share/claude/acme-plugins" }

706{ "source": "directory", "path": "/opt/acme-corp/approved-marketplaces" }

707```

708 

709Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)

710 

7117. **Host pattern matching**:

712 

713```json theme={null}

714{ "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" }

715{ "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" }

716```

717 

718Fields: `hostPattern` (required: regex pattern to match against the marketplace host)

719 

720Use host pattern matching when you want to allow all marketplaces from a specific host without enumerating each repository individually. This is useful for organizations with internal GitHub Enterprise or GitLab servers where developers create their own marketplaces.

721 

722Host extraction by source type:

723 

724* `github`: always matches against `github.com`

725* `git`: extracts hostname from the URL (supports both HTTPS and SSH formats)

726* `url`: extracts hostname from the URL

727* `npm`, `file`, `directory`: not supported for host pattern matching

728 

729**Configuration examples**:

730 

731Example: allow specific marketplaces only:

732 

733```json theme={null}

734{

735 "strictKnownMarketplaces": [

736 {

737 "source": "github",

738 "repo": "acme-corp/approved-plugins"

739 },

740 {

741 "source": "github",

742 "repo": "acme-corp/security-tools",

743 "ref": "v2.0"

744 },

745 {

746 "source": "url",

747 "url": "https://plugins.example.com/marketplace.json"

748 },

749 {

750 "source": "npm",

751 "package": "@acme-corp/compliance-plugins"

752 }

753 ]

754}

755```

756 

757Example - Disable all marketplace additions:

758 

759```json theme={null}

760{

761 "strictKnownMarketplaces": []

762}

763```

764 

765Example: allow all marketplaces from an internal git server:

766 

767```json theme={null}

768{

769 "strictKnownMarketplaces": [

770 {

771 "source": "hostPattern",

772 "hostPattern": "^github\\.example\\.com$"

773 }

774 ]

775}

776```

777 

778**Exact matching requirements**:

779 

780Marketplace sources must match **exactly** for a user's addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:

781 

782* The `repo` or `url` must match exactly

783* The `ref` field must match exactly (or both be undefined)

784* The `path` field must match exactly (or both be undefined)

785 

786Examples of sources that **do NOT match**:

787 

788```json theme={null}

789// These are DIFFERENT sources:

790{ "source": "github", "repo": "acme-corp/plugins" }

791{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }

792 

793// These are also DIFFERENT:

794{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }

795{ "source": "github", "repo": "acme-corp/plugins" }

796```

797 

798**Comparison with `extraKnownMarketplaces`**:

799 

800| Aspect | `strictKnownMarketplaces` | `extraKnownMarketplaces` |

801| --------------------- | ------------------------------------ | ------------------------------------ |

802| **Purpose** | Organizational policy enforcement | Team convenience |

803| **Settings file** | `managed-settings.json` only | Any settings file |

804| **Behavior** | Blocks non-allowlisted additions | Auto-installs missing marketplaces |

805| **When enforced** | Before network/filesystem operations | After user trust prompt |

806| **Can be overridden** | No (highest precedence) | Yes (by higher precedence settings) |

807| **Source format** | Direct source object | Named marketplace with nested source |

808| **Use case** | Compliance, security restrictions | Onboarding, standardization |

809 

810**Format difference**:

811 

812`strictKnownMarketplaces` uses direct source objects:

813 

814```json theme={null}

815{

816 "strictKnownMarketplaces": [

817 { "source": "github", "repo": "acme-corp/plugins" }

818 ]

819}

820```

821 

822`extraKnownMarketplaces` requires named marketplaces:

823 

824```json theme={null}

825{

826 "extraKnownMarketplaces": {

827 "acme-tools": {

828 "source": { "source": "github", "repo": "acme-corp/plugins" }

829 }

830 }

831}

832```

833 

834**Using both together**:

835 

836`strictKnownMarketplaces` is a policy gate: it controls what users may add but does not register any marketplaces. To both restrict and pre-register a marketplace for all users, set both in `managed-settings.json`:

837 

838```json theme={null}

839{

840 "strictKnownMarketplaces": [

841 { "source": "github", "repo": "acme-corp/plugins" }

842 ],

843 "extraKnownMarketplaces": {

844 "acme-tools": {

845 "source": { "source": "github", "repo": "acme-corp/plugins" }

846 }

847 }

848}

849```

850 

851With only `strictKnownMarketplaces` set, users can still add the allowed marketplace manually via `/plugin marketplace add`, but it is not available automatically.

852 

853**Important notes**:

854 

855* Restrictions are checked BEFORE any network requests or filesystem operations

856* When blocked, users see clear error messages indicating the source is blocked by managed policy

857* The restriction applies only to adding NEW marketplaces; previously installed marketplaces remain accessible

858* Managed settings have the highest precedence and cannot be overridden

859 

860See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation.

291 861 

292### Managing plugins862### Managing plugins

293 863 


299* View plugin details (commands, agents, hooks provided)869* View plugin details (commands, agents, hooks provided)

300* Add/remove marketplaces870* Add/remove marketplaces

301 871 

302Learn more about the plugin system in the [plugins documentation](/en/docs/claude-code/plugins).872Learn more about the plugin system in the [plugins documentation](/en/plugins).

303 873 

304## Environment variables874## Environment variables

305 875 

306Claude Code supports the following environment variables to control its behavior:876Environment variables let you control Claude Code behavior without editing settings files. Any variable can also be configured in [`settings.json`](#available-settings) under the `env` key to apply it to every session or roll it out to your team.

307 

308<Note>

309 All environment variables can also be configured in [`settings.json`](#available-settings). This is useful as a way to automatically set environment variables for each session, or to roll out a set of environment variables for your whole team or organization.

310</Note>

311 877 

312| Variable | Purpose |878See the [environment variables reference](/en/env-vars) for the full list.

313| :----------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

314| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |

315| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) |

316| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers you want to add to the request (in `Name: Value` format) |

317| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/docs/claude-code/model-config#environment-variables) |

318| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/docs/claude-code/model-config#environment-variables) |

319| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/docs/claude-code/model-config#environment-variables) |

320| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/docs/claude-code/model-config#environment-variables)) |

321| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/docs/claude-code/costs) |

322| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |

323| `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/)) |

324| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |

325| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |

326| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |

327| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |

328| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) |

329| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |

330| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |

331| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |

332| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |

333| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |

334| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |

335| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests |

336| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (e.g. when using an LLM gateway) |

337| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (e.g. when using an LLM gateway) |

338| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/docs/claude-code/model-config) |

339| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/docs/claude-code/amazon-bedrock) |

340| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/docs/claude-code/google-vertex-ai) |

341| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. This takes precedence over the `autoUpdates` configuration setting. |

342| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |

343| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |

344| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |

345| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text |

346| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |

347| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |

348| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |

349| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |

350| `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) |

351| `HTTP_PROXY` | Specify HTTP proxy server for network connections |

352| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |

353| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000) |

354| `MAX_THINKING_TOKENS` | Enable [extended thinking](/en/docs/build-with-claude/extended-thinking) and set the token budget for the thinking process. Extended thinking improves performance on complex reasoning and coding tasks but impacts [prompt caching efficiency](/en/docs/build-with-claude/prompt-caching#caching-with-thinking-blocks). Disabled by default. |

355| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |

356| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |

357| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |

358| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Maximum number of characters for slash command metadata shown to [SlashCommand tool](/en/docs/claude-code/slash-commands#slashcommand-tool) (default: 15000) |

359| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` intead of `rg` included with Claude Code |

360| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |

361| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |

362| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |

363| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |

364| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |

365 879 

366## Tools available to Claude880## Tools available to Claude

367 881 

368Claude Code has access to a set of powerful tools that help it understand and modify your codebase:882Claude Code has access to a set of tools for reading, editing, searching, running commands, and orchestrating subagents. Tool names are the exact strings you use in permission rules and hook matchers.

369 

370| Tool | Description | Permission Required |

371| :--------------- | :----------------------------------------------------------------------------------- | :------------------ |

372| **Bash** | Executes shell commands in your environment | Yes |

373| **Edit** | Makes targeted edits to specific files | Yes |

374| **Glob** | Finds files based on pattern matching | No |

375| **Grep** | Searches for patterns in file contents | No |

376| **NotebookEdit** | Modifies Jupyter notebook cells | Yes |

377| **NotebookRead** | Reads and displays Jupyter notebook contents | No |

378| **Read** | Reads the contents of files | No |

379| **SlashCommand** | Runs a [custom slash command](/en/docs/claude-code/slash-commands#slashcommand-tool) | Yes |

380| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |

381| **TodoWrite** | Creates and manages structured task lists | No |

382| **WebFetch** | Fetches content from a specified URL | Yes |

383| **WebSearch** | Performs web searches with domain filtering | Yes |

384| **Write** | Creates or overwrites files | Yes |

385 

386Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/docs/claude-code/settings#available-settings). Also see [Tool-specific permission rules](/en/docs/claude-code/iam#tool-specific-permission-rules).

387 

388### Extending tools with hooks

389 

390You can run custom commands before or after any tool executes using

391[Claude Code hooks](/en/docs/claude-code/hooks-guide).

392 883 

393For example, you could automatically run a Python formatter after Claude884See the [tools reference](/en/tools-reference) for the full list and Bash tool behavior details.

394modifies Python files, or prevent modifications to production configuration

395files by blocking Write operations to certain paths.

396 885 

397## See also886## See also

398 887 

399* [Identity and Access Management](/en/docs/claude-code/iam#configuring-permissions) - Learn about Claude Code's permission system888* [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies

400* [IAM and access control](/en/docs/claude-code/iam#enterprise-managed-policy-settings) - Enterprise policy management889* [Authentication](/en/authentication): set up user access to Claude Code

401* [Troubleshooting](/en/docs/claude-code/troubleshooting#auto-updater-issues) - Solutions for common configuration issues890* [Troubleshooting](/en/troubleshooting): solutions for common configuration issues

setup.md +382 −108

Details

1# Set up Claude Code1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Install, authenticate, and start using Claude Code on your development machine.5# Advanced setup

6 

7> System requirements, platform-specific installation, version management, and uninstallation for Claude Code.

8 

9This page covers system requirements, platform-specific installation details, updates, and uninstallation. For a guided walkthrough of your first session, see the [quickstart](/en/quickstart). If you've never used a terminal before, see the [terminal guide](/en/terminal-guide).

4 10 

5## System requirements11## System requirements

6 12 

7* **Operating Systems**: macOS 10.15+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows)13Claude Code runs on the following platforms and configurations:

8* **Hardware**: 4GB+ RAM14 

9* **Software**: [Node.js 18+](https://nodejs.org/en/download) (only required for NPM installation)15* **Operating system**:

10* **Network**: Internet connection required for authentication and AI processing16 * macOS 13.0+

11* **Shell**: Works best in Bash, Zsh or Fish17 * Windows 10 1809+ or Windows Server 2019+

18 * Ubuntu 20.04+

19 * Debian 10+

20 * Alpine Linux 3.19+

21* **Hardware**: 4 GB+ RAM

22* **Network**: internet connection required. See [network configuration](/en/network-config#network-access-requirements).

23* **Shell**: Bash, Zsh, PowerShell, or CMD. On Windows, [Git for Windows](https://git-scm.com/downloads/win) is required.

12* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)24* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)

13 25 

14### Additional dependencies26### Additional dependencies

15 27 

16* **ripgrep**: Usually included with Claude Code. If search functionality fails, see [search troubleshooting](/en/docs/claude-code/troubleshooting#search-and-discovery-issues).28* **ripgrep**: usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues).

17 29 

18## Standard installation30## Install Claude Code

31 

32<Tip>

33 Prefer a graphical interface? The [Desktop app](/en/desktop-quickstart) lets you use Claude Code without the terminal. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs).

34 

35 New to the terminal? See the [terminal guide](/en/terminal-guide) for step-by-step instructions.

36</Tip>

19 37 

20To install Claude Code, use one of the following methods:38To install Claude Code, use one of the following methods:

21 39 

22<Tabs>40<Tabs>

23 <Tab title="Native Install (Recommended)">41 <Tab title="Native Install (Recommended)">

24 **Homebrew (macOS, Linux):**

25 

26 ```sh theme={null}

27 brew install --cask claude-code

28 ```

29 

30 **macOS, Linux, WSL:**42 **macOS, Linux, WSL:**

31 43 

32 ```bash theme={null}44 ```bash theme={null}


44 ```batch theme={null}56 ```batch theme={null}

45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd57 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

46 ```58 ```

59 

60 If you see `The token '&&' is not a valid statement separator`, you're in PowerShell, not CMD. Use the PowerShell command above instead. Your prompt shows `PS C:\` when you're in PowerShell.

61 

62 **Windows requires [Git for Windows](https://git-scm.com/downloads/win).** Install it first if you don't have it.

63 

64 <Info>

65 Native installations automatically update in the background to keep you on the latest version.

66 </Info>

47 </Tab>67 </Tab>

48 68 

49 <Tab title="NPM">69 <Tab title="Homebrew">

50 If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/):70 ```bash theme={null}

71 brew install --cask claude-code

72 ```

51 73 

52 ```sh theme={null}74 <Info>

53 npm install -g @anthropic-ai/claude-code75 Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

76 </Info>

77 </Tab>

78 

79 <Tab title="WinGet">

80 ```powershell theme={null}

81 winget install Anthropic.ClaudeCode

54 ```82 ```

83 

84 <Info>

85 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

86 </Info>

55 </Tab>87 </Tab>

56</Tabs>88</Tabs>

57 89 

58<Note>90After installation completes, open a terminal in the project you want to work in and start Claude Code:

59 Some users may be automatically migrated to an improved installation method.

60</Note>

61 

62After the installation process completes, navigate to your project and start Claude Code:

63 91 

64```bash theme={null}92```bash theme={null}

65cd your-awesome-project

66claude93claude

67```94```

68 95 

69Claude Code offers the following authentication options:96If you encounter any issues during installation, see the [troubleshooting guide](/en/troubleshooting).

70 97 

711. **Claude Console**: The default option. Connect through the Claude Console and complete the OAuth process. Requires active billing at [console.anthropic.com](https://console.anthropic.com). A "Claude Code" workspace will be automatically created for usage tracking and cost management. Note that you cannot create API keys for the Claude Code workspace - it is dedicated exclusively for Claude Code usage.98### Set up on Windows

722. **Claude App (with Pro or Max plan)**: Subscribe to Claude's [Pro or Max plan](https://claude.com/pricing) for a unified subscription that includes both Claude Code and the web interface. Get more value at the same price point while managing your account in one place. Log in with your Claude.ai account. During launch, choose the option that matches your subscription type.

733. **Enterprise platforms**: Configure Claude Code to use [Amazon Bedrock or Google Vertex AI](/en/docs/claude-code/third-party-integrations) for enterprise deployments with your existing cloud infrastructure.

74 99 

75<Note>100Claude Code on Windows requires [Git for Windows](https://git-scm.com/downloads/win) or WSL. You can launch `claude` from PowerShell, CMD, or Git Bash. Claude Code uses Git Bash internally to run commands. You do not need to run PowerShell as Administrator.

76 Claude Code securely stores your credentials. See [Credential Management](/en/docs/claude-code/iam#credential-management) for details.

77</Note>

78 101 

79## Windows setup102**Option 1: Native Windows with Git Bash**

80 103 

81**Option 1: Claude Code within WSL**104Install [Git for Windows](https://git-scm.com/downloads/win), then run the install command from PowerShell or CMD.

82 105 

83* Both WSL 1 and WSL 2 are supported106If Claude Code can't find your Git Bash installation, set the path in your [settings.json file](/en/settings):

84 107 

85**Option 2: Claude Code on native Windows with Git Bash**108```json theme={null}

109{

110 "env": {

111 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

112 }

113}

114```

86 115 

87* Requires [Git for Windows](https://git-scm.com/downloads/win)116Claude 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.

88* For portable Git installations, specify the path to your `bash.exe`:

89 ```powershell theme={null}

90 $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"

91 ```

92 117 

93## Alternative installation methods118**Option 2: WSL**

94 119 

95Claude Code offers multiple installation methods to suit different environments.120Both WSL 1 and WSL 2 are supported. WSL 2 supports [sandboxing](/en/sandboxing) for enhanced security. WSL 1 does not support sandboxing.

96 121 

97If you encounter any issues during installation, consult the [troubleshooting guide](/en/docs/claude-code/troubleshooting#linux-permission-issues).122### Alpine Linux and musl-based distributions

98 123 

99<Tip>124The native installer on Alpine and other musl/uClibc-based distributions requires `libgcc`, `libstdc++`, and `ripgrep`. Install these using your distribution's package manager, then set `USE_BUILTIN_RIPGREP=0`.

100 Run `claude doctor` after installation to check your installation type and version.

101</Tip>

102 125 

103### Native installation options126This example installs the required packages on Alpine:

104 127 

105The native installation is the recommended method and offers several benefits:128```bash theme={null}

129apk add libgcc libstdc++ ripgrep

130```

106 131 

107* One self-contained executable132Then set `USE_BUILTIN_RIPGREP` to `0` in your [`settings.json`](/en/settings#available-settings) file:

108* No Node.js dependency

109* Improved auto-updater stability

110 133 

111If you have an existing installation of Claude Code, use `claude install` to migrate to the native binary installation.134```json theme={null}

135{

136 "env": {

137 "USE_BUILTIN_RIPGREP": "0"

138 }

139}

140```

112 141 

113For advanced installation options with the native installer:142## Verify your installation

114 143 

115**macOS, Linux, WSL:**144After installing, confirm Claude Code is working:

116 145 

117```bash theme={null}146```bash theme={null}

118# Install stable version (default)147claude --version

119curl -fsSL https://claude.ai/install.sh | bash148```

120 149 

121# Install latest version150For a more detailed check of your installation and configuration, run [`claude doctor`](/en/troubleshooting#get-more-help):

122curl -fsSL https://claude.ai/install.sh | bash -s latest

123 151 

124# Install specific version number152```bash theme={null}

125curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58153claude doctor

126```154```

127 155 

128<Note>156## Authenticate

129 **Alpine Linux and other musl/uClibc-based distributions**: The native build requires you to install `libgcc`, `libstdc++`, and `ripgrep`. Install (Alpine: `apk add libgcc libstdc++ ripgrep`) and set `USE_BUILTIN_RIPGREP=0`.157 

130</Note>158Claude Code requires a Pro, Max, Team, Enterprise, or Console account. The free Claude.ai plan does not include Claude Code access. You can also use Claude Code with a third-party API provider like [Amazon Bedrock](/en/amazon-bedrock), [Google Vertex AI](/en/google-vertex-ai), or [Microsoft Foundry](/en/microsoft-foundry).

159 

160After installing, log in by running `claude` and following the browser prompts. See [Authentication](/en/authentication) for all account types and team setup options.

161 

162## Update Claude Code

163 

164Native 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.

165 

166### Auto-updates

167 

168Claude 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.

131 169 

132<Note>170<Note>

133 Claude Code installed via Homebrew will auto-update outside of the brew directory unless explicitly disabled with the `DISABLE_AUTOUPDATER` environment variable (see [Auto updates](#auto-updates) section).171 Homebrew and WinGet installations do not auto-update. Use `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update manually.

172 

173 **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.

174 

175 Homebrew keeps old versions on disk after upgrades. Run `brew cleanup claude-code` periodically to reclaim disk space.

134</Note>176</Note>

135 177 

136**Windows PowerShell:**178### Configure release channel

137 179 

138```powershell theme={null}180Control which release channel Claude Code follows for auto-updates and `claude update` with the `autoUpdatesChannel` setting:

139# Install stable version (default)181 

140irm https://claude.ai/install.ps1 | iex182* `"latest"`, the default: receive new features as soon as they're released

183* `"stable"`: use a version that is typically about one week old, skipping releases with major regressions

141 184 

142# Install latest version185Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/en/settings):

143& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest

144 186 

145# Install specific version number187```json theme={null}

146& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58188{

189 "autoUpdatesChannel": "stable"

190}

147```191```

148 192 

149**Windows CMD:**193For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/permissions#managed-settings).

150 194 

151```batch theme={null}195### Disable auto-updates

152REM Install stable version (default)

153curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

154 196 

155REM Install latest version197Set `DISABLE_AUTOUPDATER` to `"1"` in the `env` key of your [`settings.json`](/en/settings#available-settings) file:

156curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd latest && del install.cmd

157 198 

158REM Install specific version number199```json theme={null}

159curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd200{

201 "env": {

202 "DISABLE_AUTOUPDATER": "1"

203 }

204}

160```205```

161 206 

162<Tip>207### Update manually

163 Make sure that you remove any outdated aliases or symlinks before installing.208 

164</Tip>209To apply an update immediately without waiting for the next background check, run:

165 210 

166### NPM installation211```bash theme={null}

212claude update

213```

167 214 

168For environments where NPM is preferred or required:215## Advanced installation options

216 

217These options are for version pinning, migrating from npm, and verifying binary integrity.

218 

219### Install a specific version

220 

221The native installer accepts either a specific version number or a release channel (`latest` or `stable`). The channel you choose at install time becomes your default for auto-updates. See [configure release channel](#configure-release-channel) for more information.

222 

223To install the latest version (default):

224 

225<Tabs>

226 <Tab title="macOS, Linux, WSL">

227 ```bash theme={null}

228 curl -fsSL https://claude.ai/install.sh | bash

229 ```

230 </Tab>

231 

232 <Tab title="Windows PowerShell">

233 ```powershell theme={null}

234 irm https://claude.ai/install.ps1 | iex

235 ```

236 </Tab>

237 

238 <Tab title="Windows CMD">

239 ```batch theme={null}

240 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

241 ```

242 </Tab>

243</Tabs>

244 

245To install the stable version:

246 

247<Tabs>

248 <Tab title="macOS, Linux, WSL">

249 ```bash theme={null}

250 curl -fsSL https://claude.ai/install.sh | bash -s stable

251 ```

252 </Tab>

253 

254 <Tab title="Windows PowerShell">

255 ```powershell theme={null}

256 & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) stable

257 ```

258 </Tab>

259 

260 <Tab title="Windows CMD">

261 ```batch theme={null}

262 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd stable && del install.cmd

263 ```

264 </Tab>

265</Tabs>

266 

267To install a specific version number:

268 

269<Tabs>

270 <Tab title="macOS, Linux, WSL">

271 ```bash theme={null}

272 curl -fsSL https://claude.ai/install.sh | bash -s 2.1.89

273 ```

274 </Tab>

169 275 

170```sh theme={null}276 <Tab title="Windows PowerShell">

277 ```powershell theme={null}

278 & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 2.1.89

279 ```

280 </Tab>

281 

282 <Tab title="Windows CMD">

283 ```batch theme={null}

284 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 2.1.89 && del install.cmd

285 ```

286 </Tab>

287</Tabs>

288 

289### Deprecated npm installation

290 

291npm 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.

292 

293#### Migrate from npm to native

294 

295If you previously installed Claude Code with npm, switch to the native installer:

296 

297```bash theme={null}

298# Install the native binary

299curl -fsSL https://claude.ai/install.sh | bash

300 

301# Remove the old npm installation

302npm uninstall -g @anthropic-ai/claude-code

303```

304 

305You can also run `claude install` from an existing npm installation to install the native binary alongside it, then remove the npm version.

306 

307#### Install with npm

308 

309If you need npm installation for compatibility reasons, you must have [Node.js 18+](https://nodejs.org/en/download) installed. Install the package globally:

310 

311```bash theme={null}

171npm install -g @anthropic-ai/claude-code312npm install -g @anthropic-ai/claude-code

172```313```

173 314 

174<Warning>315<Warning>

175 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks.316 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).

176 If you encounter permission errors, see [configure Claude Code](/en/docs/claude-code/troubleshooting#linux-permission-issues) for recommended solutions.

177</Warning>317</Warning>

178 318 

179### Local installation319### Binary integrity and code signing

180 320 

181* After global install via npm, use `claude migrate-installer` to move to local321Each release publishes a `manifest.json` containing SHA256 checksums for every platform binary. The manifest is signed with an Anthropic GPG key, so verifying the signature on the manifest transitively verifies every binary it lists.

182* Avoids autoupdater npm permission issues

183* Some users may be automatically migrated to this method

184 322 

185## Running on AWS or GCP323#### Verify the manifest signature

186 324 

187By default, Claude Code uses the Claude API.325Steps 1-3 require a POSIX shell with `gpg` and `curl`. On Windows, run them in Git Bash or WSL. Step 4 includes a PowerShell option.

188 326 

189For details on running Claude Code on AWS or GCP, see [third-party integrations](/en/docs/claude-code/third-party-integrations).327<Steps>

328 <Step title="Download and import the public key">

329 The release signing key is published at a fixed URL.

190 330 

191## Update Claude Code331 ```bash theme={null}

332 curl -fsSL https://downloads.claude.ai/keys/claude-code.asc | gpg --import

333 ```

192 334 

193### Auto updates335 Display the fingerprint of the imported key.

194 336 

195Claude Code automatically keeps itself up to date to ensure you have the latest features and security fixes.337 ```bash theme={null}

338 gpg --fingerprint security@anthropic.com

339 ```

340 

341 Confirm the output includes this fingerprint:

342 

343 ```text theme={null}

344 31DD DE24 DDFA B679 F42D 7BD2 BAA9 29FF 1A7E CACE

345 ```

346 </Step>

347 

348 <Step title="Download the manifest and signature">

349 Set `VERSION` to the release you want to verify.

350 

351 ```bash theme={null}

352 REPO=https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases

353 VERSION=2.1.89

354 curl -fsSLO "$REPO/$VERSION/manifest.json"

355 curl -fsSLO "$REPO/$VERSION/manifest.json.sig"

356 ```

357 </Step>

358 

359 <Step title="Verify the signature">

360 Verify the detached signature against the manifest.

361 

362 ```bash theme={null}

363 gpg --verify manifest.json.sig manifest.json

364 ```

365 

366 A valid result reports `Good signature from "Anthropic Claude Code Release Signing <security@anthropic.com>"`.

367 

368 `gpg` also prints `WARNING: This key is not certified with a trusted signature!` for any freshly imported key. This is expected. The `Good signature` line confirms the cryptographic check passed. The fingerprint comparison in Step 1 confirms the key itself is authentic.

369 </Step>

196 370 

197* **Update checks**: Performed on startup and periodically while running371 <Step title="Check the binary against the manifest">

198* **Update process**: Downloads and installs automatically in the background372 Compare the SHA256 checksum of your downloaded binary with the value listed under `platforms.<platform>.checksum` in `manifest.json`.

199* **Notifications**: You'll see a notification when updates are installed

200* **Applying updates**: Updates take effect the next time you start Claude Code

201 373 

202**Disable auto-updates:**374 <Tabs>

375 <Tab title="Linux">

376 ```bash theme={null}

377 sha256sum claude

378 ```

379 </Tab>

203 380 

204Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/docs/claude-code/settings):381 <Tab title="macOS">

382 ```bash theme={null}

383 shasum -a 256 claude

384 ```

385 </Tab>

386 

387 <Tab title="Windows PowerShell">

388 ```powershell theme={null}

389 (Get-FileHash claude.exe -Algorithm SHA256).Hash.ToLower()

390 ```

391 </Tab>

392 </Tabs>

393 </Step>

394</Steps>

395 

396<Note>

397 Manifest signatures are available for releases from `2.1.89` onward. Earlier releases publish checksums in `manifest.json` without a detached signature.

398</Note>

399 

400#### Platform code signatures

401 

402In addition to the signed manifest, individual binaries carry platform-native code signatures where supported.

403 

404* **macOS**: signed by "Anthropic PBC" and notarized by Apple. Verify with `codesign --verify --verbose ./claude`.

405* **Windows**: signed by "Anthropic, PBC". Verify with `Get-AuthenticodeSignature .\claude.exe`.

406* **Linux**: use the manifest signature above to verify integrity. Linux binaries are not individually code-signed.

407 

408## Uninstall Claude Code

409 

410To remove Claude Code, follow the instructions for your installation method.

411 

412### Native installation

413 

414Remove the Claude Code binary and version files:

415 

416<Tabs>

417 <Tab title="macOS, Linux, WSL">

418 ```bash theme={null}

419 rm -f ~/.local/bin/claude

420 rm -rf ~/.local/share/claude

421 ```

422 </Tab>

423 

424 <Tab title="Windows PowerShell">

425 ```powershell theme={null}

426 Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force

427 Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force

428 ```

429 </Tab>

430</Tabs>

431 

432### Homebrew installation

433 

434Remove the Homebrew cask:

205 435 

206```bash theme={null}436```bash theme={null}

207export DISABLE_AUTOUPDATER=1437brew uninstall --cask claude-code

208```438```

209 439 

210### Update manually440### WinGet installation

441 

442Remove the WinGet package:

443 

444```powershell theme={null}

445winget uninstall Anthropic.ClaudeCode

446```

447 

448### npm

449 

450Remove the global npm package:

211 451 

212```bash theme={null}452```bash theme={null}

213claude update453npm uninstall -g @anthropic-ai/claude-code

214```454```

455 

456### Remove configuration files

457 

458<Warning>

459 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.

460</Warning>

461 

462To remove Claude Code settings and cached data:

463 

464<Tabs>

465 <Tab title="macOS, Linux, WSL">

466 ```bash theme={null}

467 # Remove user settings and state

468 rm -rf ~/.claude

469 rm ~/.claude.json

470 

471 # Remove project-specific settings (run from your project directory)

472 rm -rf .claude

473 rm -f .mcp.json

474 ```

475 </Tab>

476 

477 <Tab title="Windows PowerShell">

478 ```powershell theme={null}

479 # Remove user settings and state

480 Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force

481 Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force

482 

483 # Remove project-specific settings (run from your project directory)

484 Remove-Item -Path ".claude" -Recurse -Force

485 Remove-Item -Path ".mcp.json" -Force

486 ```

487 </Tab>

488</Tabs>

skills.md +509 −410

Details

1# Agent Skills1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Create, manage, and share Skills to extend Claude's capabilities in Claude Code.5# Extend Claude with skills

4 6 

5This guide shows you how to create, use, and manage Agent Skills in Claude Code. Skills are modular capabilities that extend Claude's functionality through organized folders containing instructions, scripts, and resources.7> Create, manage, and share skills to extend Claude's capabilities in Claude Code. Includes custom commands and bundled skills.

6 8 

7## Prerequisites9Skills 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`.

8 

9* Claude Code version 1.0 or later

10* Basic familiarity with [Claude Code](/en/docs/claude-code/quickstart)

11 

12## What are Agent Skills?

13 

14Agent Skills package expertise into discoverable capabilities. Each Skill consists of a `SKILL.md` file with instructions that Claude reads when relevant, plus optional supporting files like scripts and templates.

15 

16**How Skills are invoked**: Skills are **model-invoked**—Claude autonomously decides when to use them based on your request and the Skill's description. This is different from slash commands, which are **user-invoked** (you explicitly type `/command` to trigger them).

17 

18**Benefits**:

19 

20* Extend Claude's capabilities for your specific workflows

21* Share expertise across your team via git

22* Reduce repetitive prompting

23* Compose multiple Skills for complex tasks

24 

25Learn more in the [Agent Skills overview](/en/docs/agents-and-tools/agent-skills/overview).

26 10 

27<Note>11<Note>

28 For a deep dive into the architecture and real-world applications of Agent Skills, read our engineering blog: [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills).12 For built-in commands like `/help` and `/compact`, see the [built-in commands reference](/en/commands).

29</Note>

30 

31## Create a Skill

32 

33Skills are stored as directories containing a `SKILL.md` file.

34 13 

35### Personal Skills14 **Custom commands have been merged into skills.** A file at `.claude/commands/deploy.md` and a skill at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to [control whether you or Claude invokes them](#control-who-invokes-a-skill), and the ability for Claude to load them automatically when relevant.

36 15</Note>

37Personal Skills are available across all your projects. Store them in `~/.claude/skills/`:

38 

39```bash theme={null}

40mkdir -p ~/.claude/skills/my-skill-name

41```

42 

43**Use personal Skills for**:

44 

45* Your individual workflows and preferences

46* Experimental Skills you're developing

47* Personal productivity tools

48 

49### Project Skills

50 16 

51Project Skills are shared with your team. Store them in `.claude/skills/` within your project:17Claude Code skills follow the [Agent Skills](https://agentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like [invocation control](#control-who-invokes-a-skill), [subagent execution](#run-skills-in-a-subagent), and [dynamic context injection](#inject-dynamic-context).

52 18 

53```bash theme={null}19## Bundled skills

54mkdir -p .claude/skills/my-skill-name

55```

56 20 

57**Use project Skills for**:21Bundled skills ship with Claude Code and are available in every session. Unlike [built-in commands](/en/commands), which execute fixed logic directly, bundled skills are prompt-based: they give Claude a detailed playbook and let it orchestrate the work using its tools. This means bundled skills can spawn parallel agents, read files, and adapt to your codebase.

58 22 

59* Team workflows and conventions23You invoke bundled skills the same way as any other skill: type `/` followed by the skill name. In the table below, `<arg>` indicates a required argument and `[arg]` indicates an optional one.

60* Project-specific expertise

61* Shared utilities and scripts

62 24 

63Project Skills are checked into git and automatically available to team members.25| Skill | Purpose |

26| :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

27| `/batch <instruction>` | Orchestrate large-scale changes across a codebase in parallel. Researches the codebase, decomposes the work into 5 to 30 independent units, and presents a plan. Once approved, spawns one background agent per unit in an isolated [git worktree](/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees). Each agent implements its unit, runs tests, and opens a pull request. Requires a git repository. Example: `/batch migrate src/ from Solid to React` |

28| `/claude-api` | Load Claude API reference material for your project's language (Python, TypeScript, Java, Go, Ruby, C#, PHP, or cURL) and Agent SDK reference for Python and TypeScript. Covers tool use, streaming, batches, structured outputs, and common pitfalls. Also activates automatically when your code imports `anthropic`, `@anthropic-ai/sdk`, or `claude_agent_sdk` |

29| `/debug [description]` | 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 |

30| `/loop [interval] <prompt>` | Run a prompt repeatedly on an interval while the session stays open. Useful for polling a deployment, babysitting a PR, or periodically re-running another skill. Example: `/loop 5m check if the deploy finished`. See [Run prompts on a schedule](/en/scheduled-tasks) |

31| `/simplify [focus]` | Review your recently changed files for code reuse, quality, and efficiency issues, then fix them. Spawns three review agents in parallel, aggregates their findings, and applies fixes. Pass text to focus on specific concerns: `/simplify focus on memory efficiency` |

64 32 

65### Plugin Skills33## Getting started

66 34 

67Skills can also come from [Claude Code plugins](/en/docs/claude-code/plugins). Plugins may bundle Skills that are automatically available when the plugin is installed. These Skills work the same way as personal and project Skills.35### Create your first skill

68 36 

69## Write SKILL.md37This 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`.

70 38 

71Create a `SKILL.md` file with YAML frontmatter and Markdown content:39<Steps>

40 <Step title="Create the skill directory">

41 Create a directory for the skill in your personal skills folder. Personal skills are available across all your projects.

72 42 

73```yaml theme={null}43 ```bash theme={null}

74name: your-skill-name44 mkdir -p ~/.claude/skills/explain-code

75description: Brief description of what this Skill does and when to use it45 ```

46 </Step>

76 47 

77# Your Skill Name48 <Step title="Write SKILL.md">

49 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.

78 50 

79## Instructions51 Create `~/.claude/skills/explain-code/SKILL.md`:

80Provide clear, step-by-step guidance for Claude.

81 52 

82## Examples53 ```yaml theme={null}

83Show concrete examples of using this Skill.54 ---

84```55 name: explain-code

56 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?"

57 ---

85 58 

86**Field requirements**:59 When explaining code, always include:

87 60 

88* `name`: Must use lowercase letters, numbers, and hyphens only (max 64 characters)61 1. **Start with an analogy**: Compare the code to something from everyday life

89* `description`: Brief description of what the Skill does and when to use it (max 1024 characters)62 2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships

63 3. **Walk through the code**: Explain step-by-step what happens

64 4. **Highlight a gotcha**: What's a common mistake or misconception?

90 65 

91The `description` field is critical for Claude to discover when to use your Skill. It should include both what the Skill does and when Claude should use it.66 Keep explanations conversational. For complex concepts, use multiple analogies.

67 ```

68 </Step>

92 69 

93See the [best practices guide](/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules.70 <Step title="Test the skill">

71 You can test it two ways:

94 72 

95## Add supporting files73 **Let Claude invoke it automatically** by asking something that matches the description:

96 74 

97Create additional files alongside SKILL.md:75 ```text theme={null}

76 How does this code work?

77 ```

98 78 

99```79 **Or invoke it directly** with the skill name:

100my-skill/

101├── SKILL.md (required)

102├── reference.md (optional documentation)

103├── examples.md (optional examples)

104├── scripts/

105│ └── helper.py (optional utility)

106└── templates/

107 └── template.txt (optional template)

108```

109 80 

110Reference these files from SKILL.md:81 ```text theme={null}

82 /explain-code src/auth/login.ts

83 ```

111 84 

112````markdown theme={null}85 Either way, Claude should include an analogy and ASCII diagram in its explanation.

113For advanced usage, see [reference.md](reference.md).86 </Step>

87</Steps>

114 88 

115Run the helper script:89### Where skills live

116```bash

117python scripts/helper.py input.txt

118```

119````

120 90 

121Claude reads these files only when needed, using progressive disclosure to manage context efficiently.91Where you store a skill determines who can use it:

122 92 

123## Restrict tool access with allowed-tools93| Location | Path | Applies to |

94| :--------- | :-------------------------------------------------- | :----------------------------- |

95| Enterprise | See [managed settings](/en/settings#settings-files) | All users in your organization |

96| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |

97| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |

98| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |

124 99 

125Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active:100When 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.

126 101 

127```yaml theme={null}102#### Automatic discovery from nested directories

128name: safe-file-reader

129description: Read files without making changes. Use when you need read-only file access.

130allowed-tools: Read, Grep, Glob

131 103 

132# Safe File Reader104When you work with files in subdirectories, Claude Code automatically discovers skills from nested `.claude/skills/` directories. For example, if you're editing a file in `packages/frontend/`, Claude Code also looks for skills in `packages/frontend/.claude/skills/`. This supports monorepo setups where packages have their own skills.

133 105 

134This Skill provides read-only file access.106Each skill is a directory with `SKILL.md` as the entrypoint:

135 107 

136## Instructions108```text theme={null}

1371. Use Read to view file contents109my-skill/

1382. Use Grep to search within files110├── SKILL.md # Main instructions (required)

1393. Use Glob to find files by pattern111├── template.md # Template for Claude to fill in

112├── examples/

113│ └── sample.md # Example output showing expected format

114└── scripts/

115 └── validate.sh # Script Claude can execute

140```116```

141 117 

142When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for:118The `SKILL.md` contains the main instructions and is required. Other files are optional and let you build more powerful skills: templates for Claude to fill in, example outputs showing the expected format, scripts Claude can execute, or detailed reference documentation. Reference these files from your `SKILL.md` so Claude knows what they contain and when to load them. See [Add supporting files](#add-supporting-files) for more details.

143 

144* Read-only Skills that shouldn't modify files

145* Skills with limited scope (e.g., only data analysis, no file writing)

146* Security-sensitive workflows where you want to restrict capabilities

147 

148If `allowed-tools` is not specified, Claude will ask for permission to use tools as normal, following the standard permission model.

149 119 

150<Note>120<Note>

151 `allowed-tools` is only supported for Skills in Claude Code.121 Files in `.claude/commands/` still work and support the same [frontmatter](#frontmatter-reference). Skills are recommended since they support additional features like supporting files.

152</Note>122</Note>

153 123 

154## View available Skills124#### Skills from additional directories

155 

156Skills are automatically discovered by Claude from three sources:

157 125 

158* Personal Skills: `~/.claude/skills/`126The `--add-dir` flag [grants file access](/en/permissions#additional-directories-grant-file-access-not-configuration) rather than configuration discovery, but skills are an exception: `.claude/skills/` within an added directory is loaded automatically and picked up by live change detection, so you can edit those skills during a session without restarting.

159* Project Skills: `.claude/skills/`

160* Plugin Skills: bundled with installed plugins

161 127 

162**To view all available Skills**, ask Claude directly:128Other `.claude/` configuration such as subagents, commands, and output styles is not loaded from additional directories. See the [exceptions table](/en/permissions#additional-directories-grant-file-access-not-configuration) for the complete list of what is and isn't loaded, and the recommended ways to share configuration across projects.

163 129 

164```130<Note>

165What Skills are available?131 CLAUDE.md files from `--add-dir` directories are not loaded by default. To load them, set `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`. See [Load from additional directories](/en/memory#load-from-additional-directories).

166```132</Note>

167 133 

168or134## Configure skills

169 135 

170```136Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.

171List all available Skills

172```

173 137 

174This will show all Skills from all sources, including plugin Skills.138### Types of skill content

175 139 

176**To inspect a specific Skill**, you can also check the filesystem:140Skill files can contain any instructions, but thinking about how you want to invoke them helps guide what to include:

177 141 

178```bash theme={null}142**Reference content** adds knowledge Claude applies to your current work. Conventions, patterns, style guides, domain knowledge. This content runs inline so Claude can use it alongside your conversation context.

179# List personal Skills

180ls ~/.claude/skills/

181 143 

182# List project Skills (if in a project directory)144```yaml theme={null}

183ls .claude/skills/145---

146name: api-conventions

147description: API design patterns for this codebase

148---

184 149 

185# View a specific Skill's content150When writing API endpoints:

186cat ~/.claude/skills/my-skill/SKILL.md151- Use RESTful naming conventions

152- Return consistent error formats

153- Include request validation

187```154```

188 155 

189## Test a Skill156**Task content** gives Claude step-by-step instructions for a specific action, like deployments, commits, or code generation. These are often actions you want to invoke directly with `/skill-name` rather than letting Claude decide when to run them. Add `disable-model-invocation: true` to prevent Claude from triggering it automatically.

190 157 

191After creating a Skill, test it by asking questions that match your description.158```yaml theme={null}

192 159---

193**Example**: If your description mentions "PDF files":160name: deploy

161description: Deploy the application to production

162context: fork

163disable-model-invocation: true

164---

194 165 

166Deploy the application:

1671. Run the test suite

1682. Build the application

1693. Push to the deployment target

195```170```

196Can you help me extract text from this PDF?

197```

198 

199Claude autonomously decides to use your Skill if it matches the request—you don't need to explicitly invoke it. The Skill activates automatically based on the context of your question.

200 

201## Debug a Skill

202 171 

203If Claude doesn't use your Skill, check these common issues:172Your `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.

204 173 

205### Make description specific174### Frontmatter reference

206 175 

207**Too vague**:176Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:

208 177 

209```yaml theme={null}178```yaml theme={null}

210description: Helps with documents179---

211```180name: my-skill

212 181description: What this skill does

213**Specific**:182disable-model-invocation: true

183allowed-tools: Read Grep

184---

214 185 

215```yaml theme={null}186Your skill instructions here...

216description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.

217```187```

218 188 

219Include both what the Skill does and when to use it in the description.189All fields are optional. Only `description` is recommended so Claude knows when to use the skill.

220 190 

221### Verify file path191| Field | Required | Description |

192| :------------------------- | :---------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

193| `name` | No | Display name for the skill. If omitted, uses the directory name. Lowercase letters, numbers, and hyphens only (max 64 characters). |

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. Front-load the key use case: descriptions longer than 250 characters are truncated in the skill listing to reduce context usage. |

195| `argument-hint` | No | Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. |

196| `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| `user-invocable` | No | Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn't invoke directly. Default: `true`. |

198| `allowed-tools` | No | Tools Claude can use without asking permission when this skill is active. Accepts a space-separated string or a YAML list. |

199| `model` | No | Model to use when this skill is active. |

200| `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). |

201| `context` | No | Set to `fork` to run in a forked subagent context. |

202| `agent` | No | Which subagent type to use when `context: fork` is set. |

203| `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. |

204| `paths` | No | Glob patterns that limit when this skill is activated. Accepts a comma-separated string or a YAML list. When set, Claude loads the skill automatically only when working with files matching the patterns. Uses the same format as [path-specific rules](/en/memory#path-specific-rules). |

205| `shell` | No | Shell to use for `` !`command` `` blocks in this skill. Accepts `bash` (default) or `powershell`. Setting `powershell` runs inline shell commands via PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. |

222 206 

223**Personal Skills**: `~/.claude/skills/skill-name/SKILL.md`207#### Available string substitutions

224**Project Skills**: `.claude/skills/skill-name/SKILL.md`

225 208 

226Check the file exists:209Skills support string substitution for dynamic values in the skill content:

227 210 

228```bash theme={null}211| Variable | Description |

229# Personal212| :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

230ls ~/.claude/skills/my-skill/SKILL.md213| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |

214| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |

215| `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. |

216| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |

217| `${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. |

231 218 

232# Project219**Example using substitutions:**

233ls .claude/skills/my-skill/SKILL.md

234```

235 220 

236### Check YAML syntax221```yaml theme={null}

222---

223name: session-logger

224description: Log activity for this session

225---

237 226 

238Invalid YAML prevents the Skill from loading. Verify the frontmatter:227Log the following to logs/${CLAUDE_SESSION_ID}.log:

239 228 

240```bash theme={null}229$ARGUMENTS

241cat SKILL.md | head -n 10

242```230```

243 231 

244Ensure:232### Add supporting files

245 

246* Opening `---` on line 1

247* Closing `---` before Markdown content

248* Valid YAML syntax (no tabs, correct indentation)

249 

250### View errors

251 233 

252Run Claude Code with debug mode to see Skill loading errors:234Skills can include multiple files in their directory. This keeps `SKILL.md` focused on the essentials while letting Claude access detailed reference material only when needed. Large reference docs, API specifications, or example collections don't need to load into context every time the skill runs.

253 235 

254```bash theme={null}236```text theme={null}

255claude --debug237my-skill/

238├── SKILL.md (required - overview and navigation)

239├── reference.md (detailed API docs - loaded when needed)

240├── examples.md (usage examples - loaded when needed)

241└── scripts/

242 └── helper.py (utility script - executed, not loaded)

256```243```

257 244 

258## Share Skills with your team245Reference supporting files from `SKILL.md` so Claude knows what each file contains and when to load it:

259 

260**Recommended approach**: Distribute Skills through [plugins](/en/docs/claude-code/plugins).

261 

262To share Skills via plugin:

263 

2641. Create a plugin with Skills in the `skills/` directory

2652. Add the plugin to a marketplace

2663. Team members install the plugin

267 

268For complete instructions, see [Add Skills to your plugin](/en/docs/claude-code/plugins#add-skills-to-your-plugin).

269 246 

270You can also share Skills directly through project repositories:247```markdown theme={null}

271 248## Additional resources

272### Step 1: Add Skill to your project

273 

274Create a project Skill:

275 249 

276```bash theme={null}250- For complete API details, see [reference.md](reference.md)

277mkdir -p .claude/skills/team-skill251- For usage examples, see [examples.md](examples.md)

278# Create SKILL.md

279```252```

280 253 

281### Step 2: Commit to git254<Tip>Keep `SKILL.md` under 500 lines. Move detailed reference material to separate files.</Tip>

282 255 

283```bash theme={null}256### Control who invokes a skill

284git add .claude/skills/

285git commit -m "Add team Skill for PDF processing"

286git push

287```

288 257 

289### Step 3: Team members get Skills automatically258By default, both you and Claude can invoke any skill. You can type `/skill-name` to invoke it directly, and Claude can load it automatically when relevant to your conversation. Two frontmatter fields let you restrict this:

290 259 

291When team members pull the latest changes, Skills are immediately available:260* **`disable-model-invocation: true`**: Only you can invoke the skill. Use this for workflows with side effects or that you want to control timing, like `/commit`, `/deploy`, or `/send-slack-message`. You don't want Claude deciding to deploy because your code looks ready.

292 261 

293```bash theme={null}262* **`user-invocable: false`**: Only Claude can invoke the skill. Use this for background knowledge that isn't actionable as a command. A `legacy-system-context` skill explains how an old system works. Claude should know this when relevant, but `/legacy-system-context` isn't a meaningful action for users to take.

294git pull

295claude # Skills are now available

296```

297 263 

298## Update a Skill264This example creates a deploy skill that only you can trigger. The `disable-model-invocation: true` field prevents Claude from running it automatically:

299 265 

300Edit SKILL.md directly:266```yaml theme={null}

267---

268name: deploy

269description: Deploy the application to production

270disable-model-invocation: true

271---

301 272 

302```bash theme={null}273Deploy $ARGUMENTS to production:

303# Personal Skill

304code ~/.claude/skills/my-skill/SKILL.md

305 274 

306# Project Skill2751. Run the test suite

307code .claude/skills/my-skill/SKILL.md2762. Build the application

2773. Push to the deployment target

2784. Verify the deployment succeeded

308```279```

309 280 

310Changes take effect the next time you start Claude Code. If Claude Code is already running, restart it to load the updates.281Here's how the two fields affect invocation and context loading:

311 282 

312## Remove a Skill283| Frontmatter | You can invoke | Claude can invoke | When loaded into context |

284| :------------------------------- | :------------- | :---------------- | :----------------------------------------------------------- |

285| (default) | Yes | Yes | Description always in context, full skill loads when invoked |

286| `disable-model-invocation: true` | Yes | No | Description not in context, full skill loads when you invoke |

287| `user-invocable: false` | No | Yes | Description always in context, full skill loads when invoked |

313 288 

314Delete the Skill directory:289<Note>

290 In a regular session, skill descriptions are loaded into context so Claude knows what's available, but full skill content only loads when invoked. [Subagents with preloaded skills](/en/sub-agents#preload-skills-into-subagents) work differently: the full skill content is injected at startup.

291</Note>

315 292 

316```bash theme={null}293### Restrict tool access

317# Personal

318rm -rf ~/.claude/skills/my-skill

319 294 

320# Project295Use the `allowed-tools` field to limit which tools Claude can use when a skill is active. This skill creates a read-only mode where Claude can explore files but not modify them:

321rm -rf .claude/skills/my-skill

322git commit -m "Remove unused Skill"

323```

324 296 

325## Best practices297```yaml theme={null}

298---

299name: safe-reader

300description: Read files without making changes

301allowed-tools: Read Grep Glob

302---

303```

326 304 

327### Keep Skills focused305### Pass arguments to skills

328 306 

329One Skill should address one capability:307Both you and Claude can pass arguments when invoking a skill. Arguments are available via the `$ARGUMENTS` placeholder.

330 308 

331**Focused**:309This skill fixes a GitHub issue by number. The `$ARGUMENTS` placeholder gets replaced with whatever follows the skill name:

332 310 

333* "PDF form filling"311```yaml theme={null}

334* "Excel data analysis"312---

335* "Git commit messages"313name: fix-issue

314description: Fix a GitHub issue

315disable-model-invocation: true

316---

336 317 

337**Too broad**:318Fix GitHub issue $ARGUMENTS following our coding standards.

338 319 

339* "Document processing" (split into separate Skills)3201. Read the issue description

340* "Data tools" (split by data type or operation)3212. Understand the requirements

3223. Implement the fix

3234. Write tests

3245. Create a commit

325```

341 326 

342### Write clear descriptions327When you run `/fix-issue 123`, Claude receives "Fix GitHub issue 123 following our coding standards..."

343 328 

344Help Claude discover when to use Skills by including specific triggers in your description:329If you invoke a skill with arguments but the skill doesn't include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed.

345 330 

346**Clear**:331To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`:

347 332 

348```yaml theme={null}333```yaml theme={null}

349description: Analyze Excel spreadsheets, create pivot tables, and generate charts. Use when working with Excel files, spreadsheets, or analyzing tabular data in .xlsx format.334---

350```335name: migrate-component

351 336description: Migrate a component from one framework to another

352**Vague**:337---

353 338 

354```yaml theme={null}339Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2].

355description: For files340Preserve all existing behavior and tests.

356```341```

357 342 

358### Test with your team343Running `/migrate-component SearchBar React Vue` replaces `$ARGUMENTS[0]` with `SearchBar`, `$ARGUMENTS[1]` with `React`, and `$ARGUMENTS[2]` with `Vue`. The same skill using the `$N` shorthand:

359 

360Have teammates use Skills and provide feedback:

361 344 

362* Does the Skill activate when expected?345```yaml theme={null}

363* Are the instructions clear?346---

364* Are there missing examples or edge cases?347name: migrate-component

365 348description: Migrate a component from one framework to another

366### Document Skill versions349---

367 

368You can document Skill versions in your SKILL.md content to track changes over time. Add a version history section:

369 

370```markdown theme={null}

371# My Skill

372 350 

373## Version History351Migrate the $0 component from $1 to $2.

374- v2.0.0 (2025-10-01): Breaking changes to API352Preserve all existing behavior and tests.

375- v1.1.0 (2025-09-15): Added new features

376- v1.0.0 (2025-09-01): Initial release

377```353```

378 354 

379This helps team members understand what changed between versions.355## Advanced patterns

380 356 

381## Troubleshooting357### Inject dynamic context

382 358 

383### Claude doesn't use my Skill359The `` !`<command>` `` syntax runs shell commands before the skill content is sent to Claude. The command output replaces the placeholder, so Claude receives actual data, not the command itself.

384 360 

385**Symptom**: You ask a relevant question but Claude doesn't use your Skill.361This skill summarizes a pull request by fetching live PR data with the GitHub CLI. The `` !`gh pr diff` `` and other commands run first, and their output gets inserted into the prompt:

386 362 

387**Check**: Is the description specific enough?363```yaml theme={null}

388 364---

389Vague descriptions make discovery difficult. Include both what the Skill does and when to use it, with key terms users would mention.365name: pr-summary

366description: Summarize changes in a pull request

367context: fork

368agent: Explore

369allowed-tools: Bash(gh *)

370---

390 371 

391**Too generic**:372## Pull request context

373- PR diff: !`gh pr diff`

374- PR comments: !`gh pr view --comments`

375- Changed files: !`gh pr diff --name-only`

392 376 

393```yaml theme={null}377## Your task

394description: Helps with data378Summarize this pull request...

395```379```

396 380 

397**Specific**:381When this skill runs:

398 382 

399```yaml theme={null}3831. Each `` !`<command>` `` executes immediately (before Claude sees anything)

400description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files.3842. The output replaces the placeholder in the skill content

401```3853. Claude receives the fully-rendered prompt with actual PR data

402 386 

403**Check**: Is the YAML valid?387This is preprocessing, not something Claude executes. Claude only sees the final result.

404 388 

405Run validation to check for syntax errors:389<Tip>

390 To enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) in a skill, include the word "ultrathink" anywhere in your skill content.

391</Tip>

406 392 

407```bash theme={null}393### Run skills in a subagent

408# View frontmatter

409cat .claude/skills/my-skill/SKILL.md | head -n 15

410 394 

411# Check for common issues395Add `context: fork` to your frontmatter when you want a skill to run in isolation. The skill content becomes the prompt that drives the subagent. It won't have access to your conversation history.

412# - Missing opening or closing ---

413# - Tabs instead of spaces

414# - Unquoted strings with special characters

415```

416 396 

417**Check**: Is the Skill in the correct location?397<Warning>

398 `context: fork` only makes sense for skills with explicit instructions. If your skill contains guidelines like "use these API conventions" without a task, the subagent receives the guidelines but no actionable prompt, and returns without meaningful output.

399</Warning>

418 400 

419```bash theme={null}401Skills and [subagents](/en/sub-agents) work together in two directions:

420# Personal Skills

421ls ~/.claude/skills/*/SKILL.md

422 402 

423# Project Skills403| Approach | System prompt | Task | Also loads |

424ls .claude/skills/*/SKILL.md404| :--------------------------- | :---------------------------------------- | :-------------------------- | :--------------------------- |

425```405| Skill with `context: fork` | From agent type (`Explore`, `Plan`, etc.) | SKILL.md content | CLAUDE.md |

406| Subagent with `skills` field | Subagent's markdown body | Claude's delegation message | Preloaded skills + CLAUDE.md |

426 407 

427### Skill has errors408With `context: fork`, you write the task in your skill and pick an agent type to execute it. For the inverse (defining a custom subagent that uses skills as reference material), see [Subagents](/en/sub-agents#preload-skills-into-subagents).

428 409 

429**Symptom**: The Skill loads but doesn't work correctly.410#### Example: Research skill using Explore agent

430 411 

431**Check**: Are dependencies available?412This skill runs research in a forked Explore agent. The skill content becomes the task, and the agent provides read-only tools optimized for codebase exploration:

432 413 

433Claude will automatically install required dependencies (or ask for permission to install them) when it needs them.414```yaml theme={null}

415---

416name: deep-research

417description: Research a topic thoroughly

418context: fork

419agent: Explore

420---

434 421 

435**Check**: Do scripts have execute permissions?422Research $ARGUMENTS thoroughly:

436 423 

437```bash theme={null}4241. Find relevant files using Glob and Grep

438chmod +x .claude/skills/my-skill/scripts/*.py4252. Read and analyze the code

4263. Summarize findings with specific file references

439```427```

440 428 

441**Check**: Are file paths correct?429When this skill runs:

442 430 

443Use forward slashes (Unix style) in all paths:4311. A new isolated context is created

4322. The subagent receives the skill content as its prompt ("Research \$ARGUMENTS thoroughly...")

4333. The `agent` field determines the execution environment (model, tools, and permissions)

4344. Results are summarized and returned to your main conversation

444 435 

445**Correct**: `scripts/helper.py`436The `agent` field specifies which subagent configuration to use. Options include built-in agents (`Explore`, `Plan`, `general-purpose`) or any custom subagent from `.claude/agents/`. If omitted, uses `general-purpose`.

446**Wrong**: `scripts\helper.py` (Windows style)

447 437 

448### Multiple Skills conflict438### Restrict Claude's skill access

449 439 

450**Symptom**: Claude uses the wrong Skill or seems confused between similar Skills.440By 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.

451 441 

452**Be specific in descriptions**: Help Claude choose the right Skill by using distinct trigger terms in your descriptions.442Three ways to control which skills Claude can invoke:

453 443 

454Instead of:444**Disable all skills** by denying the Skill tool in `/permissions`:

455 

456```yaml theme={null}

457# Skill 1

458description: For data analysis

459 445 

460# Skill 2446```text theme={null}

461description: For analyzing data447# Add to deny rules:

448Skill

462```449```

463 450 

464Use:451**Allow or deny specific skills** using [permission rules](/en/permissions):

465 452 

466```yaml theme={null}453```text theme={null}

467# Skill 1454# Allow only specific skills

468description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking.455Skill(commit)

456Skill(review-pr *)

469 457 

470# Skill 2458# Deny specific skills

471description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics.459Skill(deploy *)

472```460```

473 461 

474## Examples462Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments.

475 463 

476### Simple Skill (single file)464**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.

477 465 

478```466<Note>

479commit-helper/467 The `user-invocable` field only controls menu visibility, not Skill tool access. Use `disable-model-invocation: true` to block programmatic invocation.

480└── SKILL.md468</Note>

481```

482 469 

483```yaml theme={null}470## Share skills

484name: generating-commit-messages

485description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes.

486 471 

487# Generating Commit Messages472Skills can be distributed at different scopes depending on your audience:

488 473 

489## Instructions474* **Project skills**: Commit `.claude/skills/` to version control

475* **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins)

476* **Managed**: Deploy organization-wide through [managed settings](/en/settings#settings-files)

490 477 

4911. Run `git diff --staged` to see changes478### Generate visual output

4922. I'll suggest a commit message with:

493 - Summary under 50 characters

494 - Detailed description

495 - Affected components

496 479 

497## Best practices480Skills can bundle and run scripts in any language, giving Claude capabilities beyond what's possible in a single prompt. One powerful pattern is generating visual output: interactive HTML files that open in your browser for exploring data, debugging, or creating reports.

498 481 

499- Use present tense482This example creates a codebase explorer: an interactive tree view where you can expand and collapse directories, see file sizes at a glance, and identify file types by color.

500- Explain what and why, not how

501```

502 483 

503### Skill with tool permissions484Create the Skill directory:

504 485 

505```486```bash theme={null}

506code-reviewer/487mkdir -p ~/.claude/skills/codebase-visualizer/scripts

507└── SKILL.md

508```488```

509 489 

510```yaml theme={null}490Create `~/.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:

491 

492````yaml theme={null}

511---493---

512name: code-reviewer494name: codebase-visualizer

513description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.495description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.

514allowed-tools: Read, Grep, Glob496allowed-tools: Bash(python *)

515---497---

516 498 

517# Code Reviewer499# Codebase Visualizer

518 500 

519## Review checklist501Generate an interactive HTML tree view that shows your project's file structure with collapsible directories.

520 502 

5211. Code organization and structure503## Usage

5222. Error handling

5233. Performance considerations

5244. Security concerns

5255. Test coverage

526 504 

527## Instructions505Run the visualization script from your project root:

528 506 

5291. Read the target files using Read tool507```bash

5302. Search for patterns using Grep508python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .

5313. Find related files using Glob

5324. Provide detailed feedback on code quality

533```509```

534 510 

535### Multi-file Skill511This creates `codebase-map.html` in the current directory and opens it in your default browser.

536 512 

537```513## What the visualization shows

538pdf-processing/

539├── SKILL.md

540├── FORMS.md

541├── REFERENCE.md

542└── scripts/

543 ├── fill_form.py

544 └── validate.py

545```

546 514 

547**SKILL.md**:515- **Collapsible directories**: Click folders to expand/collapse

548 516- **File sizes**: Displayed next to each file

549````yaml theme={null}517- **Colors**: Different colors for different file types

550name: pdf-processing518- **Directory totals**: Shows aggregate size of each folder

551description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages.519````

552 520 

553# PDF Processing521Create `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with:

522 

523* A **summary sidebar** showing file count, directory count, total size, and number of file types

524* A **bar chart** breaking down the codebase by file type (top 8 by size)

525* A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators

526 

527The script requires Python but uses only built-in libraries, so there are no packages to install:

528 

529```python expandable theme={null}

530#!/usr/bin/env python3

531"""Generate an interactive collapsible tree visualization of a codebase."""

532 

533import json

534import sys

535import webbrowser

536from pathlib import Path

537from collections import Counter

538 

539IGNORE = {'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build'}

540 

541def scan(path: Path, stats: dict) -> dict:

542 result = {"name": path.name, "children": [], "size": 0}

543 try:

544 for item in sorted(path.iterdir()):

545 if item.name in IGNORE or item.name.startswith('.'):

546 continue

547 if item.is_file():

548 size = item.stat().st_size

549 ext = item.suffix.lower() or '(no ext)'

550 result["children"].append({"name": item.name, "size": size, "ext": ext})

551 result["size"] += size

552 stats["files"] += 1

553 stats["extensions"][ext] += 1

554 stats["ext_sizes"][ext] += size

555 elif item.is_dir():

556 stats["dirs"] += 1

557 child = scan(item, stats)

558 if child["children"]:

559 result["children"].append(child)

560 result["size"] += child["size"]

561 except PermissionError:

562 pass

563 return result

564 

565def generate_html(data: dict, stats: dict, output: Path) -> None:

566 ext_sizes = stats["ext_sizes"]

567 total_size = sum(ext_sizes.values()) or 1

568 sorted_exts = sorted(ext_sizes.items(), key=lambda x: -x[1])[:8]

569 colors = {

570 '.js': '#f7df1e', '.ts': '#3178c6', '.py': '#3776ab', '.go': '#00add8',

571 '.rs': '#dea584', '.rb': '#cc342d', '.css': '#264de4', '.html': '#e34c26',

572 '.json': '#6b7280', '.md': '#083fa1', '.yaml': '#cb171e', '.yml': '#cb171e',

573 '.mdx': '#083fa1', '.tsx': '#3178c6', '.jsx': '#61dafb', '.sh': '#4eaa25',

574 }

575 lang_bars = "".join(

576 f'<div class="bar-row"><span class="bar-label">{ext}</span>'

577 f'<div class="bar" style="width:{(size/total_size)*100}%;background:{colors.get(ext,"#6b7280")}"></div>'

578 f'<span class="bar-pct">{(size/total_size)*100:.1f}%</span></div>'

579 for ext, size in sorted_exts

580 )

581 def fmt(b):

582 if b < 1024: return f"{b} B"

583 if b < 1048576: return f"{b/1024:.1f} KB"

584 return f"{b/1048576:.1f} MB"

585 

586 html = f'''<!DOCTYPE html>

587<html><head>

588 <meta charset="utf-8"><title>Codebase Explorer</title>

589 <style>

590 body {{ font: 14px/1.5 system-ui, sans-serif; margin: 0; background: #1a1a2e; color: #eee; }}

591 .container {{ display: flex; height: 100vh; }}

592 .sidebar {{ width: 280px; background: #252542; padding: 20px; border-right: 1px solid #3d3d5c; overflow-y: auto; flex-shrink: 0; }}

593 .main {{ flex: 1; padding: 20px; overflow-y: auto; }}

594 h1 {{ margin: 0 0 10px 0; font-size: 18px; }}

595 h2 {{ margin: 20px 0 10px 0; font-size: 14px; color: #888; text-transform: uppercase; }}

596 .stat {{ display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #3d3d5c; }}

597 .stat-value {{ font-weight: bold; }}

598 .bar-row {{ display: flex; align-items: center; margin: 6px 0; }}

599 .bar-label {{ width: 55px; font-size: 12px; color: #aaa; }}

600 .bar {{ height: 18px; border-radius: 3px; }}

601 .bar-pct {{ margin-left: 8px; font-size: 12px; color: #666; }}

602 .tree {{ list-style: none; padding-left: 20px; }}

603 details {{ cursor: pointer; }}

604 summary {{ padding: 4px 8px; border-radius: 4px; }}

605 summary:hover {{ background: #2d2d44; }}

606 .folder {{ color: #ffd700; }}

607 .file {{ display: flex; align-items: center; padding: 4px 8px; border-radius: 4px; }}

608 .file:hover {{ background: #2d2d44; }}

609 .size {{ color: #888; margin-left: auto; font-size: 12px; }}

610 .dot {{ width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; }}

611 </style>

612</head><body>

613 <div class="container">

614 <div class="sidebar">

615 <h1>📊 Summary</h1>

616 <div class="stat"><span>Files</span><span class="stat-value">{stats["files"]:,}</span></div>

617 <div class="stat"><span>Directories</span><span class="stat-value">{stats["dirs"]:,}</span></div>

618 <div class="stat"><span>Total size</span><span class="stat-value">{fmt(data["size"])}</span></div>

619 <div class="stat"><span>File types</span><span class="stat-value">{len(stats["extensions"])}</span></div>

620 <h2>By file type</h2>

621 {lang_bars}

622 </div>

623 <div class="main">

624 <h1>📁 {data["name"]}</h1>

625 <ul class="tree" id="root"></ul>

626 </div>

627 </div>

628 <script>

629 const data = {json.dumps(data)};

630 const colors = {json.dumps(colors)};

631 function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }}

632 function render(node, parent) {{

633 if (node.children) {{

634 const det = document.createElement('details');

635 det.open = parent === document.getElementById('root');

636 det.innerHTML = `<summary><span class="folder">📁 ${{node.name}}</span><span class="size">${{fmt(node.size)}}</span></summary>`;

637 const ul = document.createElement('ul'); ul.className = 'tree';

638 node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name));

639 node.children.forEach(c => render(c, ul));

640 det.appendChild(ul);

641 const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li);

642 }} else {{

643 const li = document.createElement('li'); li.className = 'file';

644 li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{node.name}}<span class="size">${{fmt(node.size)}}</span>`;

645 parent.appendChild(li);

646 }}

647 }}

648 data.children.forEach(c => render(c, document.getElementById('root')));

649 </script>

650</body></html>'''

651 output.write_text(html)

652 

653if __name__ == '__main__':

654 target = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()

655 stats = {"files": 0, "dirs": 0, "extensions": Counter(), "ext_sizes": Counter()}

656 data = scan(target, stats)

657 out = Path('codebase-map.html')

658 generate_html(data, stats, out)

659 print(f'Generated {out.absolute()}')

660 webbrowser.open(f'file://{out.absolute()}')

661```

662 

663To 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.

664 

665This 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.

554 666 

555## Quick start667## Troubleshooting

556 668 

557Extract text:669### Skill not triggering

558```python

559import pdfplumber

560with pdfplumber.open("doc.pdf") as pdf:

561 text = pdf.pages[0].extract_text()

562```

563 670 

564For form filling, see [FORMS.md](FORMS.md).671If Claude doesn't use your skill when expected:

565For detailed API reference, see [REFERENCE.md](REFERENCE.md).

566 672 

567## Requirements6731. Check the description includes keywords users would naturally say

6742. Verify the skill appears in `What skills are available?`

6753. Try rephrasing your request to match the description more closely

6764. Invoke it directly with `/skill-name` if the skill is user-invocable

568 677 

569Packages must be installed in your environment:678### Skill triggers too often

570```bash

571pip install pypdf pdfplumber

572```

573````

574 679 

575<Note>680If Claude uses your skill when you don't want it:

576 List required packages in the description. Packages must be installed in your environment before Claude can use them.

577</Note>

578 681 

579Claude loads additional files only when needed.6821. Make the description more specific

6832. Add `disable-model-invocation: true` if you only want manual invocation

580 684 

581## Next steps685### Skill descriptions are cut short

582 686 

583<CardGroup cols={2}>687Skill 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.

584 <Card title="Authoring best practices" icon="lightbulb" href="/en/docs/agents-and-tools/agent-skills/best-practices">

585 Write Skills that Claude can use effectively

586 </Card>

587 688 

588 <Card title="Agent Skills overview" icon="book" href="/en/docs/agents-and-tools/agent-skills/overview">689To raise the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable. Or trim descriptions at the source: front-load the key use case, since each entry is capped at 250 characters regardless of budget.

589 Learn how Skills work across Claude products

590 </Card>

591 690 

592 <Card title="Use Skills in the Agent SDK" icon="cube" href="/en/api/agent-sdk/skills">691## Related resources

593 Use Skills programmatically with TypeScript and Python

594 </Card>

595 692 

596 <Card title="Get started with Agent Skills" icon="rocket" href="/en/docs/agents-and-tools/agent-skills/quickstart">693* **[Subagents](/en/sub-agents)**: delegate tasks to specialized agents

597 Create your first Skill694* **[Plugins](/en/plugins)**: package and distribute skills with other extensions

598 </Card>695* **[Hooks](/en/hooks)**: automate workflows around tool events

599</CardGroup>696* **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context

697* **[Built-in commands](/en/commands)**: reference for built-in `/` commands

698* **[Permissions](/en/permissions)**: control tool and skill access

slack.md +235 −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# Claude Code in Slack

6 

7> Delegate coding tasks directly from your Slack workspace

8 

9Claude Code in Slack brings the power of Claude Code directly into your Slack workspace. When you mention `@Claude` with a coding task, Claude automatically detects the intent and creates a Claude Code session on the web, allowing you to delegate development work without leaving your team conversations.

10 

11This integration is built on the existing Claude for Slack app but adds intelligent routing to Claude Code on the web for coding-related requests.

12 

13## Use cases

14 

15* **Bug investigation and fixes**: Ask Claude to investigate and fix bugs as soon as they're reported in Slack channels.

16* **Quick code reviews and modifications**: Have Claude implement small features or refactor code based on team feedback.

17* **Collaborative debugging**: When team discussions provide crucial context (e.g., error reproductions or user reports), Claude can use that information to inform its debugging approach.

18* **Parallel task execution**: Kick off coding tasks in Slack while you continue other work, receiving notifications when complete.

19 

20## Prerequisites

21 

22Before using Claude Code in Slack, ensure you have the following:

23 

24| Requirement | Details |

25| :--------------------- | :----------------------------------------------------------------------------- |

26| Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats) |

27| Claude Code on the web | Access to [Claude Code on the web](/en/claude-code-on-the-web) must be enabled |

28| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |

29| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |

30 

31## Setting up Claude Code in Slack

32 

33<Steps>

34 <Step title="Install the Claude App in Slack">

35 A workspace administrator must install the Claude app from the Slack App Marketplace. Visit the [Slack App Marketplace](https://slack.com/marketplace/A08SF47R6P4) and click "Add to Slack" to begin the installation process.

36 </Step>

37 

38 <Step title="Connect your Claude account">

39 After the app is installed, authenticate your individual Claude account:

40 

41 1. Open the Claude app in Slack by clicking on "Claude" in your Apps section

42 2. Navigate to the App Home tab

43 3. Click "Connect" to link your Slack account with your Claude account

44 4. Complete the authentication flow in your browser

45 </Step>

46 

47 <Step title="Configure Claude Code on the web">

48 Ensure your Claude Code on the web is properly configured:

49 

50 * Visit [claude.ai/code](https://claude.ai/code) and sign in with the same account you connected to Slack

51 * Connect your GitHub account if not already connected

52 * Authenticate at least one repository that you want Claude to work with

53 </Step>

54 

55 <Step title="Choose your routing mode">

56 After connecting your accounts, configure how Claude handles your messages in Slack. Navigate to the Claude App Home in Slack to find the **Routing Mode** setting.

57 

58 | Mode | Behavior |

59 | :-------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

60 | **Code only** | Claude routes all @mentions to Claude Code sessions. Best for teams using Claude in Slack exclusively for development tasks. |

61 | **Code + Chat** | Claude analyzes each message and intelligently routes between Claude Code (for coding tasks) and Claude Chat (for writing, analysis, and general questions). Best for teams who want a single @Claude entry point for all types of work. |

62 

63 <Note>

64 In Code + Chat mode, if Claude routes a message to Chat but you wanted a coding session, you can click "Retry as Code" to create a Claude Code session instead. Similarly, if it's routed to Code but you wanted a Chat session, you can choose that option in that thread.

65 </Note>

66 </Step>

67 

68 <Step title="Add Claude to channels">

69 Claude is not automatically added to any channels after installation. To use Claude in a channel, invite it by typing `/invite @Claude` in that channel. Claude can only respond to @mentions in channels where it has been added.

70 </Step>

71</Steps>

72 

73## How it works

74 

75### Automatic detection

76 

77When you mention @Claude in a Slack channel or thread, Claude automatically analyzes your message to determine if it's a coding task. If Claude detects coding intent, it will route your request to Claude Code on the web instead of responding as a regular chat assistant.

78 

79You can also explicitly tell Claude to handle a request as a coding task, even if it doesn't automatically detect it.

80 

81<Note>

82 Claude Code in Slack only works in channels (public or private). It does not work in direct messages (DMs).

83</Note>

84 

85### Context gathering

86 

87**From threads**: When you @mention Claude in a thread, it gathers context from all messages in that thread to understand the full conversation.

88 

89**From channels**: When mentioned directly in a channel, Claude looks at recent channel messages for relevant context.

90 

91This context helps Claude understand the problem, select the appropriate repository, and inform its approach to the task.

92 

93<Warning>

94 When @Claude is invoked in Slack, Claude is given access to the conversation context to better understand your request. Claude may follow directions from other messages in the context, so users should make sure to only use Claude in trusted Slack conversations.

95</Warning>

96 

97### Session flow

98 

991. **Initiation**: You @mention Claude with a coding request

1002. **Detection**: Claude analyzes your message and detects coding intent

1013. **Session creation**: A new Claude Code session is created on claude.ai/code

1024. **Progress updates**: Claude posts status updates to your Slack thread as work progresses

1035. **Completion**: When finished, Claude @mentions you with a summary and action buttons

1046. **Review**: Click "View Session" to see the full transcript, or "Create PR" to open a pull request

105 

106## User interface elements

107 

108### App Home

109 

110The App Home tab shows your connection status and allows you to connect or disconnect your Claude account from Slack.

111 

112### Message actions

113 

114* **View Session**: Opens the full Claude Code session in your browser where you can see all work performed, continue the session, or make additional requests.

115* **Create PR**: Creates a pull request directly from the session's changes.

116* **Retry as Code**: If Claude initially responds as a chat assistant but you wanted a coding session, click this button to retry the request as a Claude Code task.

117* **Change Repo**: Allows you to select a different repository if Claude chose incorrectly.

118 

119### Repository selection

120 

121Claude automatically selects a repository based on context from your Slack conversation. If multiple repositories could apply, Claude may display a dropdown allowing you to choose the correct one.

122 

123## Access and permissions

124 

125### User-level access

126 

127| Access Type | Requirement |

128| :------------------- | :-------------------------------------------------------------- |

129| Claude Code Sessions | Each user runs sessions under their own Claude account |

130| Usage & Rate Limits | Sessions count against the individual user's plan limits |

131| Repository Access | Users can only access repositories they've personally connected |

132| Session History | Sessions appear in your Claude Code history on claude.ai/code |

133 

134### Workspace-level access

135 

136Slack workspace administrators control whether the Claude app is available in their workspace:

137 

138| Control | Description |

139| :--------------------------- | :---------------------------------------------------------------------------------------------------------------- |

140| App installation | Workspace admins decide whether to install the Claude app from the Slack App Marketplace |

141| Enterprise Grid distribution | For Enterprise Grid organizations, organization admins can control which workspaces have access to the Claude app |

142| App removal | Removing the app from a workspace immediately revokes access for all users in that workspace |

143 

144### Channel-based access control

145 

146Claude is not automatically added to any channels after installation. Users must explicitly invite Claude to channels where they want to use it:

147 

148* **Invite required**: Type `/invite @Claude` in any channel to add Claude to that channel

149* **Channel membership controls access**: Claude can only respond to @mentions in channels where it has been added

150* **Access gating through channels**: Admins can control who uses Claude Code by managing which channels Claude is invited to and who has access to those channels

151* **Private channel support**: Claude works in both public and private channels, giving teams flexibility in controlling visibility

152 

153This channel-based model allows teams to restrict Claude Code usage to specific channels, providing an additional layer of access control beyond workspace-level permissions.

154 

155## What's accessible where

156 

157**In Slack**: You'll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible.

158 

159**On the web**: The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests.

160 

161For Enterprise and Team accounts, sessions created from Claude in Slack are

162automatically visible to the organization. See [Claude Code on the Web sharing](/en/claude-code-on-the-web#sharing-sessions)

163for more details.

164 

165## Best practices

166 

167### Writing effective requests

168 

169* **Be specific**: Include file names, function names, or error messages when relevant.

170* **Provide context**: Mention the repository or project if it's not clear from the conversation.

171* **Define success**: Explain what "done" looks like—should Claude write tests? Update documentation? Create a PR?

172* **Use threads**: Reply in threads when discussing bugs or features so Claude can gather the full context.

173 

174### When to use Slack vs. web

175 

176**Use Slack when**: Context already exists in a Slack discussion, you want to kick off a task asynchronously, or you're collaborating with teammates who need visibility.

177 

178**Use the web directly when**: You need to upload files, want real-time interaction during development, or are working on longer, more complex tasks.

179 

180## Troubleshooting

181 

182### Sessions not starting

183 

1841. Verify your Claude account is connected in the Claude App Home

1852. Check that you have Claude Code on the web access enabled

1863. Ensure you have at least one GitHub repository connected to Claude Code

187 

188### Repository not showing

189 

1901. Connect the repository in Claude Code on the web at [claude.ai/code](https://claude.ai/code)

1912. Verify your GitHub permissions for that repository

1923. Try disconnecting and reconnecting your GitHub account

193 

194### Wrong repository selected

195 

1961. Click the "Change Repo" button to select a different repository

1972. Include the repository name in your request for more accurate selection

198 

199### Authentication errors

200 

2011. Disconnect and reconnect your Claude account in the App Home

2022. Ensure you're signed into the correct Claude account in your browser

2033. Check that your Claude plan includes Claude Code access

204 

205### Session expiration

206 

2071. Sessions remain accessible in your Claude Code history on the web

2082. You can continue or reference past sessions from [claude.ai/code](https://claude.ai/code)

209 

210## Current limitations

211 

212* **GitHub only**: Currently supports repositories on GitHub.

213* **One PR at a time**: Each session can create one pull request.

214* **Rate limits apply**: Sessions use your individual Claude plan's rate limits.

215* **Web access required**: Users must have Claude Code on the web access; those without it will only get standard Claude chat responses.

216 

217## Related resources

218 

219<CardGroup>

220 <Card title="Claude Code on the web" icon="globe" href="/en/claude-code-on-the-web">

221 Learn more about Claude Code on the web

222 </Card>

223 

224 <Card title="Claude for Slack" icon="slack" href="https://claude.com/claude-and-slack">

225 General Claude for Slack documentation

226 </Card>

227 

228 <Card title="Slack App Marketplace" icon="store" href="https://slack.com/marketplace/A08SF47R6P4">

229 Install the Claude app from the Slack Marketplace

230 </Card>

231 

232 <Card title="Claude Help Center" icon="circle-question" href="https://support.claude.com">

233 Get additional support

234 </Card>

235</CardGroup>

slash-commands.md +0 −482 deleted

File DeletedView Diff

1# Slash commands

2 

3> Control Claude's behavior during an interactive session with slash commands.

4 

5## Built-in slash commands

6 

7| Command | Purpose |

8| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------- |

9| `/add-dir` | Add additional working directories |

10| `/agents` | Manage custom AI subagents for specialized tasks |

11| `/bug` | Report bugs (sends conversation to Anthropic) |

12| `/clear` | Clear conversation history |

13| `/compact [instructions]` | Compact conversation with optional focus instructions |

14| `/config` | Open the Settings interface (Config tab) |

15| `/cost` | Show token usage statistics (see [cost tracking guide](/en/docs/claude-code/costs#using-the-cost-command) for subscription-specific details) |

16| `/doctor` | Checks the health of your Claude Code installation |

17| `/help` | Get usage help |

18| `/init` | Initialize project with CLAUDE.md guide |

19| `/login` | Switch Anthropic accounts |

20| `/logout` | Sign out from your Anthropic account |

21| `/mcp` | Manage MCP server connections and OAuth authentication |

22| `/memory` | Edit CLAUDE.md memory files |

23| `/model` | Select or change the AI model |

24| `/permissions` | View or update [permissions](/en/docs/claude-code/iam#configuring-permissions) |

25| `/pr_comments` | View pull request comments |

26| `/review` | Request code review |

27| `/sandbox` | Enable sandboxed bash tool with filesystem and network isolation for safer, more autonomous execution |

28| `/rewind` | Rewind the conversation and/or code |

29| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |

30| `/terminal-setup` | Install Shift+Enter key binding for newlines (iTerm2 and VSCode only) |

31| `/usage` | Show plan usage limits and rate limit status (subscription plans only) |

32| `/vim` | Enter vim mode for alternating insert and command modes |

33 

34## Custom slash commands

35 

36Custom slash commands allow you to define frequently-used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures.

37 

38### Syntax

39 

40```

41/<command-name> [arguments]

42```

43 

44#### Parameters

45 

46| Parameter | Description |

47| :--------------- | :---------------------------------------------------------------- |

48| `<command-name>` | Name derived from the Markdown filename (without `.md` extension) |

49| `[arguments]` | Optional arguments passed to the command |

50 

51### Command types

52 

53#### Project commands

54 

55Commands stored in your repository and shared with your team. When listed in `/help`, these commands show "(project)" after their description.

56 

57**Location**: `.claude/commands/`

58 

59In the following example, we create the `/optimize` command:

60 

61```bash theme={null}

62# Create a project command

63mkdir -p .claude/commands

64echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md

65```

66 

67#### Personal commands

68 

69Commands available across all your projects. When listed in `/help`, these commands show "(user)" after their description.

70 

71**Location**: `~/.claude/commands/`

72 

73In the following example, we create the `/security-review` command:

74 

75```bash theme={null}

76# Create a personal command

77mkdir -p ~/.claude/commands

78echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md

79```

80 

81### Features

82 

83#### Namespacing

84 

85Organize commands in subdirectories. The subdirectories are used for organization and appear in the command description, but they do not affect the command name itself. The description will show whether the command comes from the project directory (`.claude/commands`) or the user-level directory (`~/.claude/commands`), along with the subdirectory name.

86 

87Conflicts between user and project level commands are not supported. Otherwise, multiple commands with the same base file name can coexist.

88 

89For example, a file at `.claude/commands/frontend/component.md` creates the command `/component` with description showing "(project:frontend)".

90Meanwhile, a file at `~/.claude/commands/component.md` creates the command `/component` with description showing "(user)".

91 

92#### Arguments

93 

94Pass dynamic values to commands using argument placeholders:

95 

96##### All arguments with `$ARGUMENTS`

97 

98The `$ARGUMENTS` placeholder captures all arguments passed to the command:

99 

100```bash theme={null}

101# Command definition

102echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md

103 

104# Usage

105> /fix-issue 123 high-priority

106# $ARGUMENTS becomes: "123 high-priority"

107```

108 

109##### Individual arguments with `$1`, `$2`, etc.

110 

111Access specific arguments individually using positional parameters (similar to shell scripts):

112 

113```bash theme={null}

114# Command definition

115echo 'Review PR #$1 with priority $2 and assign to $3' > .claude/commands/review-pr.md

116 

117# Usage

118> /review-pr 456 high alice

119# $1 becomes "456", $2 becomes "high", $3 becomes "alice"

120```

121 

122Use positional arguments when you need to:

123 

124* Access arguments individually in different parts of your command

125* Provide defaults for missing arguments

126* Build more structured commands with specific parameter roles

127 

128#### Bash command execution

129 

130Execute bash commands before the slash command runs using the `!` prefix. The output is included in the command context. You *must* include `allowed-tools` with the `Bash` tool, but you can choose the specific bash commands to allow.

131 

132For example:

133 

134```markdown theme={null}

135allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)

136description: Create a git commit

137 

138## Context

139 

140- Current git status: !`git status`

141- Current git diff (staged and unstaged changes): !`git diff HEAD`

142- Current branch: !`git branch --show-current`

143- Recent commits: !`git log --oneline -10`

144 

145## Your task

146 

147Based on the above changes, create a single git commit.

148```

149 

150#### File references

151 

152Include file contents in commands using the `@` prefix to [reference files](/en/docs/claude-code/common-workflows#reference-files-and-directories).

153 

154For example:

155 

156```markdown theme={null}

157# Reference a specific file

158 

159Review the implementation in @src/utils/helpers.js

160 

161# Reference multiple files

162 

163Compare @src/old-version.js with @src/new-version.js

164```

165 

166#### Thinking mode

167 

168Slash commands can trigger extended thinking by including [extended thinking keywords](/en/docs/claude-code/common-workflows#use-extended-thinking).

169 

170### Frontmatter

171 

172Command files support frontmatter, useful for specifying metadata about the command:

173 

174| Frontmatter | Purpose | Default |

175| :------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------- |

176| `allowed-tools` | List of tools the command can use | Inherits from the conversation |

177| `argument-hint` | The arguments expected for the slash command. Example: `argument-hint: add [tagId] \| remove [tagId] \| list`. This hint is shown to the user when auto-completing the slash command. | None |

178| `description` | Brief description of the command | Uses the first line from the prompt |

179| `model` | Specific model string (see [Models overview](/en/docs/about-claude/models/overview)) | Inherits from the conversation |

180| `disable-model-invocation` | Whether to prevent `SlashCommand` tool from calling this command | false |

181 

182For example:

183 

184```markdown theme={null}

185allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)

186argument-hint: [message]

187description: Create a git commit

188model: claude-3-5-haiku-20241022

189 

190Create a git commit with message: $ARGUMENTS

191```

192 

193Example using positional arguments:

194 

195```markdown theme={null}

196argument-hint: [pr-number] [priority] [assignee]

197description: Review pull request

198 

199Review PR #$1 with priority $2 and assign to $3.

200Focus on security, performance, and code style.

201```

202 

203## Plugin commands

204 

205[Plugins](/en/docs/claude-code/plugins) can provide custom slash commands that integrate seamlessly with Claude Code. Plugin commands work exactly like user-defined commands but are distributed through [plugin marketplaces](/en/docs/claude-code/plugin-marketplaces).

206 

207### How plugin commands work

208 

209Plugin commands are:

210 

211* **Namespaced**: Commands can use the format `/plugin-name:command-name` to avoid conflicts (plugin prefix is optional unless there are name collisions)

212* **Automatically available**: Once a plugin is installed and enabled, its commands appear in `/help`

213* **Fully integrated**: Support all command features (arguments, frontmatter, bash execution, file references)

214 

215### Plugin command structure

216 

217**Location**: `commands/` directory in plugin root

218 

219**File format**: Markdown files with frontmatter

220 

221**Basic command structure**:

222 

223```markdown theme={null}

224description: Brief description of what the command does

225 

226# Command Name

227 

228Detailed instructions for Claude on how to execute this command.

229Include specific guidance on parameters, expected outcomes, and any special considerations.

230```

231 

232**Advanced command features**:

233 

234* **Arguments**: Use placeholders like `{arg1}` in command descriptions

235* **Subdirectories**: Organize commands in subdirectories for namespacing

236* **Bash integration**: Commands can execute shell scripts and programs

237* **File references**: Commands can reference and modify project files

238 

239### Invocation patterns

240 

241```shell Direct command (when no conflicts) theme={null}

242/command-name

243```

244 

245```shell Plugin-prefixed (when needed for disambiguation) theme={null}

246/plugin-name:command-name

247```

248 

249```shell With arguments (if command supports them) theme={null}

250/command-name arg1 arg2

251```

252 

253## MCP slash commands

254 

255MCP servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers.

256 

257### Command format

258 

259MCP commands follow the pattern:

260 

261```

262/mcp__<server-name>__<prompt-name> [arguments]

263```

264 

265### Features

266 

267#### Dynamic discovery

268 

269MCP commands are automatically available when:

270 

271* An MCP server is connected and active

272* The server exposes prompts through the MCP protocol

273* The prompts are successfully retrieved during connection

274 

275#### Arguments

276 

277MCP prompts can accept arguments defined by the server:

278 

279```

280# Without arguments

281> /mcp__github__list_prs

282 

283# With arguments

284> /mcp__github__pr_review 456

285> /mcp__jira__create_issue "Bug title" high

286```

287 

288#### Naming conventions

289 

290* Server and prompt names are normalized

291* Spaces and special characters become underscores

292* Names are lowercased for consistency

293 

294### Managing MCP connections

295 

296Use the `/mcp` command to:

297 

298* View all configured MCP servers

299* Check connection status

300* Authenticate with OAuth-enabled servers

301* Clear authentication tokens

302* View available tools and prompts from each server

303 

304### MCP permissions and wildcards

305 

306When configuring [permissions for MCP tools](/en/docs/claude-code/iam#tool-specific-permission-rules), note that **wildcards are not supported**:

307 

308* ✅ **Correct**: `mcp__github` (approves ALL tools from the github server)

309* ✅ **Correct**: `mcp__github__get_issue` (approves specific tool)

310* ❌ **Incorrect**: `mcp__github__*` (wildcards not supported)

311 

312To approve all tools from an MCP server, use just the server name: `mcp__servername`. To approve specific tools only, list each tool individually.

313 

314## `SlashCommand` tool

315 

316The `SlashCommand` tool allows Claude to execute [custom slash commands](/en/docs/claude-code/slash-commands#custom-slash-commands) programmatically

317during a conversation. This gives Claude the ability to invoke custom commands

318on your behalf when appropriate.

319 

320To encourage Claude to trigger `SlashCommand` tool, your instructions (prompts,

321CLAUDE.md, etc.) generally need to reference the command by name with its slash.

322 

323Example:

324 

325```

326> Run /write-unit-test when you are about to start writing tests.

327```

328 

329This tool puts each available custom slash command's metadata into context up to the

330character budget limit. You can use `/context` to monitor token usage and follow

331the operations below to manage context.

332 

333### `SlashCommand` tool supported commands

334 

335`SlashCommand` tool only supports custom slash commands that:

336 

337* Are user-defined. Built-in commands like `/compact` and `/init` are *not* supported.

338* Have the `description` frontmatter field populated. We use the `description` in the context.

339 

340For Claude Code versions >= 1.0.124, you can see which custom slash commands

341`SlashCommand` tool can invoke by running `claude --debug` and triggering a query.

342 

343### Disable `SlashCommand` tool

344 

345To prevent Claude from executing any slash commands via the tool:

346 

347```bash theme={null}

348/permissions

349# Add to deny rules: SlashCommand

350```

351 

352This will also remove SlashCommand tool (and the slash command descriptions) from context.

353 

354### Disable specific commands only

355 

356To prevent a specific slash command from becoming available, add

357`disable-model-invocation: true` to the slash command's frontmatter.

358 

359This will also remove the command's metadata from context.

360 

361### `SlashCommand` permission rules

362 

363The permission rules support:

364 

365* **Exact match**: `SlashCommand:/commit` (allows only `/commit` with no arguments)

366* **Prefix match**: `SlashCommand:/review-pr:*` (allows `/review-pr` with any arguments)

367 

368### Character budget limit

369 

370The `SlashCommand` tool includes a character budget to limit the size of command

371descriptions shown to Claude. This prevents token overflow when many commands

372are available.

373 

374The budget includes each custom slash command's name, args, and description.

375 

376* **Default limit**: 15,000 characters

377* **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable

378 

379When the character budget is exceeded, Claude will see only a subset of the

380available commands. In `/context`, a warning will show with "M of N commands".

381 

382## Skills vs slash commands

383 

384**Slash commands** and **Agent Skills** serve different purposes in Claude Code:

385 

386### Use slash commands for

387 

388**Quick, frequently-used prompts**:

389 

390* Simple prompt snippets you use often

391* Quick reminders or templates

392* Frequently-used instructions that fit in one file

393 

394**Examples**:

395 

396* `/review` → "Review this code for bugs and suggest improvements"

397* `/explain` → "Explain this code in simple terms"

398* `/optimize` → "Analyze this code for performance issues"

399 

400### Use Skills for

401 

402**Comprehensive capabilities with structure**:

403 

404* Complex workflows with multiple steps

405* Capabilities requiring scripts or utilities

406* Knowledge organized across multiple files

407* Team workflows you want to standardize

408 

409**Examples**:

410 

411* PDF processing Skill with form-filling scripts and validation

412* Data analysis Skill with reference docs for different data types

413* Documentation Skill with style guides and templates

414 

415### Key differences

416 

417| Aspect | Slash Commands | Agent Skills |

418| -------------- | -------------------------------- | ----------------------------------- |

419| **Complexity** | Simple prompts | Complex capabilities |

420| **Structure** | Single .md file | Directory with SKILL.md + resources |

421| **Discovery** | Explicit invocation (`/command`) | Automatic (based on context) |

422| **Files** | One file only | Multiple files, scripts, templates |

423| **Scope** | Project or personal | Project or personal |

424| **Sharing** | Via git | Via git |

425 

426### Example comparison

427 

428**As a slash command**:

429 

430```markdown theme={null}

431# .claude/commands/review.md

432Review this code for:

433- Security vulnerabilities

434- Performance issues

435- Code style violations

436```

437 

438Usage: `/review` (manual invocation)

439 

440**As a Skill**:

441 

442```

443.claude/skills/code-review/

444├── SKILL.md (overview and workflows)

445├── SECURITY.md (security checklist)

446├── PERFORMANCE.md (performance patterns)

447├── STYLE.md (style guide reference)

448└── scripts/

449 └── run-linters.sh

450```

451 

452Usage: "Can you review this code?" (automatic discovery)

453 

454The Skill provides richer context, validation scripts, and organized reference material.

455 

456### When to use each

457 

458**Use slash commands**:

459 

460* You invoke the same prompt repeatedly

461* The prompt fits in a single file

462* You want explicit control over when it runs

463 

464**Use Skills**:

465 

466* Claude should discover the capability automatically

467* Multiple files or scripts are needed

468* Complex workflows with validation steps

469* Team needs standardized, detailed guidance

470 

471Both slash commands and Skills can coexist. Use the approach that fits your needs.

472 

473Learn more about [Agent Skills](/en/docs/claude-code/skills).

474 

475## See also

476 

477* [Plugins](/en/docs/claude-code/plugins) - Extend Claude Code with custom commands through plugins

478* [Identity and Access Management](/en/docs/claude-code/iam) - Complete guide to permissions, including MCP tool permissions

479* [Interactive mode](/en/docs/claude-code/interactive-mode) - Shortcuts, input modes, and interactive features

480* [CLI reference](/en/docs/claude-code/cli-reference) - Command-line flags and options

481* [Settings](/en/docs/claude-code/settings) - Configuration options

482* [Memory management](/en/docs/claude-code/memory) - Managing Claude's memory across sessions

statusline.md +931 −126

Details

1# Status line configuration1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Create a custom status line for Claude Code to display contextual information5# Customize your status line

4 6 

5Make Claude Code your own with a custom status line that displays at the bottom of the Claude Code interface, similar to how terminal prompts (PS1) work in shells like Oh-my-zsh.7> Configure a custom status bar to monitor context window usage, costs, and git status in Claude Code

6 8 

7## Create a custom status line9The status line is a customizable bar at the bottom of Claude Code that runs any shell script you configure. It receives JSON session data on stdin and displays whatever your script prints, giving you a persistent, at-a-glance view of context usage, costs, git status, or anything else you want to track.

8 10 

9You can either:11Status lines are useful when you:

10 12 

11* Run `/statusline` to ask Claude Code to help you set up a custom status line. By default, it will try to reproduce your terminal's prompt, but you can provide additional instructions about the behavior you want to Claude Code, such as `/statusline show the model name in orange`13* Want to monitor context window usage as you work

14* Need to track session costs

15* Work across multiple sessions and need to distinguish them

16* Want git branch and status always visible

12 17 

13* Directly add a `statusLine` command to your `.claude/settings.json`:18Here's an example of a [multi-line status line](#display-multiple-lines) that displays git info on the first line and a color-coded context bar on the second.

19 

20<Frame>

21 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="A multi-line status line showing model name, directory, git branch on the first line, and a context usage progress bar with cost and duration on the second line" width="776" height="212" data-path="images/statusline-multiline.png" />

22</Frame>

23 

24This page walks through [setting up a basic status line](#set-up-a-status-line), explains [how the data flows](#how-status-lines-work) from Claude Code to your script, lists [all the fields you can display](#available-data), and provides [ready-to-use examples](#examples) for common patterns like git status, cost tracking, and progress bars.

25 

26## Set up a status line

27 

28Use the [`/statusline` command](#use-the-statusline-command) to have Claude Code generate a script for you, or [manually create a script](#manually-configure-a-status-line) and add it to your settings.

29 

30### Use the /statusline command

31 

32The `/statusline` command accepts natural language instructions describing what you want displayed. Claude Code generates a script file in `~/.claude/` and updates your settings automatically:

33 

34```text theme={null}

35/statusline show model name and context percentage with a progress bar

36```

37 

38### Manually configure a status line

39 

40Add a `statusLine` field to your user settings (`~/.claude/settings.json`, where `~` is your home directory) or [project settings](/en/settings#settings-files). Set `type` to `"command"` and point `command` to a script path or an inline shell command. For a full walkthrough of creating a script, see [Build a status line step by step](#build-a-status-line-step-by-step).

14 41 

15```json theme={null}42```json theme={null}

16{43{

17 "statusLine": {44 "statusLine": {

18 "type": "command",45 "type": "command",

19 "command": "~/.claude/statusline.sh",46 "command": "~/.claude/statusline.sh",

20 "padding": 0 // Optional: set to 0 to let status line go to edge47 "padding": 2

48 }

49}

50```

51 

52The `command` field runs in a shell, so you can also use inline commands instead of a script file. This example uses `jq` to parse the JSON input and display the model name and context percentage:

53 

54```json theme={null}

55{

56 "statusLine": {

57 "type": "command",

58 "command": "jq -r '\"[\\(.model.display_name)] \\(.context_window.used_percentage // 0)% context\"'"

21 }59 }

22}60}

23```61```

24 62 

25## How it Works63The optional `padding` field adds extra horizontal spacing (in characters) to the status line content. Defaults to `0`. This padding is in addition to the interface's built-in spacing, so it controls relative indentation rather than absolute distance from the terminal edge.

26 64 

27* The status line is updated when the conversation messages update65### Disable the status line

28* Updates run at most every 300ms

29* The first line of stdout from your command becomes the status line text

30* ANSI color codes are supported for styling your status line

31* Claude Code passes contextual information about the current session (model, directories, etc.) as JSON to your script via stdin

32 66 

33## JSON Input Structure67Run `/statusline` and ask it to remove or clear your status line (e.g., `/statusline delete`, `/statusline clear`, `/statusline remove it`). You can also manually delete the `statusLine` field from your settings.json.

34 68 

35Your status line command receives structured data via stdin in JSON format:69## Build a status line step by step

36 70 

37```json theme={null}71This walkthrough shows what's happening under the hood by manually creating a status line that displays the current model, working directory, and context window usage percentage.

38{72 

39 "hook_event_name": "Status",73<Note>Running [`/statusline`](#use-the-statusline-command) with a description of what you want configures all of this for you automatically.</Note>

40 "session_id": "abc123...",74 

41 "transcript_path": "/path/to/transcript.json",75These examples use Bash scripts, which work on macOS and Linux. On Windows, see [Windows configuration](#windows-configuration) for PowerShell and Git Bash examples.

76 

77<Frame>

78 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=696445e59ca0059213250651ad23db6b" alt="A status line showing model name, directory, and context percentage" width="726" height="164" data-path="images/statusline-quickstart.png" />

79</Frame>

80 

81<Steps>

82 <Step title="Create a script that reads JSON and prints output">

83 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.github.io/jq/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.

84 

85 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):

86 

87 ```bash theme={null}

88 #!/bin/bash

89 # Read JSON data that Claude Code sends to stdin

90 input=$(cat)

91 

92 # Extract fields using jq

93 MODEL=$(echo "$input" | jq -r '.model.display_name')

94 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

95 # The "// 0" provides a fallback if the field is null

96 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

97 

98 # Output the status line - ${DIR##*/} extracts just the folder name

99 echo "[$MODEL] 📁 ${DIR##*/} | ${PCT}% context"

100 ```

101 </Step>

102 

103 <Step title="Make it executable">

104 Mark the script as executable so your shell can run it:

105 

106 ```bash theme={null}

107 chmod +x ~/.claude/statusline.sh

108 ```

109 </Step>

110 

111 <Step title="Add to settings">

112 Tell Claude Code to run your script as the status line. Add this configuration to `~/.claude/settings.json`, which sets `type` to `"command"` (meaning "run this shell command") and points `command` to your script:

113 

114 ```json theme={null}

115 {

116 "statusLine": {

117 "type": "command",

118 "command": "~/.claude/statusline.sh"

119 }

120 }

121 ```

122 

123 Your status line appears at the bottom of the interface. Settings reload automatically, but changes won't appear until your next interaction with Claude Code.

124 </Step>

125</Steps>

126 

127## How status lines work

128 

129Claude Code runs your script and pipes [JSON session data](#available-data) to it via stdin. Your script reads the JSON, extracts what it needs, and prints text to stdout. Claude Code displays whatever your script prints.

130 

131**When it updates**

132 

133Your script runs after each new assistant message, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won't appear until your next interaction with Claude Code triggers an update.

134 

135**What your script can output**

136 

137* **Multiple lines**: each `echo` or `print` statement displays as a separate row. See the [multi-line example](#display-multiple-lines).

138* **Colors**: use [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) like `\033[32m` for green (terminal must support them). See the [git status example](#git-status-with-colors).

139* **Links**: use [OSC 8 escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code#OSC) to make text clickable (Cmd+click on macOS, Ctrl+click on Windows/Linux). Requires a terminal that supports hyperlinks like iTerm2, Kitty, or WezTerm. See the [clickable links example](#clickable-links).

140 

141<Note>The status line runs locally and does not consume API tokens. It temporarily hides during certain UI interactions, including autocomplete suggestions, the help menu, and permission prompts.</Note>

142 

143## Available data

144 

145Claude Code sends the following JSON fields to your script via stdin:

146 

147| Field | Description |

148| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

149| `model.id`, `model.display_name` | Current model identifier and display name |

150| `cwd`, `workspace.current_dir` | Current working directory. Both fields contain the same value; `workspace.current_dir` is preferred for consistency with `workspace.project_dir`. |

151| `workspace.project_dir` | Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session |

152| `workspace.added_dirs` | Additional directories added via `/add-dir` or `--add-dir`. Empty array if none have been added |

153| `cost.total_cost_usd` | Total session cost in USD |

154| `cost.total_duration_ms` | Total wall-clock time since the session started, in milliseconds |

155| `cost.total_api_duration_ms` | Total time spent waiting for API responses in milliseconds |

156| `cost.total_lines_added`, `cost.total_lines_removed` | Lines of code changed |

157| `context_window.total_input_tokens`, `context_window.total_output_tokens` | Cumulative token counts across the session |

158| `context_window.context_window_size` | Maximum context window size in tokens. 200000 by default, or 1000000 for models with extended context. |

159| `context_window.used_percentage` | Pre-calculated percentage of context window used |

160| `context_window.remaining_percentage` | Pre-calculated percentage of context window remaining |

161| `context_window.current_usage` | Token counts from the last API call, described in [context window fields](#context-window-fields) |

162| `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. |

163| `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 |

164| `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 |

165| `session_id` | Unique session identifier |

166| `session_name` | Custom session name set with the `--name` flag or `/rename`. Absent if no custom name has been set |

167| `transcript_path` | Path to conversation transcript file |

168| `version` | Claude Code version |

169| `output_style.name` | Name of the current output style |

170| `vim.mode` | Current vim mode (`NORMAL` or `INSERT`) when [vim mode](/en/interactive-mode#vim-editor-mode) is enabled |

171| `agent.name` | Agent name when running with the `--agent` flag or agent settings configured |

172| `worktree.name` | Name of the active worktree. Present only during `--worktree` sessions |

173| `worktree.path` | Absolute path to the worktree directory |

174| `worktree.branch` | Git branch name for the worktree (for example, `"worktree-my-feature"`). Absent for hook-based worktrees |

175| `worktree.original_cwd` | The directory Claude was in before entering the worktree |

176| `worktree.original_branch` | Git branch checked out before entering the worktree. Absent for hook-based worktrees |

177 

178<Accordion title="Full JSON schema">

179 Your status line command receives this JSON structure via stdin:

180 

181 ```json theme={null}

182 {

42 "cwd": "/current/working/directory",183 "cwd": "/current/working/directory",

184 "session_id": "abc123...",

185 "session_name": "my-session",

186 "transcript_path": "/path/to/transcript.jsonl",

43 "model": {187 "model": {

44 "id": "claude-opus-4-1",188 "id": "claude-opus-4-6",

45 "display_name": "Opus"189 "display_name": "Opus"

46 },190 },

47 "workspace": {191 "workspace": {

48 "current_dir": "/current/working/directory",192 "current_dir": "/current/working/directory",

49 "project_dir": "/original/project/directory"193 "project_dir": "/original/project/directory",

194 "added_dirs": []

50 },195 },

51 "version": "1.0.80",196 "version": "2.1.90",

52 "output_style": {197 "output_style": {

53 "name": "default"198 "name": "default"

54 },199 },


58 "total_api_duration_ms": 2300,203 "total_api_duration_ms": 2300,

59 "total_lines_added": 156,204 "total_lines_added": 156,

60 "total_lines_removed": 23205 "total_lines_removed": 23

206 },

207 "context_window": {

208 "total_input_tokens": 15234,

209 "total_output_tokens": 4521,

210 "context_window_size": 200000,

211 "used_percentage": 8,

212 "remaining_percentage": 92,

213 "current_usage": {

214 "input_tokens": 8500,

215 "output_tokens": 1200,

216 "cache_creation_input_tokens": 5000,

217 "cache_read_input_tokens": 2000

61 }218 }

62}219 },

63```220 "exceeds_200k_tokens": false,

221 "rate_limits": {

222 "five_hour": {

223 "used_percentage": 23.5,

224 "resets_at": 1738425600

225 },

226 "seven_day": {

227 "used_percentage": 41.2,

228 "resets_at": 1738857600

229 }

230 },

231 "vim": {

232 "mode": "NORMAL"

233 },

234 "agent": {

235 "name": "security-reviewer"

236 },

237 "worktree": {

238 "name": "my-feature",

239 "path": "/path/to/.claude/worktrees/my-feature",

240 "branch": "worktree-my-feature",

241 "original_cwd": "/path/to/project",

242 "original_branch": "main"

243 }

244 }

245 ```

64 246 

65## Example Scripts247 **Fields that may be absent** (not present in JSON):

66 248 

67### Simple Status Line249 * `session_name`: appears only when a custom name has been set with `--name` or `/rename`

250 * `vim`: appears only when vim mode is enabled

251 * `agent`: appears only when running with the `--agent` flag or agent settings configured

252 * `worktree`: appears only during `--worktree` sessions. When present, `branch` and `original_branch` may also be absent for hook-based worktrees

253 * `rate_limits`: appears only for Claude.ai subscribers (Pro/Max) after the first API response in the session. Each window (`five_hour`, `seven_day`) may be independently absent. Use `jq -r '.rate_limits.five_hour.used_percentage // empty'` to handle absence gracefully.

68 254 

69```bash theme={null}255 **Fields that may be `null`**:

70#!/bin/bash

71# Read JSON input from stdin

72input=$(cat)

73 256 

74# Extract values using jq257 * `context_window.current_usage`: `null` before the first API call in a session

75MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')258 * `context_window.used_percentage`, `context_window.remaining_percentage`: may be `null` early in the session

76CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

77 259 

78echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}"260 Handle missing fields with conditional access and null values with fallback defaults in your scripts.

79```261</Accordion>

262 

263### Context window fields

264 

265The `context_window` object provides two ways to track context usage:

266 

267* **Cumulative totals** (`total_input_tokens`, `total_output_tokens`): sum of all tokens across the entire session, useful for tracking total consumption

268* **Current usage** (`current_usage`): token counts from the most recent API call, use this for accurate context percentage since it reflects the actual context state

269 

270The `current_usage` object contains:

271 

272* `input_tokens`: input tokens in current context

273* `output_tokens`: output tokens generated

274* `cache_creation_input_tokens`: tokens written to cache

275* `cache_read_input_tokens`: tokens read from cache

276 

277The `used_percentage` field is calculated from input tokens only: `input_tokens + cache_creation_input_tokens + cache_read_input_tokens`. It does not include `output_tokens`.

278 

279If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.

280 

281The `current_usage` object is `null` before the first API call in a session.

282 

283## Examples

80 284 

81### Git-Aware Status Line285These examples show common status line patterns. To use any example:

82 286 

83```bash theme={null}2871. Save the script to a file like `~/.claude/statusline.sh` (or `.py`/`.js`)

84#!/bin/bash2882. Make it executable: `chmod +x ~/.claude/statusline.sh`

85# Read JSON input from stdin2893. Add the path to your [settings](#manually-configure-a-status-line)

86input=$(cat)

87 290 

88# Extract values using jq291The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.

89MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')

90CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

91 292 

92# Show git branch if in a git repo293### Context window usage

93GIT_BRANCH=""294 

94if git rev-parse --git-dir > /dev/null 2>&1; then295Display the current model and context window usage with a visual progress bar. Each script reads JSON from stdin, extracts the `used_percentage` field, and builds a 10-character bar where filled blocks (▓) represent usage:

296 

297<Frame>

298 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=15b58ab3602f036939145dde3165c6f7" alt="A status line showing model name and a progress bar with percentage" width="448" height="152" data-path="images/statusline-context-window-usage.png" />

299</Frame>

300 

301<CodeGroup>

302 ```bash Bash theme={null}

303 #!/bin/bash

304 # Read all of stdin into a variable

305 input=$(cat)

306 

307 # Extract fields with jq, "// 0" provides fallback for null

308 MODEL=$(echo "$input" | jq -r '.model.display_name')

309 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

310 

311 # Build progress bar: printf -v creates a run of spaces, then

312 # ${var// /▓} replaces each space with a block character

313 BAR_WIDTH=10

314 FILLED=$((PCT * BAR_WIDTH / 100))

315 EMPTY=$((BAR_WIDTH - FILLED))

316 BAR=""

317 [ "$FILLED" -gt 0 ] && printf -v FILL "%${FILLED}s" && BAR="${FILL// /▓}"

318 [ "$EMPTY" -gt 0 ] && printf -v PAD "%${EMPTY}s" && BAR="${BAR}${PAD// /░}"

319 

320 echo "[$MODEL] $BAR $PCT%"

321 ```

322 

323 ```python Python theme={null}

324 #!/usr/bin/env python3

325 import json, sys

326 

327 # json.load reads and parses stdin in one step

328 data = json.load(sys.stdin)

329 model = data['model']['display_name']

330 # "or 0" handles null values

331 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

332 

333 # String multiplication builds the bar

334 filled = pct * 10 // 100

335 bar = '▓' * filled + '░' * (10 - filled)

336 

337 print(f"[{model}] {bar} {pct}%")

338 ```

339 

340 ```javascript Node.js theme={null}

341 #!/usr/bin/env node

342 // Node.js reads stdin asynchronously with events

343 let input = '';

344 process.stdin.on('data', chunk => input += chunk);

345 process.stdin.on('end', () => {

346 const data = JSON.parse(input);

347 const model = data.model.display_name;

348 // Optional chaining (?.) safely handles null fields

349 const pct = Math.floor(data.context_window?.used_percentage || 0);

350 

351 // String.repeat() builds the bar

352 const filled = Math.floor(pct * 10 / 100);

353 const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);

354 

355 console.log(`[${model}] ${bar} ${pct}%`);

356 });

357 ```

358</CodeGroup>

359 

360### Git status with colors

361 

362Show git branch with color-coded indicators for staged and modified files. This script uses [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) for terminal colors: `\033[32m` is green, `\033[33m` is yellow, and `\033[0m` resets to default.

363 

364<Frame>

365 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e656f34f90d1d9a1d0e220988914345f" alt="A status line showing model, directory, git branch, and colored indicators for staged and modified files" width="742" height="178" data-path="images/statusline-git-context.png" />

366</Frame>

367 

368Each script checks if the current directory is a git repository, counts staged and modified files, and displays color-coded indicators:

369 

370<CodeGroup>

371 ```bash Bash theme={null}

372 #!/bin/bash

373 input=$(cat)

374 

375 MODEL=$(echo "$input" | jq -r '.model.display_name')

376 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

377 

378 GREEN='\033[32m'

379 YELLOW='\033[33m'

380 RESET='\033[0m'

381 

382 if git rev-parse --git-dir > /dev/null 2>&1; then

95 BRANCH=$(git branch --show-current 2>/dev/null)383 BRANCH=$(git branch --show-current 2>/dev/null)

96 if [ -n "$BRANCH" ]; then384 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

97 GIT_BRANCH=" | 🌿 $BRANCH"385 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

386 

387 GIT_STATUS=""

388 [ "$STAGED" -gt 0 ] && GIT_STATUS="${GREEN}+${STAGED}${RESET}"

389 [ "$MODIFIED" -gt 0 ] && GIT_STATUS="${GIT_STATUS}${YELLOW}~${MODIFIED}${RESET}"

390 

391 echo -e "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH $GIT_STATUS"

392 else

393 echo "[$MODEL] 📁 ${DIR##*/}"

98 fi394 fi

99fi395 ```

100 396 

101echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH"397 ```python Python theme={null}

102```398 #!/usr/bin/env python3

399 import json, sys, subprocess, os

400 

401 data = json.load(sys.stdin)

402 model = data['model']['display_name']

403 directory = os.path.basename(data['workspace']['current_dir'])

404 

405 GREEN, YELLOW, RESET = '\033[32m', '\033[33m', '\033[0m'

406 

407 try:

408 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

409 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

410 staged_output = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

411 modified_output = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

412 staged = len(staged_output.split('\n')) if staged_output else 0

413 modified = len(modified_output.split('\n')) if modified_output else 0

414 

415 git_status = f"{GREEN}+{staged}{RESET}" if staged else ""

416 git_status += f"{YELLOW}~{modified}{RESET}" if modified else ""

417 

418 print(f"[{model}] 📁 {directory} | 🌿 {branch} {git_status}")

419 except:

420 print(f"[{model}] 📁 {directory}")

421 ```

422 

423 ```javascript Node.js theme={null}

424 #!/usr/bin/env node

425 const { execSync } = require('child_process');

426 const path = require('path');

427 

428 let input = '';

429 process.stdin.on('data', chunk => input += chunk);

430 process.stdin.on('end', () => {

431 const data = JSON.parse(input);

432 const model = data.model.display_name;

433 const dir = path.basename(data.workspace.current_dir);

434 

435 const GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RESET = '\x1b[0m';

436 

437 try {

438 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

439 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

440 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

441 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

442 

443 let gitStatus = staged ? `${GREEN}+${staged}${RESET}` : '';

444 gitStatus += modified ? `${YELLOW}~${modified}${RESET}` : '';

445 

446 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} ${gitStatus}`);

447 } catch {

448 console.log(`[${model}] 📁 ${dir}`);

449 }

450 });

451 ```

452</CodeGroup>

453 

454### Cost and duration tracking

455 

456Track 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.

457 

458Each script formats cost as currency and converts milliseconds to minutes and seconds:

459 

460<Frame>

461 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e3444a51fe6f3440c134bd5f1f08ad29" alt="A status line showing model name, session cost, and duration" width="588" height="180" data-path="images/statusline-cost-tracking.png" />

462</Frame>

463 

464<CodeGroup>

465 ```bash Bash theme={null}

466 #!/bin/bash

467 input=$(cat)

468 

469 MODEL=$(echo "$input" | jq -r '.model.display_name')

470 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

471 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

472 

473 COST_FMT=$(printf '$%.2f' "$COST")

474 DURATION_SEC=$((DURATION_MS / 1000))

475 MINS=$((DURATION_SEC / 60))

476 SECS=$((DURATION_SEC % 60))

477 

478 echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"

479 ```

480 

481 ```python Python theme={null}

482 #!/usr/bin/env python3

483 import json, sys

484 

485 data = json.load(sys.stdin)

486 model = data['model']['display_name']

487 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

488 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

489 

490 duration_sec = duration_ms // 1000

491 mins, secs = duration_sec // 60, duration_sec % 60

492 

493 print(f"[{model}] 💰 ${cost:.2f} | ⏱️ {mins}m {secs}s")

494 ```

495 

496 ```javascript Node.js theme={null}

497 #!/usr/bin/env node

498 let input = '';

499 process.stdin.on('data', chunk => input += chunk);

500 process.stdin.on('end', () => {

501 const data = JSON.parse(input);

502 const model = data.model.display_name;

503 const cost = data.cost?.total_cost_usd || 0;

504 const durationMs = data.cost?.total_duration_ms || 0;

103 505 

104### Python Example506 const durationSec = Math.floor(durationMs / 1000);

507 const mins = Math.floor(durationSec / 60);

508 const secs = durationSec % 60;

105 509 

106```python theme={null}510 console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`);

107#!/usr/bin/env python3511 });

108import json512 ```

109import sys513</CodeGroup>

110import os

111 514 

112# Read JSON from stdin515### Display multiple lines

113data = json.load(sys.stdin)

114 516 

115# Extract values517Your script can output multiple lines to create a richer display. Each `echo` statement produces a separate row in the status area.

116model = data['model']['display_name']518 

117current_dir = os.path.basename(data['workspace']['current_dir'])519<Frame>

520 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="A multi-line status line showing model name, directory, git branch on the first line, and a context usage progress bar with cost and duration on the second line" width="776" height="212" data-path="images/statusline-multiline.png" />

521</Frame>

522 

523This example combines several techniques: threshold-based colors (green under 70%, yellow 70-89%, red 90%+), a progress bar, and git branch info. Each `print` or `echo` statement creates a separate row:

524 

525<CodeGroup>

526 ```bash Bash theme={null}

527 #!/bin/bash

528 input=$(cat)

529 

530 MODEL=$(echo "$input" | jq -r '.model.display_name')

531 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

532 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

533 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

534 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

535 

536 CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

537 

538 # Pick bar color based on context usage

539 if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"

540 elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"

541 else BAR_COLOR="$GREEN"; fi

542 

543 FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))

544 printf -v FILL "%${FILLED}s"; printf -v PAD "%${EMPTY}s"

545 BAR="${FILL// /█}${PAD// /░}"

546 

547 MINS=$((DURATION_MS / 60000)); SECS=$(((DURATION_MS % 60000) / 1000))

548 

549 BRANCH=""

550 git rev-parse --git-dir > /dev/null 2>&1 && BRANCH=" | 🌿 $(git branch --show-current 2>/dev/null)"

551 

552 echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"

553 COST_FMT=$(printf '$%.2f' "$COST")

554 echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"

555 ```

556 

557 ```python Python theme={null}

558 #!/usr/bin/env python3

559 import json, sys, subprocess, os

560 

561 data = json.load(sys.stdin)

562 model = data['model']['display_name']

563 directory = os.path.basename(data['workspace']['current_dir'])

564 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

565 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

566 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

567 

568 CYAN, GREEN, YELLOW, RED, RESET = '\033[36m', '\033[32m', '\033[33m', '\033[31m', '\033[0m'

569 

570 bar_color = RED if pct >= 90 else YELLOW if pct >= 70 else GREEN

571 filled = pct // 10

572 bar = '█' * filled + '░' * (10 - filled)

573 

574 mins, secs = duration_ms // 60000, (duration_ms % 60000) // 1000

118 575 

119# Check for git branch

120git_branch = ""

121if os.path.exists('.git'):

122 try:576 try:

123 with open('.git/HEAD', 'r') as f:577 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True, stderr=subprocess.DEVNULL).strip()

124 ref = f.read().strip()578 branch = f" | 🌿 {branch}" if branch else ""

125 if ref.startswith('ref: refs/heads/'):

126 git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}"

127 except:579 except:

128 pass580 branch = ""

129 581 

130print(f"[{model}] 📁 {current_dir}{git_branch}")582 print(f"{CYAN}[{model}]{RESET} 📁 {directory}{branch}")

131```583 print(f"{bar_color}{bar}{RESET} {pct}% | {YELLOW}${cost:.2f}{RESET} | ⏱️ {mins}m {secs}s")

584 ```

585 

586 ```javascript Node.js theme={null}

587 #!/usr/bin/env node

588 const { execSync } = require('child_process');

589 const path = require('path');

590 

591 let input = '';

592 process.stdin.on('data', chunk => input += chunk);

593 process.stdin.on('end', () => {

594 const data = JSON.parse(input);

595 const model = data.model.display_name;

596 const dir = path.basename(data.workspace.current_dir);

597 const cost = data.cost?.total_cost_usd || 0;

598 const pct = Math.floor(data.context_window?.used_percentage || 0);

599 const durationMs = data.cost?.total_duration_ms || 0;

600 

601 const CYAN = '\x1b[36m', GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RED = '\x1b[31m', RESET = '\x1b[0m';

602 

603 const barColor = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;

604 const filled = Math.floor(pct / 10);

605 const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);

606 

607 const mins = Math.floor(durationMs / 60000);

608 const secs = Math.floor((durationMs % 60000) / 1000);

609 

610 let branch = '';

611 try {

612 branch = execSync('git branch --show-current', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

613 branch = branch ? ` | 🌿 ${branch}` : '';

614 } catch {}

615 

616 console.log(`${CYAN}[${model}]${RESET} 📁 ${dir}${branch}`);

617 console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`);

618 });

619 ```

620</CodeGroup>

621 

622### Clickable links

623 

624This example creates a clickable link to your GitHub repository. It reads the git remote URL, converts SSH format to HTTPS with `sed`, and wraps the repo name in OSC 8 escape codes. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser.

625 

626<Frame>

627 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=4bcc6e7deb7cf52f41ab85a219b52661" alt="A status line showing a clickable link to a GitHub repository" width="726" height="198" data-path="images/statusline-links.png" />

628</Frame>

629 

630Each script gets the git remote URL, converts SSH format to HTTPS, and wraps the repo name in OSC 8 escape codes. The Bash version uses `printf '%b'` which interprets backslash escapes more reliably than `echo -e` across different shells:

132 631 

133### Node.js Example632<CodeGroup>

633 ```bash Bash theme={null}

634 #!/bin/bash

635 input=$(cat)

134 636 

135```javascript theme={null}637 MODEL=$(echo "$input" | jq -r '.model.display_name')

136#!/usr/bin/env node

137 638 

138const fs = require('fs');639 # Convert git SSH URL to HTTPS

139const path = require('path');640 REMOTE=$(git remote get-url origin 2>/dev/null | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//')

140 641 

141// Read JSON from stdin642 if [ -n "$REMOTE" ]; then

142let input = '';643 REPO_NAME=$(basename "$REMOTE")

143process.stdin.on('data', chunk => input += chunk);644 # OSC 8 format: \e]8;;URL\a then TEXT then \e]8;;\a

144process.stdin.on('end', () => {645 # printf %b interprets escape sequences reliably across shells

646 printf '%b' "[$MODEL] 🔗 \e]8;;${REMOTE}\a${REPO_NAME}\e]8;;\a\n"

647 else

648 echo "[$MODEL]"

649 fi

650 ```

651 

652 ```python Python theme={null}

653 #!/usr/bin/env python3

654 import json, sys, subprocess, re, os

655 

656 data = json.load(sys.stdin)

657 model = data['model']['display_name']

658 

659 # Get git remote URL

660 try:

661 remote = subprocess.check_output(

662 ['git', 'remote', 'get-url', 'origin'],

663 stderr=subprocess.DEVNULL, text=True

664 ).strip()

665 # Convert SSH to HTTPS format

666 remote = re.sub(r'^git@github\.com:', 'https://github.com/', remote)

667 remote = re.sub(r'\.git$', '', remote)

668 repo_name = os.path.basename(remote)

669 # OSC 8 escape sequences

670 link = f"\033]8;;{remote}\a{repo_name}\033]8;;\a"

671 print(f"[{model}] 🔗 {link}")

672 except:

673 print(f"[{model}]")

674 ```

675 

676 ```javascript Node.js theme={null}

677 #!/usr/bin/env node

678 const { execSync } = require('child_process');

679 const path = require('path');

680 

681 let input = '';

682 process.stdin.on('data', chunk => input += chunk);

683 process.stdin.on('end', () => {

145 const data = JSON.parse(input);684 const data = JSON.parse(input);

685 const model = data.model.display_name;

686 

687 try {

688 let remote = execSync('git remote get-url origin', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

689 // Convert SSH to HTTPS format

690 remote = remote.replace(/^git@github\.com:/, 'https://github.com/').replace(/\.git$/, '');

691 const repoName = path.basename(remote);

692 // OSC 8 escape sequences

693 const link = `\x1b]8;;${remote}\x07${repoName}\x1b]8;;\x07`;

694 console.log(`[${model}] 🔗 ${link}`);

695 } catch {

696 console.log(`[${model}]`);

697 }

698 });

699 ```

700</CodeGroup>

701 

702### Rate limit usage

703 

704Display Claude.ai subscription rate limit usage in the status line. The `rate_limits` object contains `five_hour` (5-hour rolling window) and `seven_day` (weekly) windows. Each window provides `used_percentage` (0-100) and `resets_at` (Unix epoch seconds when the window resets).

705 

706This field is only present for Claude.ai subscribers (Pro/Max) after the first API response. Each script handles the absent field gracefully:

146 707 

147 // Extract values708<CodeGroup>

709 ```bash Bash theme={null}

710 #!/bin/bash

711 input=$(cat)

712 

713 MODEL=$(echo "$input" | jq -r '.model.display_name')

714 # "// empty" produces no output when rate_limits is absent

715 FIVE_H=$(echo "$input" | jq -r '.rate_limits.five_hour.used_percentage // empty')

716 WEEK=$(echo "$input" | jq -r '.rate_limits.seven_day.used_percentage // empty')

717 

718 LIMITS=""

719 [ -n "$FIVE_H" ] && LIMITS="5h: $(printf '%.0f' "$FIVE_H")%"

720 [ -n "$WEEK" ] && LIMITS="${LIMITS:+$LIMITS }7d: $(printf '%.0f' "$WEEK")%"

721 

722 [ -n "$LIMITS" ] && echo "[$MODEL] | $LIMITS" || echo "[$MODEL]"

723 ```

724 

725 ```python Python theme={null}

726 #!/usr/bin/env python3

727 import json, sys

728 

729 data = json.load(sys.stdin)

730 model = data['model']['display_name']

731 

732 parts = []

733 rate = data.get('rate_limits', {})

734 five_h = rate.get('five_hour', {}).get('used_percentage')

735 week = rate.get('seven_day', {}).get('used_percentage')

736 

737 if five_h is not None:

738 parts.append(f"5h: {five_h:.0f}%")

739 if week is not None:

740 parts.append(f"7d: {week:.0f}%")

741 

742 if parts:

743 print(f"[{model}] | {' '.join(parts)}")

744 else:

745 print(f"[{model}]")

746 ```

747 

748 ```javascript Node.js theme={null}

749 #!/usr/bin/env node

750 let input = '';

751 process.stdin.on('data', chunk => input += chunk);

752 process.stdin.on('end', () => {

753 const data = JSON.parse(input);

148 const model = data.model.display_name;754 const model = data.model.display_name;

149 const currentDir = path.basename(data.workspace.current_dir);

150 755 

151 // Check for git branch756 const parts = [];

152 let gitBranch = '';757 const fiveH = data.rate_limits?.five_hour?.used_percentage;

758 const week = data.rate_limits?.seven_day?.used_percentage;

759 

760 if (fiveH != null) parts.push(`5h: ${Math.round(fiveH)}%`);

761 if (week != null) parts.push(`7d: ${Math.round(week)}%`);

762 

763 console.log(parts.length ? `[${model}] | ${parts.join(' ')}` : `[${model}]`);

764 });

765 ```

766</CodeGroup>

767 

768### Cache expensive operations

769 

770Your status line script runs frequently during active sessions. Commands like `git status` or `git diff` can be slow, especially in large repositories. This example caches git information to a temp file and only refreshes it every 5 seconds.

771 

772Use a stable, fixed filename for the cache file like `/tmp/statusline-git-cache`. Each status line invocation runs as a new process, so process-based identifiers like `$$`, `os.getpid()`, or `process.pid` produce a different value every time and the cache is never reused.

773 

774Each script checks if the cache file is missing or older than 5 seconds before running git commands:

775 

776<CodeGroup>

777 ```bash Bash theme={null}

778 #!/bin/bash

779 input=$(cat)

780 

781 MODEL=$(echo "$input" | jq -r '.model.display_name')

782 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

783 

784 CACHE_FILE="/tmp/statusline-git-cache"

785 CACHE_MAX_AGE=5 # seconds

786 

787 cache_is_stale() {

788 [ ! -f "$CACHE_FILE" ] || \

789 # stat -f %m is macOS, stat -c %Y is Linux

790 [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0))) -gt $CACHE_MAX_AGE ]

791 }

792 

793 if cache_is_stale; then

794 if git rev-parse --git-dir > /dev/null 2>&1; then

795 BRANCH=$(git branch --show-current 2>/dev/null)

796 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

797 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

798 echo "$BRANCH|$STAGED|$MODIFIED" > "$CACHE_FILE"

799 else

800 echo "||" > "$CACHE_FILE"

801 fi

802 fi

803 

804 IFS='|' read -r BRANCH STAGED MODIFIED < "$CACHE_FILE"

805 

806 if [ -n "$BRANCH" ]; then

807 echo "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH +$STAGED ~$MODIFIED"

808 else

809 echo "[$MODEL] 📁 ${DIR##*/}"

810 fi

811 ```

812 

813 ```python Python theme={null}

814 #!/usr/bin/env python3

815 import json, sys, subprocess, os, time

816 

817 data = json.load(sys.stdin)

818 model = data['model']['display_name']

819 directory = os.path.basename(data['workspace']['current_dir'])

820 

821 CACHE_FILE = "/tmp/statusline-git-cache"

822 CACHE_MAX_AGE = 5 # seconds

823 

824 def cache_is_stale():

825 if not os.path.exists(CACHE_FILE):

826 return True

827 return time.time() - os.path.getmtime(CACHE_FILE) > CACHE_MAX_AGE

828 

829 if cache_is_stale():

830 try:

831 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

832 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

833 staged = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

834 modified = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

835 staged_count = len(staged.split('\n')) if staged else 0

836 modified_count = len(modified.split('\n')) if modified else 0

837 with open(CACHE_FILE, 'w') as f:

838 f.write(f"{branch}|{staged_count}|{modified_count}")

839 except:

840 with open(CACHE_FILE, 'w') as f:

841 f.write("||")

842 

843 with open(CACHE_FILE) as f:

844 branch, staged, modified = f.read().strip().split('|')

845 

846 if branch:

847 print(f"[{model}] 📁 {directory} | 🌿 {branch} +{staged} ~{modified}")

848 else:

849 print(f"[{model}] 📁 {directory}")

850 ```

851 

852 ```javascript Node.js theme={null}

853 #!/usr/bin/env node

854 const { execSync } = require('child_process');

855 const fs = require('fs');

856 const path = require('path');

857 

858 let input = '';

859 process.stdin.on('data', chunk => input += chunk);

860 process.stdin.on('end', () => {

861 const data = JSON.parse(input);

862 const model = data.model.display_name;

863 const dir = path.basename(data.workspace.current_dir);

864 

865 const CACHE_FILE = '/tmp/statusline-git-cache';

866 const CACHE_MAX_AGE = 5; // seconds

867 

868 const cacheIsStale = () => {

869 if (!fs.existsSync(CACHE_FILE)) return true;

870 return (Date.now() / 1000) - fs.statSync(CACHE_FILE).mtimeMs / 1000 > CACHE_MAX_AGE;

871 };

872 

873 if (cacheIsStale()) {

153 try {874 try {

154 const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim();875 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

155 if (headContent.startsWith('ref: refs/heads/')) {876 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

156 gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`;877 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

878 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

879 fs.writeFileSync(CACHE_FILE, `${branch}|${staged}|${modified}`);

880 } catch {

881 fs.writeFileSync(CACHE_FILE, '||');

157 }882 }

158 } catch (e) {

159 // Not a git repo or can't read HEAD

160 }883 }

161 884 

162 console.log(`[${model}] 📁 ${currentDir}${gitBranch}`);885 const [branch, staged, modified] = fs.readFileSync(CACHE_FILE, 'utf8').trim().split('|');

163});

164```

165 886 

166### Helper Function Approach887 if (branch) {

167 888 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} +${staged} ~${modified}`);

168For more complex bash scripts, you can create helper functions:889 } else {

169 890 console.log(`[${model}] 📁 ${dir}`);

170```bash theme={null}891 }

171#!/bin/bash892 });

172# Read JSON input once893 ```

173input=$(cat)894</CodeGroup>

174 895 

175# Helper functions for common extractions896### Windows configuration

176get_model_name() { echo "$input" | jq -r '.model.display_name'; }897 

177get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; }898On Windows, Claude Code runs status line commands through Git Bash. You can invoke PowerShell from that shell:

178get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; }899 

179get_version() { echo "$input" | jq -r '.version'; }900<CodeGroup>

180get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; }901 ```json settings.json theme={null}

181get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; }902 {

182get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; }903 "statusLine": {

183get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; }904 "type": "command",

184 905 "command": "powershell -NoProfile -File C:/Users/username/.claude/statusline.ps1"

185# Use the helpers906 }

186MODEL=$(get_model_name)907 }

187DIR=$(get_current_dir)908 ```

188echo "[$MODEL] 📁 ${DIR##*/}"909 

189```910 ```powershell statusline.ps1 theme={null}

911 $input_json = $input | Out-String | ConvertFrom-Json

912 $cwd = $input_json.cwd

913 $model = $input_json.model.display_name

914 $used = $input_json.context_window.used_percentage

915 $dirname = Split-Path $cwd -Leaf

916 

917 if ($used) {

918 Write-Host "$dirname [$model] ctx: $used%"

919 } else {

920 Write-Host "$dirname [$model]"

921 }

922 ```

923</CodeGroup>

924 

925Or run a Bash script directly:

926 

927<CodeGroup>

928 ```json settings.json theme={null}

929 {

930 "statusLine": {

931 "type": "command",

932 "command": "~/.claude/statusline.sh"

933 }

934 }

935 ```

936 

937 ```bash statusline.sh theme={null}

938 #!/usr/bin/env bash

939 input=$(cat)

940 cwd=$(echo "$input" | grep -o '"cwd":"[^"]*"' | cut -d'"' -f4)

941 model=$(echo "$input" | grep -o '"display_name":"[^"]*"' | cut -d'"' -f4)

942 dirname="${cwd##*[/\\]}"

943 echo "$dirname [$model]"

944 ```

945</CodeGroup>

190 946 

191## Tips947## Tips

192 948 

193* Keep your status line concise - it should fit on one line949* **Test with mock input**: `echo '{"model":{"display_name":"Opus"},"context_window":{"used_percentage":25}}' | ./statusline.sh`

194* Use emojis (if your terminal supports them) and colors to make information scannable950* **Keep output short**: the status bar has limited width, so long output may get truncated or wrap awkwardly

195* Use `jq` for JSON parsing in Bash (see examples above)951* **Cache slow operations**: your script runs frequently during active sessions, so commands like `git status` can cause lag. See the [caching example](#cache-expensive-operations) for how to handle this.

196* Test your script by running it manually with mock JSON input: `echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/test"}}' | ./statusline.sh`952 

197* Consider caching expensive operations (like git status) if needed953Community projects like [ccstatusline](https://github.com/sirmalloc/ccstatusline) and [starship-claude](https://github.com/martinemde/starship-claude) provide pre-built configurations with themes and additional features.

198 954 

199## Troubleshooting955## Troubleshooting

200 956 

201* If your status line doesn't appear, check that your script is executable (`chmod +x`)957**Status line not appearing**

202* Ensure your script outputs to stdout (not stderr)958 

959* Verify your script is executable: `chmod +x ~/.claude/statusline.sh`

960* Check that your script outputs to stdout, not stderr

961* Run your script manually to verify it produces output

962* If `disableAllHooks` is set to `true` in your settings, the status line is also disabled. Remove this setting or set it to `false` to re-enable.

963* Run `claude --debug` to log the exit code and stderr from the first status line invocation in a session

964* Ask Claude to read your settings file and execute the `statusLine` command directly to surface errors

965 

966**Status line shows `--` or empty values**

967 

968* Fields may be `null` before the first API response completes

969* Handle null values in your script with fallbacks such as `// 0` in jq

970* Restart Claude Code if values remain empty after multiple messages

971 

972**Context percentage shows unexpected values**

973 

974* Use `used_percentage` for accurate context state rather than cumulative totals

975* The `total_input_tokens` and `total_output_tokens` are cumulative across the session and may exceed the context window size

976* Context percentage may differ from `/context` output due to when each is calculated

977 

978**OSC 8 links not clickable**

979 

980* Verify your terminal supports OSC 8 hyperlinks (iTerm2, Kitty, WezTerm)

981* Terminal.app does not support clickable links

982* SSH and tmux sessions may strip OSC sequences depending on configuration

983* If escape sequences appear as literal text like `\e]8;;`, use `printf '%b'` instead of `echo -e` for more reliable escape handling

984 

985**Display glitches with escape sequences**

986 

987* Complex escape sequences (ANSI colors, OSC 8 links) can occasionally cause garbled output if they overlap with other UI updates

988* If you see corrupted text, try simplifying your script to plain text output

989* Multi-line status lines with escape codes are more prone to rendering issues than single-line plain text

990 

991**Workspace trust required**

992 

993* The status line command only runs if you've accepted the workspace trust dialog for the current directory. Because `statusLine` executes a shell command, it requires the same trust acceptance as hooks and other shell-executing settings.

994* If trust isn't accepted, you'll see the notification `statusline skipped · restart to fix` instead of your status line output. Restart Claude Code and accept the trust prompt to enable it.

995 

996**Script errors or hangs**

997 

998* Scripts that exit with non-zero codes or produce no output cause the status line to go blank

999* Slow scripts block the status line from updating until they complete. Keep scripts fast to avoid stale output.

1000* If a new update triggers while a slow script is running, the in-flight script is cancelled

1001* Test your script independently with mock input before configuring it

1002 

1003**Notifications share the status line row**

1004 

1005* System notifications like MCP server errors, auto-updates, and token warnings display on the right side of the same row as your status line

1006* Enabling verbose mode adds a token counter to this area

1007* On narrow terminals, these notifications may truncate your status line output

sub-agents.md +700 −157

Details

1# Subagents1> ## 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# Create custom subagents

2 6 

3> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.7> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.

4 8 

5Custom subagents in Claude Code are specialized AI assistants that can be invoked to handle specific types of tasks. They enable more efficient problem-solving by providing task-specific configurations with customized system prompts, tools and a separate context window.9Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results. To see the context savings in practice, the [context window visualization](/en/context-window) walks through a session where a subagent handles research in its own separate window.

10 

11<Note>

12 If you need multiple agents working in parallel and communicating with each other, see [agent teams](/en/agent-teams) instead. Subagents work within a single session; agent teams coordinate across separate sessions.

13</Note>

14 

15Subagents help you:

16 

17* **Preserve context** by keeping exploration and implementation out of your main conversation

18* **Enforce constraints** by limiting which tools a subagent can use

19* **Reuse configurations** across projects with user-level subagents

20* **Specialize behavior** with focused system prompts for specific domains

21* **Control costs** by routing tasks to faster, cheaper models like Haiku

22 

23Claude 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.

24 

25Claude 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).

26 

27## Built-in subagents

28 

29Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation's permissions with additional tool restrictions.

30 

31<Tabs>

32 <Tab title="Explore">

33 A fast, read-only agent optimized for searching and analyzing codebases.

34 

35 * **Model**: Haiku (fast, low-latency)

36 * **Tools**: Read-only tools (denied access to Write and Edit tools)

37 * **Purpose**: File discovery, code search, codebase exploration

38 

39 Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.

40 

41 When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis.

42 </Tab>

43 

44 <Tab title="Plan">

45 A research agent used during [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan.

6 46 

7## What are subagents?47 * **Model**: Inherits from main conversation

48 * **Tools**: Read-only tools (denied access to Write and Edit tools)

49 * **Purpose**: Codebase research for planning

8 50 

9Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent:51 When you're in plan mode and Claude needs to understand your codebase, it delegates research to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still gathering necessary context.

52 </Tab>

10 53 

11* Has a specific purpose and expertise area54 <Tab title="General-purpose">

12* Uses its own context window separate from the main conversation55 A capable agent for complex, multi-step tasks that require both exploration and action.

13* Can be configured with specific tools it's allowed to use

14* Includes a custom system prompt that guides its behavior

15 56 

16When Claude Code encounters a task that matches a subagent's expertise, it can delegate that task to the specialized subagent, which works independently and returns results.57 * **Model**: Inherits from main conversation

58 * **Tools**: All tools

59 * **Purpose**: Complex research, multi-step operations, code modifications

17 60 

18## Key benefits61 Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps.

62 </Tab>

19 63 

20<CardGroup cols={2}>64 <Tab title="Other">

21 <Card title="Context preservation" icon="layer-group">65 Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly.

22 Each subagent operates in its own context, preventing pollution of the main conversation and keeping it focused on high-level objectives.

23 </Card>

24 66 

25 <Card title="Specialized expertise" icon="brain">67 | Agent | Model | When Claude uses it |

26 Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks.68 | :---------------- | :----- | :------------------------------------------------------- |

27 </Card>69 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |

70 | Claude Code Guide | Haiku | When you ask questions about Claude Code features |

71 </Tab>

72</Tabs>

28 73 

29 <Card title="Reusability" icon="rotate">74Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents.

30 Once created, subagents can be used across different projects and shared with your team for consistent workflows.

31 </Card>

32 75 

33 <Card title="Flexible permissions" icon="shield-check">76## Quickstart: create your first subagent

34 Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types.

35 </Card>

36</CardGroup>

37 77 

38## Quick start78Subagents are defined in Markdown files with YAML frontmatter. You can [create them manually](#write-subagent-files) or use the `/agents` command.

39 79 

40To create your first subagent:80This walkthrough guides you through creating a user-level subagent with the `/agents` command. The subagent reviews code and suggests improvements for the codebase.

41 81 

42<Steps>82<Steps>

43 <Step title="Open the subagents interface">83 <Step title="Open the subagents interface">

44 Run the following command:84 In Claude Code, run:

45 85 

46 ```86 ```text theme={null}

47 /agents87 /agents

48 ```88 ```

49 </Step>89 </Step>

50 90 

51 <Step title="Select 'Create New Agent'">91 <Step title="Choose a location">

52 Choose whether to create a project-level or user-level subagent92 Select **Create new agent**, then choose **Personal**. This saves the subagent to `~/.claude/agents/` so it's available in all your projects.

93 </Step>

94 

95 <Step title="Generate with Claude">

96 Select **Generate with Claude**. When prompted, describe the subagent:

97 

98 ```text theme={null}

99 A code improvement agent that scans files and suggests improvements

100 for readability, performance, and best practices. It should explain

101 each issue, show the current code, and provide an improved version.

102 ```

103 

104 Claude generates the identifier, description, and system prompt for you.

53 </Step>105 </Step>

54 106 

55 <Step title="Define the subagent">107 <Step title="Select tools">

56 * **Recommended**: Generate with Claude first, then customize to make it yours108 For a read-only reviewer, deselect everything except **Read-only tools**. If you keep all tools selected, the subagent inherits all tools available to the main conversation.

57 * Describe your subagent in detail and when it should be used

58 * Select the tools you want to grant access to (or leave blank to inherit all tools)

59 * The interface shows all available tools, making selection easy

60 * If you're generating with Claude, you can also edit the system prompt in your own editor by pressing `e`

61 </Step>109 </Step>

62 110 

63 <Step title="Save and use">111 <Step title="Select model">

64 Your subagent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly:112 Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns.

113 </Step>

65 114 

115 <Step title="Choose a color">

116 Pick a background color for the subagent. This helps you identify which subagent is running in the UI.

117 </Step>

118 

119 <Step title="Configure memory">

120 Select **User scope** to give the subagent a [persistent memory directory](#enable-persistent-memory) at `~/.claude/agent-memory/`. The subagent uses this to accumulate insights across conversations, such as codebase patterns and recurring issues. Select **None** if you don't want the subagent to persist learnings.

121 </Step>

122 

123 <Step title="Save and try it out">

124 Review the configuration summary. Press `s` or `Enter` to save, or press `e` to save and edit the file in your editor. The subagent is available immediately. Try it:

125 

126 ```text theme={null}

127 Use the code-improver agent to suggest improvements in this project

66 ```128 ```

67 > Use the code-reviewer subagent to check my recent changes129 

68 ```130 Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.

69 </Step>131 </Step>

70</Steps>132</Steps>

71 133 

72## Subagent configuration134You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements.

73 135 

74### File locations136You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options.

75 137 

76Subagents are stored as Markdown files with YAML frontmatter in two possible locations:138## Configure subagents

77 139 

78| Type | Location | Scope | Priority |140### Use the /agents command

79| :-------------------- | :------------------ | :---------------------------- | :------- |

80| **Project subagents** | `.claude/agents/` | Available in current project | Highest |

81| **User subagents** | `~/.claude/agents/` | Available across all projects | Lower |

82 141 

83When subagent names conflict, project-level subagents take precedence over user-level subagents.142The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to:

84 143 

85### Plugin agents144* View all available subagents (built-in, user, project, and plugin)

145* Create new subagents with guided setup or Claude generation

146* Edit existing subagent configuration and tool access

147* Delete custom subagents

148* See which subagents are active when duplicates exist

149 

150This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.

86 151 

87[Plugins](/en/docs/claude-code/plugins) can provide custom subagents that integrate seamlessly with Claude Code. Plugin agents work identically to user-defined agents and appear in the `/agents` interface.152To list all configured subagents from the command line without starting an interactive session, run `claude agents`. This shows agents grouped by source and indicates which are overridden by higher-priority definitions.

88 153 

89**Plugin agent locations**: Plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest).154### Choose the subagent scope

90 155 

91**Using plugin agents**:156Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.

92 157 

93* Plugin agents appear in `/agents` alongside your custom agents158| Location | Scope | Priority | How to create |

94* Can be invoked explicitly: "Use the code-reviewer agent from the security-plugin"159| :--------------------------- | :---------------------- | :---------- | :-------------------------------------------- |

95* Can be invoked automatically by Claude when appropriate160| Managed settings | Organization-wide | 1 (highest) | Deployed via [managed settings](/en/settings) |

96* Can be managed (viewed, inspected) through `/agents` interface161| `--agents` CLI flag | Current session | 2 | Pass JSON when launching Claude Code |

162| `.claude/agents/` | Current project | 3 | Interactive or manual |

163| `~/.claude/agents/` | All your projects | 4 | Interactive or manual |

164| Plugin's `agents/` directory | Where plugin is enabled | 5 (lowest) | Installed with [plugins](/en/plugins) |

97 165 

98See the [plugin components reference](/en/docs/claude-code/plugins-reference#agents) for details on creating plugin agents.166**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively.

99 167 

100### CLI-based configuration168Project subagents are discovered by walking up from the current working directory. Directories added with `--add-dir` [grant file access only](/en/permissions#additional-directories-grant-file-access-not-configuration) and are not scanned for subagents. To share subagents across projects, use `~/.claude/agents/` or a [plugin](/en/plugins).

101 169 

102You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object:170**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.

171 

172**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:

103 173 

104```bash theme={null}174```bash theme={null}

105claude --agents '{175claude --agents '{


108 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",178 "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",

109 "tools": ["Read", "Grep", "Glob", "Bash"],179 "tools": ["Read", "Grep", "Glob", "Bash"],

110 "model": "sonnet"180 "model": "sonnet"

181 },

182 "debugger": {

183 "description": "Debugging specialist for errors and test failures.",

184 "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."

111 }185 }

112}'186}'

113```187```

114 188 

115**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents.189The `--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.

190 

191**Managed subagents** are deployed by organization administrators. Place markdown files in `.claude/agents/` inside the [managed settings directory](/en/settings#settings-files), using the same frontmatter format as project and user subagents. Managed definitions take precedence over project and user subagents with the same name.

116 192 

117**Use case**: This approach is useful for:193**Plugin subagents** come from [plugins](/en/plugins) you've installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.

118 194 

119* Quick testing of subagent configurations195<Note>

120* Session-specific subagents that don't need to be saved196 For security reasons, plugin subagents do not support the `hooks`, `mcpServers`, or `permissionMode` frontmatter fields. These fields are ignored when loading agents from a plugin. If you need them, copy the agent file into `.claude/agents/` or `~/.claude/agents/`. You can also add rules to [`permissions.allow`](/en/settings#permission-settings) in `settings.json` or `settings.local.json`, but these rules apply to the entire session, not just the plugin subagent.

121* Automation scripts that need custom subagents197</Note>

122* Sharing subagent definitions in documentation or scripts

123 198 

124For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/docs/claude-code/cli-reference#agents-flag-format).199Subagent definitions from any of these scopes are also available to [agent teams](/en/agent-teams#use-subagent-definitions-for-teammates): when spawning a teammate, you can reference a subagent type and the teammate uses its `tools` and `model`, with the definition's body appended to the teammate's system prompt as additional instructions. See [agent teams](/en/agent-teams#use-subagent-definitions-for-teammates) for which frontmatter fields apply on that path.

125 200 

126### File format201### Write subagent files

127 202 

128Each subagent is defined in a Markdown file with this structure:203Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:

204 

205<Note>

206 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.

207</Note>

129 208 

130```markdown theme={null}209```markdown theme={null}

131---210---

132name: your-sub-agent-name211name: code-reviewer

133description: Description of when this subagent should be invoked212description: Reviews code for quality and best practices

134tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted213tools: Read, Glob, Grep

135model: sonnet # Optional - specify model alias or 'inherit'214model: sonnet

136---215---

137 216 

138Your subagent's system prompt goes here. This can be multiple paragraphs217You are a code reviewer. When invoked, analyze the code and provide

139and should clearly define the subagent's role, capabilities, and approach218specific, actionable feedback on quality, security, and best practices.

140to solving problems.

141 

142Include specific instructions, best practices, and any constraints

143the subagent should follow.

144```219```

145 220 

146#### Configuration fields221The frontmatter defines the subagent's metadata and configuration. The body becomes the system prompt that guides the subagent's behavior. Subagents receive only this system prompt (plus basic environment details like working directory), not the full Claude Code system prompt.

222 

223#### Supported frontmatter fields

224 

225The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.

147 226 

148| Field | Required | Description |227| Field | Required | Description |

149| :------------ | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |228| :---------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

150| `name` | Yes | Unique identifier using lowercase letters and hyphens |229| `name` | Yes | Unique identifier using lowercase letters and hyphens |

151| `description` | Yes | Natural language description of the subagent's purpose |230| `description` | Yes | When Claude should delegate to this subagent |

152| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |231| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |

153| `model` | No | Model to use for this subagent. Can be a model alias (`sonnet`, `opus`, `haiku`) or `'inherit'` to use the main conversation's model. If omitted, defaults to the [configured subagent model](/en/docs/claude-code/model-config) |232| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |

233| `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` |

234| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `auto`, `dontAsk`, `bypassPermissions`, or `plan` |

235| `maxTurns` | No | Maximum number of agentic turns before the subagent stops |

236| `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 |

237| `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 |

238| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |

239| `memory` | No | [Persistent memory scope](#enable-persistent-memory): `user`, `project`, or `local`. Enables cross-session learning |

240| `background` | No | Set to `true` to always run this subagent as a [background task](#run-subagents-in-foreground-or-background). Default: `false` |

241| `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) |

242| `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 |

243| `color` | No | Display color for the subagent in the task list and transcript. Accepts `red`, `blue`, `green`, `yellow`, `purple`, `orange`, `pink`, or `cyan` |

244| `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 |

245 

246### Choose a model

247 

248The `model` field controls which [AI model](/en/model-config) the subagent uses:

154 249 

155### Model selection250* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`

251* **Full model ID**: Use a full model ID such as `claude-opus-4-6` or `claude-sonnet-4-6`. Accepts the same values as the `--model` flag

252* **inherit**: Use the same model as the main conversation

253* **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation)

156 254 

157The `model` field allows you to control which [AI model](/en/docs/claude-code/model-config) the subagent uses:255When Claude invokes a subagent, it can also pass a `model` parameter for that specific invocation. Claude Code resolves the subagent's model in this order:

158 256 

159* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`2571. The [`CLAUDE_CODE_SUBAGENT_MODEL`](/en/model-config#environment-variables) environment variable, if set

160* **`'inherit'`**: Use the same model as the main conversation (useful for consistency)2582. The per-invocation `model` parameter

161* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)2593. The subagent definition's `model` frontmatter

2604. The main conversation's model

261 

262### Control subagent capabilities

263 

264You can control what subagents can do through tool access, permission modes, and conditional rules.

265 

266#### Available tools

267 

268Subagents can use any of Claude Code's [internal tools](/en/tools-reference). By default, subagents inherit all tools from the main conversation, including MCP tools.

269 

270To restrict tools, use either the `tools` field (allowlist) or the `disallowedTools` field (denylist). This example uses `tools` to exclusively allow Read, Grep, Glob, and Bash. The subagent can't edit files, write files, or use any MCP tools:

271 

272```yaml theme={null}

273---

274name: safe-researcher

275description: Research agent with restricted capabilities

276tools: Read, Grep, Glob, Bash

277---

278```

279 

280This example uses `disallowedTools` to inherit every tool from the main conversation except Write and Edit. The subagent keeps Bash, MCP tools, and everything else:

281 

282```yaml theme={null}

283---

284name: no-writes

285description: Inherits every tool except file writes

286disallowedTools: Write, Edit

287---

288```

289 

290If both are set, `disallowedTools` is applied first, then `tools` is resolved against the remaining pool. A tool listed in both is removed.

291 

292#### Restrict which subagents can be spawned

293 

294When an agent runs as the main thread with `claude --agent`, it can spawn subagents using the Agent tool. To restrict which subagent types it can spawn, use `Agent(agent_type)` syntax in the `tools` field.

295 

296<Note>In version 2.1.63, the Task tool was renamed to Agent. Existing `Task(...)` references in settings and agent definitions still work as aliases.</Note>

297 

298```yaml theme={null}

299---

300name: coordinator

301description: Coordinates work across specialized agents

302tools: Agent(worker, researcher), Read, Bash

303---

304```

305 

306This is an allowlist: only the `worker` and `researcher` subagents can be spawned. If the agent tries to spawn any other type, the request fails and the agent sees only the allowed types in its prompt. To block specific agents while allowing all others, use [`permissions.deny`](#disable-specific-subagents) instead.

307 

308To allow spawning any subagent without restrictions, use `Agent` without parentheses:

309 

310```yaml theme={null}

311tools: Agent, Read, Bash

312```

313 

314If `Agent` is omitted from the `tools` list entirely, the agent cannot spawn any subagents. This restriction only applies to agents running as the main thread with `claude --agent`. Subagents cannot spawn other subagents, so `Agent(agent_type)` has no effect in subagent definitions.

315 

316#### Scope MCP servers to a subagent

317 

318Use 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.

319 

320Each entry in the list is either an inline server definition or a string referencing an MCP server already configured in your session:

321 

322```yaml theme={null}

323---

324name: browser-tester

325description: Tests features in a real browser using Playwright

326mcpServers:

327 # Inline definition: scoped to this subagent only

328 - playwright:

329 type: stdio

330 command: npx

331 args: ["-y", "@playwright/mcp@latest"]

332 # Reference by name: reuses an already-configured server

333 - github

334---

335 

336Use the Playwright tools to navigate, screenshot, and interact with pages.

337```

338 

339Inline definitions use the same schema as `.mcp.json` server entries (`stdio`, `http`, `sse`, `ws`), keyed by the server name.

340 

341To keep an MCP server out of the main conversation entirely and avoid its tool descriptions consuming context there, define it inline here rather than in `.mcp.json`. The subagent gets the tools; the parent conversation does not.

342 

343#### Permission modes

344 

345The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation and can override the mode, except when the parent mode takes precedence as described below.

346 

347| Mode | Behavior |

348| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------ |

349| `default` | Standard permission checking with prompts |

350| `acceptEdits` | Auto-accept file edits except in protected directories |

351| `auto` | [Auto mode](/en/permission-modes#eliminate-prompts-with-auto-mode): a background classifier reviews commands and protected-directory writes |

352| `dontAsk` | Auto-deny permission prompts (explicitly allowed tools still work) |

353| `bypassPermissions` | Skip permission prompts |

354| `plan` | Plan mode (read-only exploration) |

355 

356<Warning>

357 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.

358</Warning>

359 

360If 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.

361 

362#### Preload skills into subagents

363 

364Use the `skills` field to inject skill content into a subagent's context at startup. This gives the subagent domain knowledge without requiring it to discover and load skills during execution.

365 

366```yaml theme={null}

367---

368name: api-developer

369description: Implement API endpoints following team conventions

370skills:

371 - api-conventions

372 - error-handling-patterns

373---

374 

375Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

376```

377 

378The 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.

162 379 

163<Note>380<Note>

164 Using `'inherit'` is particularly useful when you want your subagents to adapt to the model choice of the main conversation, ensuring consistent capabilities and response style throughout your session.381 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.

165</Note>382</Note>

166 383 

167### Available tools384#### Enable persistent memory

168 385 

169Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools.386The `memory` field gives the subagent a persistent directory that survives across conversations. The subagent uses this directory to build up knowledge over time, such as codebase patterns, debugging insights, and architectural decisions.

170 387 

171<Tip>388```yaml theme={null}

172 **Recommended:** Use the `/agents` command to modify tool access - it provides an interactive interface that lists all available tools, including any connected MCP server tools, making it easier to select the ones you need.389---

173</Tip>390name: code-reviewer

391description: Reviews code for quality and best practices

392memory: user

393---

174 394 

175You have two options for configuring tools:395You are a code reviewer. As you review code, update your agent memory with

396patterns, conventions, and recurring issues you discover.

397```

176 398 

177* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools399Choose a scope based on how broadly the memory should apply:

178* **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`)

179 400 

180**MCP Tools**: Subagents can access MCP tools from configured MCP servers. When the `tools` field is omitted, subagents inherit all MCP tools available to the main thread.401| Scope | Location | Use when |

402| :-------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------ |

403| `user` | `~/.claude/agent-memory/<name-of-agent>/` | the subagent should remember learnings across all projects |

404| `project` | `.claude/agent-memory/<name-of-agent>/` | the subagent's knowledge is project-specific and shareable via version control |

405| `local` | `.claude/agent-memory-local/<name-of-agent>/` | the subagent's knowledge is project-specific but should not be checked into version control |

181 406 

182## Managing subagents407When memory is enabled:

183 408 

184### Using the /agents command (Recommended)409* The subagent's system prompt includes instructions for reading and writing to the memory directory.

410* The subagent's system prompt also includes the first 200 lines or 25KB of `MEMORY.md` in the memory directory, whichever comes first, with instructions to curate `MEMORY.md` if it exceeds that limit.

411* Read, Write, and Edit tools are automatically enabled so the subagent can manage its memory files.

185 412 

186The `/agents` command provides a comprehensive interface for subagent management:413##### Persistent memory tips

187 414 

415* `project` is the recommended default scope. It makes subagent knowledge shareable via version control. Use `user` when the subagent's knowledge is broadly applicable across projects, or `local` when the knowledge should not be checked into version control.

416* Ask the subagent to consult its memory before starting work: "Review this PR, and check your memory for patterns you've seen before."

417* Ask the subagent to update its memory after completing a task: "Now that you're done, save what you learned to your memory." Over time, this builds a knowledge base that makes the subagent more effective.

418* Include memory instructions directly in the subagent's markdown file so it proactively maintains its own knowledge base:

419 

420 ```markdown theme={null}

421 Update your agent memory as you discover codepaths, patterns, library

422 locations, and key architectural decisions. This builds up institutional

423 knowledge across conversations. Write concise notes about what you found

424 and where.

425 ```

426 

427#### Conditional rules with hooks

428 

429For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.

430 

431This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash command executes:

432 

433```yaml theme={null}

434---

435name: db-reader

436description: Execute read-only database queries

437tools: Bash

438hooks:

439 PreToolUse:

440 - matcher: "Bash"

441 hooks:

442 - type: command

443 command: "./scripts/validate-readonly-query.sh"

444---

188```445```

189/agents446 

447Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and [exits with code 2](/en/hooks#exit-code-2-behavior-per-event) to block write operations:

448 

449```bash theme={null}

450#!/bin/bash

451# ./scripts/validate-readonly-query.sh

452 

453INPUT=$(cat)

454COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

455 

456# Block SQL write operations (case-insensitive)

457if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then

458 echo "Blocked: Only SELECT queries are allowed" >&2

459 exit 2

460fi

461 

462exit 0

190```463```

191 464 

192This opens an interactive menu where you can:465See [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.

193 466 

194* View all available subagents (built-in, user, and project)467#### Disable specific subagents

195* Create new subagents with guided setup

196* Edit existing custom subagents, including their tool access

197* Delete custom subagents

198* See which subagents are active when duplicates exist

199* **Easily manage tool permissions** with a complete list of available tools

200 468 

201### Direct file management469You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Agent(subagent-name)` where `subagent-name` matches the subagent's name field.

470 

471```json theme={null}

472{

473 "permissions": {

474 "deny": ["Agent(Explore)", "Agent(my-custom-agent)"]

475 }

476}

477```

202 478 

203You can also manage subagents by working directly with their files:479This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:

204 480 

205```bash theme={null}481```bash theme={null}

206# Create a project subagent482claude --disallowedTools "Agent(Explore)"

207mkdir -p .claude/agents483```

208echo '---484 

209name: test-runner485See [Permissions documentation](/en/permissions#tool-specific-permission-rules) for more details on permission rules.

210description: Use proactively to run tests and fix failures486 

487### Define hooks for subagents

488 

489Subagents can define [hooks](/en/hooks) that run during the subagent's lifecycle. There are two ways to configure hooks:

490 

4911. **In the subagent's frontmatter**: Define hooks that run only while that subagent is active

4922. **In `settings.json`**: Define hooks that run in the main session when subagents start or stop

493 

494#### Hooks in subagent frontmatter

495 

496Define 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.

497 

498All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are:

499 

500| Event | Matcher input | When it fires |

501| :------------ | :------------ | :------------------------------------------------------------------ |

502| `PreToolUse` | Tool name | Before the subagent uses a tool |

503| `PostToolUse` | Tool name | After the subagent uses a tool |

504| `Stop` | (none) | When the subagent finishes (converted to `SubagentStop` at runtime) |

505 

506This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:

507 

508```yaml theme={null}

509---

510name: code-reviewer

511description: Review code changes with automatic linting

512hooks:

513 PreToolUse:

514 - matcher: "Bash"

515 hooks:

516 - type: command

517 command: "./scripts/validate-command.sh $TOOL_INPUT"

518 PostToolUse:

519 - matcher: "Edit|Write"

520 hooks:

521 - type: command

522 command: "./scripts/run-linter.sh"

211---523---

524```

525 

526`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.

527 

528#### Project-level hooks for subagent events

529 

530Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session.

531 

532| Event | Matcher input | When it fires |

533| :-------------- | :-------------- | :------------------------------- |

534| `SubagentStart` | Agent type name | When a subagent begins execution |

535| `SubagentStop` | Agent type name | When a subagent completes |

212 536 

213You are a test automation expert. When you see code changes, proactively run the appropriate tests. If tests fail, analyze the failures and fix them while preserving the original test intent.' > .claude/agents/test-runner.md537Both events support matchers to target specific agent types by name. This example runs a setup script only when the `db-agent` subagent starts, and a cleanup script when any subagent stops:

214 538 

215# Create a user subagent539```json theme={null}

216mkdir -p ~/.claude/agents540{

217# ... create subagent file541 "hooks": {

542 "SubagentStart": [

543 {

544 "matcher": "db-agent",

545 "hooks": [

546 { "type": "command", "command": "./scripts/setup-db-connection.sh" }

547 ]

548 }

549 ],

550 "SubagentStop": [

551 {

552 "hooks": [

553 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }

554 ]

555 }

556 ]

557 }

558}

218```559```

219 560 

220## Using subagents effectively561See [Hooks](/en/hooks) for the complete hook configuration format.

221 562 

222### Automatic delegation563## Work with subagents

223 564 

224Claude Code proactively delegates tasks based on:565### Understand automatic delegation

225 566 

226* The task description in your request567Claude automatically delegates tasks based on the task description in your request, the `description` field in subagent configurations, and current context. To encourage proactive delegation, include phrases like "use proactively" in your subagent's description field.

227* The `description` field in subagent configurations

228* Current context and available tools

229 568 

230<Tip>569### Invoke subagents explicitly

231 To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.570 

232</Tip>571When automatic delegation isn't enough, you can request a subagent yourself. Three patterns escalate from a one-off suggestion to a session-wide default:

233 572 

234### Explicit invocation573* **Natural language**: name the subagent in your prompt; Claude decides whether to delegate

574* **@-mention**: guarantees the subagent runs for one task

575* **Session-wide**: the whole session uses that subagent's system prompt, tool restrictions, and model via the `--agent` flag or the `agent` setting

235 576 

236Request a specific subagent by mentioning it in your command:577For natural language, there's no special syntax. Name the subagent and Claude typically delegates:

237 578 

579```text theme={null}

580Use the test-runner subagent to fix failing tests

581Have the code-reviewer subagent look at my recent changes

238```582```

239> Use the test-runner subagent to fix failing tests583 

240> Have the code-reviewer subagent look at my recent changes584**@-mention the subagent.** Type `@` and pick the subagent from the typeahead, the same way you @-mention files. This ensures that specific subagent runs rather than leaving the choice to Claude:

241> Ask the debugger subagent to investigate this error585 

586```text theme={null}

587@"code-reviewer (agent)" look at the auth changes

588```

589 

590Your full message still goes to Claude, which writes the subagent's task prompt based on what you asked. The @-mention controls which subagent Claude invokes, not what prompt it receives.

591 

592Subagents provided by an enabled [plugin](/en/plugins) appear in the typeahead as `<plugin-name>:<agent-name>`. Named background subagents currently running in the session also appear in the typeahead, showing their status next to the name. You can also type the mention manually without using the picker: `@agent-<name>` for local subagents, or `@agent-<plugin-name>:<agent-name>` for plugin subagents.

593 

594**Run the whole session as a subagent.** Pass [`--agent <name>`](/en/cli-reference) to start a session where the main thread itself takes on that subagent's system prompt, tool restrictions, and model:

595 

596```bash theme={null}

597claude --agent code-reviewer

242```598```

243 599 

600The subagent's system prompt replaces the default Claude Code system prompt entirely, the same way [`--system-prompt`](/en/cli-reference) does. `CLAUDE.md` files and project memory still load through the normal message flow. The agent name appears as `@<name>` in the startup header so you can confirm it's active.

601 

602This works with built-in and custom subagents, and the choice persists when you resume the session.

603 

604For a plugin-provided subagent, pass the scoped name: `claude --agent <plugin-name>:<agent-name>`.

605 

606To make it the default for every session in a project, set `agent` in `.claude/settings.json`:

607 

608```json theme={null}

609{

610 "agent": "code-reviewer"

611}

612```

613 

614The CLI flag overrides the setting if both are present.

615 

616### Run subagents in foreground or background

617 

618Subagents can run in the foreground (blocking) or background (concurrent):

619 

620* **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/tools-reference)) are passed through to you.

621* **Background subagents** run concurrently while you continue working. Before launching, Claude Code prompts for any tool permissions the subagent will need, ensuring it has the necessary approvals upfront. Once running, the subagent inherits these permissions and auto-denies anything not pre-approved. If a background subagent needs to ask clarifying questions, that tool call fails but the subagent continues.

622 

623If a background subagent fails due to missing permissions, you can start a new foreground subagent with the same task to retry with interactive prompts.

624 

625Claude decides whether to run subagents in the foreground or background based on the task. You can also:

626 

627* Ask Claude to "run this in the background"

628* Press **Ctrl+B** to background a running task

629 

630To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/env-vars).

631 

632### Common patterns

633 

634#### Isolate high-volume operations

635 

636One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation.

637 

638```text theme={null}

639Use a subagent to run the test suite and report only the failing tests with their error messages

640```

641 

642#### Run parallel research

643 

644For independent investigations, spawn multiple subagents to work simultaneously:

645 

646```text theme={null}

647Research the authentication, database, and API modules in parallel using separate subagents

648```

649 

650Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other.

651 

652<Warning>

653 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.

654</Warning>

655 

656For tasks that need sustained parallelism or exceed your context window, [agent teams](/en/agent-teams) give each worker its own independent context.

657 

658#### Chain subagents

659 

660For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.

661 

662```text theme={null}

663Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

664```

665 

666### Choose between subagents and main conversation

667 

668Use the **main conversation** when:

669 

670* The task needs frequent back-and-forth or iterative refinement

671* Multiple phases share significant context (planning → implementation → testing)

672* You're making a quick, targeted change

673* Latency matters. Subagents start fresh and may need time to gather context

674 

675Use **subagents** when:

676 

677* The task produces verbose output you don't need in your main context

678* You want to enforce specific tool restrictions or permissions

679* The work is self-contained and can return a summary

680 

681Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.

682 

683For 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.

684 

685<Note>

686 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.

687</Note>

688 

689### Manage subagent context

690 

691#### Resume subagents

692 

693Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it.

694 

695Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh.

696 

697When a subagent completes, Claude receives its agent ID. Claude uses the `SendMessage` tool with the agent's ID as the `to` field to resume it. The `SendMessage` tool is only available when [agent teams](/en/agent-teams) are enabled via `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`.

698 

699To resume a subagent, ask Claude to continue the previous work:

700 

701```text theme={null}

702Use the code-reviewer subagent to review the authentication module

703[Agent completes]

704 

705Continue that code review and now analyze the authorization logic

706[Claude resumes the subagent with full context from previous conversation]

707```

708 

709If a stopped subagent receives a `SendMessage`, it auto-resumes in the background without requiring a new `Agent` invocation.

710 

711You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`.

712 

713Subagent transcripts persist independently of the main conversation:

714 

715* **Main conversation compaction**: When the main conversation compacts, subagent transcripts are unaffected. They're stored in separate files.

716* **Session persistence**: Subagent transcripts persist within their session. You can [resume a subagent](#resume-subagents) after restarting Claude Code by resuming the same session.

717* **Automatic cleanup**: Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).

718 

719#### Auto-compaction

720 

721Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` to a lower percentage (for example, `50`). See [environment variables](/en/env-vars) for details.

722 

723Compaction events are logged in subagent transcript files:

724 

725```json theme={null}

726{

727 "type": "system",

728 "subtype": "compact_boundary",

729 "compactMetadata": {

730 "trigger": "auto",

731 "preTokens": 167189

732 }

733}

734```

735 

736The `preTokens` value shows how many tokens were used before compaction occurred.

737 

244## Example subagents738## Example subagents

245 739 

740These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.

741 

742<Tip>

743 **Best practices:**

744 

745 * **Design focused subagents:** each subagent should excel at one specific task

746 * **Write detailed descriptions:** Claude uses the description to decide when to delegate

747 * **Limit tool access:** grant only necessary permissions for security and focus

748 * **Check into version control:** share project subagents with your team

749</Tip>

750 

246### Code reviewer751### Code reviewer

247 752 

753A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output.

754 

248```markdown theme={null}755```markdown theme={null}

249---756---

250name: code-reviewer757name: code-reviewer


2613. Begin review immediately7683. Begin review immediately

262 769 

263Review checklist:770Review checklist:

264- Code is simple and readable771- Code is clear and readable

265- Functions and variables are well-named772- Functions and variables are well-named

266- No duplicated code773- No duplicated code

267- Proper error handling774- Proper error handling


280 787 

281### Debugger788### Debugger

282 789 

790A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification.

791 

283```markdown theme={null}792```markdown theme={null}

284---793---

285name: debugger794name: debugger


310- Testing approach819- Testing approach

311- Prevention recommendations820- Prevention recommendations

312 821 

313Focus on fixing the underlying issue, not just symptoms.822Focus on fixing the underlying issue, not the symptoms.

314```823```

315 824 

316### Data scientist825### Data scientist

317 826 

827A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets `model: sonnet` for more capable analysis.

828 

318```markdown theme={null}829```markdown theme={null}

319---830---

320name: data-scientist831name: data-scientist


348Always ensure queries are efficient and cost-effective.859Always ensure queries are efficient and cost-effective.

349```860```

350 861 

351## Best practices862### Database query validator

863 

864A subagent that allows Bash access but validates commands to permit only read-only SQL queries. This example shows how to use `PreToolUse` hooks for conditional validation when you need finer control than the `tools` field provides.

865 

866```markdown theme={null}

867---

868name: db-reader

869description: Execute read-only database queries. Use when analyzing data or generating reports.

870tools: Bash

871hooks:

872 PreToolUse:

873 - matcher: "Bash"

874 hooks:

875 - type: command

876 command: "./scripts/validate-readonly-query.sh"

877---

878 

879You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.

352 880 

353* **Start with Claude-generated agents**: We highly recommend generating your initial subagent with Claude and then iterating on it to make it personally yours. This approach gives you the best results - a solid foundation that you can customize to your specific needs.881When asked to analyze data:

8821. Identify which tables contain the relevant data

8832. Write efficient SELECT queries with appropriate filters

8843. Present results clearly with context

354 885 

355* **Design focused subagents**: Create subagents with single, clear responsibilities rather than trying to make one subagent do everything. This improves performance and makes subagents more predictable.886You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.

887```

356 888 

357* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform.889Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script [exits with code 2](/en/hooks#exit-code-2-behavior-per-event) to block execution and returns an error message to Claude via stderr.

358 890 

359* **Limit tool access**: Only grant tools that are necessary for the subagent's purpose. This improves security and helps the subagent focus on relevant actions.891Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:

360 892 

361* **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively.893```bash theme={null}

894#!/bin/bash

895# Blocks SQL write operations, allows SELECT queries

362 896 

363## Advanced usage897# Read JSON input from stdin

898INPUT=$(cat)

364 899 

365### Chaining subagents900# Extract the command field from tool_input using jq

901COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

366 902 

367For complex workflows, you can chain multiple subagents:903if [ -z "$COMMAND" ]; then

904 exit 0

905fi

368 906 

369```907# Block write operations (case-insensitive)

370> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them908if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then

909 echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2

910 exit 2

911fi

912 

913exit 0

371```914```

372 915 

373### Dynamic subagent selection916Make the script executable:

374 917 

375Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results.918```bash theme={null}

919chmod +x ./scripts/validate-readonly-query.sh

920```

376 921 

377## Performance considerations922The 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.

378 923 

379* **Context efficiency**: Agents help preserve main context, enabling longer overall sessions924## Next steps

380* **Latency**: Subagents start off with a clean slate each time they are invoked and may add latency as they gather context that they require to do their job effectively.

381 925 

382## Related documentation926Now that you understand subagents, explore these related features:

383 927 

384* [Plugins](/en/docs/claude-code/plugins) - Extend Claude Code with custom agents through plugins928* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects

385* [Slash commands](/en/docs/claude-code/slash-commands) - Learn about other built-in commands929* [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation

386* [Settings](/en/docs/claude-code/settings) - Configure Claude Code behavior930* [Use MCP servers](/en/mcp) to give subagents access to external tools and data

387* [Hooks](/en/docs/claude-code/hooks) - Automate workflows with event handlers

terminal-config.md +52 −19

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Optimize your terminal setup5# Optimize your terminal setup

2 6 

3> Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience.7> Claude Code works best when your terminal is properly configured. Follow these guidelines to optimize your experience.


6 10 

7Claude 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.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.

8 12 

9For additional customization of the Claude Code interface itself, you can configure a [custom status line](/en/docs/claude-code/statusline) to display contextual information like the current model, working directory, or git branch at the bottom of your terminal.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.

10 14 

11### Line breaks15### Line breaks

12 16 

13You have several options for entering linebreaks into Claude Code:17You have several options for entering line breaks into Claude Code:

14 18 

15* **Quick escape**: Type `\` followed by Enter to create a newline19* **Quick escape**: Type `\` followed by Enter to create a newline

16* **Keyboard shortcut**: Set up a keybinding to insert a newline20* **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 

24**Set up Shift+Enter for other terminals**

17 25 

18#### Set up Shift+Enter (VS Code or iTerm2):26Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter for VS Code, Alacritty, Zed, and Warp.

19 27 

20Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter.28<Note>

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>

21 31 

22#### Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app):32**Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app)**

23 33 

24**For Mac Terminal.app:**34**For Mac Terminal.app:**

25 35 

261. Open Settings → Profiles → Keyboard361. Open Settings → Profiles → Keyboard

272. Check "Use Option as Meta Key"372. Check "Use Option as Meta Key"

28 38 

29**For iTerm2 and VS Code terminal:**39**For iTerm2:**

30 40 

311. Open Settings → Profiles → Keys411. Open Settings → Profiles → Keys

322. Under General, set Left/Right Option key to "Esc+"422. Under General, set Left/Right Option key to "Esc+"

33 43 

44**For VS Code terminal:**

45 

46Set `"terminal.integrated.macOptionIsMeta": true` in VS Code settings.

47 

34### Notification setup48### Notification setup

35 49 

36Never miss when Claude completes a task with proper notification configuration:50When 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).

51 

52#### Terminal notifications

53 

54Kitty and Ghostty support desktop notifications without additional configuration. iTerm 2 requires setup:

37 55 

38#### iTerm 2 system notifications561. Open iTerm 2 Settings → Profiles → Terminal

572. Enable "Notification Center Alerts"

583. Click "Filter Alerts" and check "Send escape sequence-generated alerts"

39 59 

40For iTerm 2 alerts when tasks complete:60If notifications aren't appearing, verify that your terminal app has notification permissions in your OS settings.

41 61 

421. Open iTerm 2 Preferences62When 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:

432. Navigate to Profiles → Terminal

443. Enable "Silence bell" and Filter Alerts → "Send escape sequence-generated alerts"

454. Set your preferred notification delay

46 63 

47Note that these notifications are specific to iTerm 2 and not available in the default macOS Terminal.64```

65set -g allow-passthrough on

66```

48 67 

49#### Custom notification hooks68Without this setting, tmux intercepts the escape sequences and they do not reach the terminal application.

50 69 

51For advanced notification handling, you can create [notification hooks](/en/docs/claude-code/hooks#notification) to run your own logic.70Other terminals, including the default macOS Terminal, do not support native notifications. Use [notification hooks](/en/hooks#notification) instead.

71 

72#### Notification hooks

73 

74To 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.

75 

76### Reduce flicker and memory usage

77 

78If 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`.

52 79 

53### Handling large inputs80### Handling large inputs

54 81 


60 87 

61### Vim Mode88### Vim Mode

62 89 

63Claude Code supports a subset of Vim keybindings that can be enabled with `/vim` or configured via `/config`.90Claude Code supports a subset of Vim keybindings that can be enabled with `/vim` or configured via `/config`. 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`.

64 91 

65The supported subset includes:92The supported subset includes:

66 93 

67* Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT)94* Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT)

68* Navigation: `h`/`j`/`k`/`l`, `w`/`e`/`b`, `0`/`$`/`^`, `gg`/`G`95* Navigation: `h`/`j`/`k`/`l`, `w`/`e`/`b`, `0`/`$`/`^`, `gg`/`G`, `f`/`F`/`t`/`T` with `;`/`,` repeat

69* Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat)96* Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat)

97* Yank/paste: `yy`/`Y`, `yw`/`ye`/`yb`, `p`/`P`

98* Text objects: `iw`/`aw`, `iW`/`aW`, `i"`/`a"`, `i'`/`a'`, `i(`/`a(`, `i[`/`a[`, `i{`/`a{`

99* Indentation: `>>`/`<<`

100* Line operations: `J` (join lines)

101 

102See [Interactive mode](/en/interactive-mode#vim-editor-mode) for the complete reference.

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Enterprise deployment overview5# Enterprise deployment overview

2 6 

3> Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements.7> Learn how Claude Code can integrate with various third-party services and infrastructure to meet enterprise deployment requirements.

4 8 

5This page provides an overview of available deployment options and helps you choose the right configuration for your organization.9Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration.

10 

11## Compare deployment options

12 

13For most organizations, Claude for Teams or Claude for Enterprise provides the best experience. Team members get access to both Claude Code and Claude on the web with a single subscription, centralized billing, and no infrastructure setup required.

14 

15**Claude for Teams** is self-service and includes collaboration features, admin tools, and billing management. Best for smaller teams that need to get started quickly.

16 

17**Claude for Enterprise** adds SSO and domain capture, role-based permissions, compliance API access, and managed policy settings for deploying organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.

6 18 

7## Provider comparison19Learn more about [Team plans](https://support.claude.com/en/articles/9266767-what-is-the-team-plan) and [Enterprise plans](https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan).

20 

21If your organization has specific infrastructure requirements, compare the options below:

8 22 

9<table>23<table>

10 <thead>24 <thead>

11 <tr>25 <tr>

12 <th>Feature</th>26 <th>Feature</th>

13 <th>Anthropic</th>27 <th>Claude for Teams/Enterprise</th>

28 <th>Anthropic Console</th>

14 <th>Amazon Bedrock</th>29 <th>Amazon Bedrock</th>

15 <th>Google Vertex AI</th>30 <th>Google Vertex AI</th>

31 <th>Microsoft Foundry</th>

16 </tr>32 </tr>

17 </thead>33 </thead>

18 34 

19 <tbody>35 <tbody>

36 <tr>

37 <td>Best for</td>

38 <td>Most organizations (recommended)</td>

39 <td>Individual developers</td>

40 <td>AWS-native deployments</td>

41 <td>GCP-native deployments</td>

42 <td>Azure-native deployments</td>

43 </tr>

44 

45 <tr>

46 <td>Billing</td>

47 <td><strong>Teams:</strong> \$150/seat (Premium) with PAYG available<br /><strong>Enterprise:</strong> <a href="https://claude.com/contact-sales?utm_source=claude_code&utm_medium=docs&utm_content=third_party_enterprise">Contact Sales</a></td>

48 <td>PAYG</td>

49 <td>PAYG through AWS</td>

50 <td>PAYG through GCP</td>

51 <td>PAYG through Azure</td>

52 </tr>

53 

20 <tr>54 <tr>

21 <td>Regions</td>55 <td>Regions</td>

22 <td>Supported [countries](https://www.anthropic.com/supported-countries)</td>56 <td>Supported [countries](https://www.anthropic.com/supported-countries)</td>

57 <td>Supported [countries](https://www.anthropic.com/supported-countries)</td>

23 <td>Multiple AWS [regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)</td>58 <td>Multiple AWS [regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)</td>

24 <td>Multiple GCP [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations)</td>59 <td>Multiple GCP [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations)</td>

60 <td>Multiple Azure [regions](https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/)</td>

25 </tr>61 </tr>

26 62 

27 <tr>63 <tr>


29 <td>Enabled by default</td>65 <td>Enabled by default</td>

30 <td>Enabled by default</td>66 <td>Enabled by default</td>

31 <td>Enabled by default</td>67 <td>Enabled by default</td>

68 <td>Enabled by default</td>

69 <td>Enabled by default</td>

32 </tr>70 </tr>

33 71 

34 <tr>72 <tr>

35 <td>Authentication</td>73 <td>Authentication</td>

74 <td>Claude.ai SSO or email</td>

36 <td>API key</td>75 <td>API key</td>

37 <td>AWS credentials (IAM)</td>76 <td>API key or AWS credentials</td>

38 <td>GCP credentials (OAuth/Service Account)</td>77 <td>GCP credentials</td>

78 <td>API key or Microsoft Entra ID</td>

39 </tr>79 </tr>

40 80 

41 <tr>81 <tr>

42 <td>Cost tracking</td>82 <td>Cost tracking</td>

43 <td>Dashboard</td>83 <td>Usage dashboard</td>

84 <td>Usage dashboard</td>

44 <td>AWS Cost Explorer</td>85 <td>AWS Cost Explorer</td>

45 <td>GCP Billing</td>86 <td>GCP Billing</td>

87 <td>Azure Cost Management</td>

88 </tr>

89 

90 <tr>

91 <td>Includes Claude on web</td>

92 <td>Yes</td>

93 <td>No</td>

94 <td>No</td>

95 <td>No</td>

96 <td>No</td>

46 </tr>97 </tr>

47 98 

48 <tr>99 <tr>

49 <td>Enterprise features</td>100 <td>Enterprise features</td>

50 <td>Teams, usage monitoring</td>101 <td>Team management, SSO, usage monitoring</td>

102 <td>None</td>

51 <td>IAM policies, CloudTrail</td>103 <td>IAM policies, CloudTrail</td>

52 <td>IAM roles, Cloud Audit Logs</td>104 <td>IAM roles, Cloud Audit Logs</td>

105 <td>RBAC policies, Azure Monitor</td>

53 </tr>106 </tr>

54 </tbody>107 </tbody>

55</table>108</table>

56 109 

57## Cloud providers110Select a deployment option to view setup instructions:

58 111 

59<CardGroup cols={2}>112* [Claude for Teams or Enterprise](/en/authentication#claude-for-teams-or-enterprise)

60 <Card title="Amazon Bedrock" icon="aws" href="/en/docs/claude-code/amazon-bedrock">113* [Anthropic Console](/en/authentication#claude-console-authentication)

61 Use Claude models through AWS infrastructure with IAM-based authentication and AWS-native monitoring114* [Amazon Bedrock](/en/amazon-bedrock)

62 </Card>115* [Google Vertex AI](/en/google-vertex-ai)

116* [Microsoft Foundry](/en/microsoft-foundry)

63 117 

64 <Card title="Google Vertex AI" icon="google" href="/en/docs/claude-code/google-vertex-ai">118## Configure proxies and gateways

65 Access Claude models via Google Cloud Platform with enterprise-grade security and compliance

66 </Card>

67</CardGroup>

68 119 

69## Corporate infrastructure120Most organizations can use a cloud provider directly without additional configuration. However, you may need to configure a corporate proxy or LLM gateway if your organization has specific network or management requirements. These are different configurations that can be used together:

70 121 

71<CardGroup cols={2}>122* **Corporate proxy**: Routes traffic through an HTTP/HTTPS proxy. Use this if your organization requires all outbound traffic to pass through a proxy server for security monitoring, compliance, or network policy enforcement. Configure with the `HTTPS_PROXY` or `HTTP_PROXY` environment variables. Learn more in [Enterprise network configuration](/en/network-config).

72 <Card title="Enterprise Network" icon="shield" href="/en/docs/claude-code/network-config">123* **LLM Gateway**: A service that sits between Claude Code and the cloud provider to handle authentication and routing. Use this if you need centralized usage tracking across teams, custom rate limiting or budgets, or centralized authentication management. Configure with the `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, or `ANTHROPIC_VERTEX_BASE_URL` environment variables. Learn more in [LLM gateway configuration](/en/llm-gateway).

73 Configure Claude Code to work with your organization's proxy servers and SSL/TLS requirements

74 </Card>

75 124 

76 <Card title="LLM Gateway" icon="server" href="/en/docs/claude-code/llm-gateway">125The following examples show the environment variables to set in your shell or shell profile (`.bashrc`, `.zshrc`). See [Settings](/en/settings) for other configuration methods.

77 Deploy centralized model access with usage tracking, budgeting, and audit logging

78 </Card>

79</CardGroup>

80 126 

81## Configuration overview127### Amazon Bedrock

82 128 

83Claude Code supports flexible configuration options that allow you to combine different providers and infrastructure:129<Tabs>

130 <Tab title="Corporate proxy">

131 Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/en/env-vars):

84 132 

85<Note>133 ```bash theme={null}

86 Understand the difference between:134 # Enable Bedrock

135 export CLAUDE_CODE_USE_BEDROCK=1

136 export AWS_REGION=us-east-1

87 137 

88 * **Corporate proxy**: An HTTP/HTTPS proxy for routing traffic (set via `HTTPS_PROXY` or `HTTP_PROXY`)138 # Configure corporate proxy

89 * **LLM Gateway**: A service that handles authentication and provides provider-compatible endpoints (set via `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, or `ANTHROPIC_VERTEX_BASE_URL`)139 export HTTPS_PROXY='https://proxy.example.com:8080'

140 ```

141 </Tab>

90 142 

91 Both configurations can be used in tandem.143 <Tab title="LLM Gateway">

92</Note>144 Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/en/env-vars):

93 145 

94### Using Bedrock with corporate proxy146 ```bash theme={null}

147 # Enable Bedrock

148 export CLAUDE_CODE_USE_BEDROCK=1

95 149 

96Route Bedrock traffic through a corporate HTTP/HTTPS proxy:150 # Configure LLM gateway

151 export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'

152 export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth

153 ```

154 </Tab>

155</Tabs>

97 156 

98```bash theme={null}157### Microsoft Foundry

99# Enable Bedrock

100export CLAUDE_CODE_USE_BEDROCK=1

101export AWS_REGION=us-east-1

102 158 

103# Configure corporate proxy159<Tabs>

104export HTTPS_PROXY='https://proxy.example.com:8080'160 <Tab title="Corporate proxy">

105```161 Route Foundry traffic through your corporate proxy by setting the following [environment variables](/en/env-vars):

106 162 

107### Using Bedrock with LLM Gateway163 ```bash theme={null}

164 # Enable Microsoft Foundry

165 export CLAUDE_CODE_USE_FOUNDRY=1

166 export ANTHROPIC_FOUNDRY_RESOURCE=your-resource

167 export ANTHROPIC_FOUNDRY_API_KEY=your-api-key # Or omit for Entra ID auth

108 168 

109Use a gateway service that provides Bedrock-compatible endpoints:169 # Configure corporate proxy

170 export HTTPS_PROXY='https://proxy.example.com:8080'

171 ```

172 </Tab>

110 173 

111```bash theme={null}174 <Tab title="LLM Gateway">

112# Enable Bedrock175 Route Foundry traffic through your LLM gateway by setting the following [environment variables](/en/env-vars):

113export CLAUDE_CODE_USE_BEDROCK=1

114 176 

115# Configure LLM gateway177 ```bash theme={null}

116export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'178 # Enable Microsoft Foundry

117export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth179 export CLAUDE_CODE_USE_FOUNDRY=1

118```

119 180 

120### Using Vertex AI with corporate proxy181 # Configure LLM gateway

182 export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com'

183 export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 # If gateway handles Azure auth

184 ```

185 </Tab>

186</Tabs>

121 187 

122Route Vertex AI traffic through a corporate HTTP/HTTPS proxy:188### Google Vertex AI

123 189 

124```bash theme={null}190<Tabs>

125# Enable Vertex191 <Tab title="Corporate proxy">

126export CLAUDE_CODE_USE_VERTEX=1192 Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/en/env-vars):

127export CLOUD_ML_REGION=us-east5

128export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

129 193 

130# Configure corporate proxy194 ```bash theme={null}

131export HTTPS_PROXY='https://proxy.example.com:8080'195 # Enable Vertex

132```196 export CLAUDE_CODE_USE_VERTEX=1

197 export CLOUD_ML_REGION=us-east5

198 export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

133 199 

134### Using Vertex AI with LLM Gateway200 # Configure corporate proxy

201 export HTTPS_PROXY='https://proxy.example.com:8080'

202 ```

203 </Tab>

135 204 

136Combine Google Vertex AI models with an LLM gateway for centralized management:205 <Tab title="LLM Gateway">

206 Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/en/env-vars):

137 207 

138```bash theme={null}208 ```bash theme={null}

139# Enable Vertex209 # Enable Vertex

140export CLAUDE_CODE_USE_VERTEX=1210 export CLAUDE_CODE_USE_VERTEX=1

141 211 

142# Configure LLM gateway212 # Configure LLM gateway

143export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'213 export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'

144export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth214 export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth

145```215 ```

216 </Tab>

217</Tabs>

146 218 

147### Authentication configuration219<Tip>

148 220 Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly.

149Claude Code uses the `ANTHROPIC_AUTH_TOKEN` for the `Authorization` header when needed. The `SKIP_AUTH` flags (`CLAUDE_CODE_SKIP_BEDROCK_AUTH`, `CLAUDE_CODE_SKIP_VERTEX_AUTH`) are used in LLM gateway scenarios where the gateway handles provider authentication.221</Tip>

150 

151## Choosing the right deployment configuration

152 

153Consider these factors when selecting your deployment approach:

154 

155### Direct provider access

156 

157Best for organizations that:

158 

159* Want the simplest setup

160* Have existing AWS or GCP infrastructure

161* Need provider-native monitoring and compliance

162 

163### Corporate proxy

164 

165Best for organizations that:

166 

167* Have existing corporate proxy requirements

168* Need traffic monitoring and compliance

169* Must route all traffic through specific network paths

170 

171### LLM Gateway

172 

173Best for organizations that:

174 

175* Need usage tracking across teams

176* Want to dynamically switch between models

177* Require custom rate limiting or budgets

178* Need centralized authentication management

179 

180## Debugging

181 

182When debugging your deployment:

183 

184* Use the `claude /status` [slash command](/en/docs/claude-code/slash-commands). This command provides observability into any applied authentication, proxy, and URL settings.

185* Set environment variable `export ANTHROPIC_LOG=debug` to log requests.

186 222 

187## Best practices for organizations223## Best practices for organizations

188 224 

189### 1. Invest in documentation and memory225### Invest in documentation and memory

190 226 

191We strongly recommend investing in documentation so that Claude Code understands your codebase. Organizations can deploy CLAUDE.md files at multiple levels:227We strongly recommend investing in documentation so that Claude Code understands your codebase. Organizations can deploy CLAUDE.md files at multiple levels:

192 228 

193* **Organization-wide**: Deploy to system directories like `/Library/Application Support/ClaudeCode/CLAUDE.md` (macOS) for company-wide standards229* **Organization-wide**: Deploy to system directories like `/Library/Application Support/ClaudeCode/CLAUDE.md` (macOS) for company-wide standards

194* **Repository-level**: Create `CLAUDE.md` files in repository roots containing project architecture, build commands, and contribution guidelines. Check these into source control so all users benefit230* **Repository-level**: Create `CLAUDE.md` files in repository roots containing project architecture, build commands, and contribution guidelines. Check these into source control so all users benefit

195 231 

196 [Learn more](/en/docs/claude-code/memory).232Learn more in [Memory and CLAUDE.md files](/en/memory).

197 233 

198### 2. Simplify deployment234### Simplify deployment

199 235 

200If you have a custom development environment, we find that creating a "one click" way to install Claude Code is key to growing adoption across an organization.236If you have a custom development environment, we find that creating a "one click" way to install Claude Code is key to growing adoption across an organization.

201 237 

202### 3. Start with guided usage238### Start with guided usage

203 239 

204Encourage new users to try Claude Code for codebase Q\&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude's suggestions and give feedback if it's off-track. Over time, as users understand this new paradigm better, then they'll be more effective at letting Claude Code run more agentically.240Encourage new users to try Claude Code for codebase Q\&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude's suggestions and give feedback if it's off-track. Over time, as users understand this new paradigm better, then they'll be more effective at letting Claude Code run more agentically.

205 241 

206### 4. Configure security policies242### Pin model versions for cloud providers

243 

244If you deploy through [Bedrock](/en/amazon-bedrock), [Vertex AI](/en/google-vertex-ai), or [Foundry](/en/microsoft-foundry), pin specific model versions using `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, and `ANTHROPIC_DEFAULT_HAIKU_MODEL`. Without pinning, Claude Code aliases resolve to the latest version, which can break users when Anthropic releases a new model that isn't yet enabled in your account. See [Model configuration](/en/model-config#pin-models-for-third-party-deployments) for details.

207 245 

208Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](/en/docs/claude-code/security).246### Configure security policies

209 247 

210### 5. Leverage MCP for integrations248Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](/en/security).

211 249 

212MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](/en/docs/claude-code/mcp).250### Leverage MCP for integrations

213 251 

214At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do!252MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](/en/mcp).

253 

254At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do.

215 255 

216## Next steps256## Next steps

217 257 

218* [Set up Amazon Bedrock](/en/docs/claude-code/amazon-bedrock) for AWS-native deployment258Once you've chosen a deployment option and configured access for your team:

219* [Configure Google Vertex AI](/en/docs/claude-code/google-vertex-ai) for GCP deployment259 

220* [Configure Enterprise Network](/en/docs/claude-code/network-config) for network requirements2601. **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/en/setup) and authenticate with their credentials.

221* [Deploy LLM Gateway](/en/docs/claude-code/llm-gateway) for enterprise management2612. **Set up shared configuration**: Create a [CLAUDE.md file](/en/memory) in your repositories to help Claude Code understand your codebase and coding standards.

222* [Settings](/en/docs/claude-code/settings) for configuration options and environment variables2623. **Configure permissions**: Review [security settings](/en/security) to define what Claude Code can and cannot do in your environment.

tools-reference.md +125 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Tools reference

6 

7> Complete reference for the tools Claude Code can use, including permission requirements.

8 

9Claude Code has access to a set of built-in tools that help it understand and modify your codebase. The tool names are the exact strings you use in [permission rules](/en/permissions#tool-specific-permission-rules), [subagent tool lists](/en/sub-agents), and [hook matchers](/en/hooks). To disable a tool entirely, add its name to the `deny` array in your [permission settings](/en/permissions#tool-specific-permission-rules).

10 

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 

13| Tool | Description | Permission Required |

14| :--------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |

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 |

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 |

19| `CronDelete` | Cancels a scheduled task by ID | No |

20| `CronList` | Lists all scheduled tasks in the session | No |

21| `Edit` | Makes targeted edits to specific files | Yes |

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 | No |

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 |

26| `Glob` | Finds files based on pattern matching | No |

27| `Grep` | Searches for patterns in file contents | 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 |

30| `NotebookEdit` | Modifies Jupyter notebook cells | Yes |

31| `PowerShell` | Executes PowerShell commands on Windows. Opt-in preview. See [PowerShell tool](#powershell-tool) | Yes |

32| `Read` | Reads the contents of files | No |

33| `ReadMcpResourceTool` | Reads a specific MCP resource by URI | No |

34| `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| `Skill` | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

36| `TaskCreate` | Creates a new task in the task list | No |

37| `TaskGet` | Retrieves full details for a specific task | No |

38| `TaskList` | Lists all tasks with their current status | No |

39| `TaskOutput` | (Deprecated) Retrieves output from a background task. Prefer `Read` on the task's output file path | No |

40| `TaskStop` | Kills a running background task by ID | No |

41| `TaskUpdate` | Updates task status, dependencies, details, or deletes tasks | No |

42| `TeamCreate` | Creates an [agent team](/en/agent-teams) with multiple teammates. Only available when `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set | No |

43| `TeamDelete` | Disbands an agent team and cleans up teammate processes. Only available when `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set | No |

44| `TodoWrite` | Manages the session task checklist. Available in non-interactive mode and the [Agent SDK](/en/headless); interactive sessions use TaskCreate, TaskGet, TaskList, and TaskUpdate instead | No |

45| `ToolSearch` | Searches for and loads deferred tools when [tool search](/en/mcp#scale-with-mcp-tool-search) is enabled | No |

46| `WebFetch` | Fetches content from a specified URL | Yes |

47| `WebSearch` | Performs web searches | Yes |

48| `Write` | Creates or overwrites files | Yes |

49 

50Permission rules can be configured using `/permissions` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/permissions#tool-specific-permission-rules).

51 

52## Bash tool behavior

53 

54The Bash tool runs each command in a separate process with the following persistence behavior:

55 

56* Working directory persists across commands. Set `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1` to reset to the project directory after each command.

57* Environment variables do not persist. An `export` in one command will not be available in the next.

58 

59Activate your virtualenv or conda environment before launching Claude Code. To make environment variables persist across Bash commands, set [`CLAUDE_ENV_FILE`](/en/env-vars) to a shell script before launching Claude Code, or use a [SessionStart hook](/en/hooks#persist-environment-variables) to populate it dynamically.

60 

61## LSP tool behavior

62 

63The LSP tool gives Claude code intelligence from a running language server. After each file edit, it automatically reports type errors and warnings so Claude can fix issues without a separate build step. Claude can also call it directly to navigate code:

64 

65* Jump to a symbol's definition

66* Find all references to a symbol

67* Get type information at a position

68* List symbols in a file or workspace

69* Find implementations of an interface

70* Trace call hierarchies

71 

72The tool is inactive until you install a [code intelligence plugin](/en/discover-plugins#code-intelligence) for your language. The plugin bundles the language server configuration, and you install the server binary separately.

73 

74## PowerShell tool

75 

76On Windows, Claude Code can run PowerShell commands natively instead of routing through Git Bash. This is an opt-in preview.

77 

78### Enable the PowerShell tool

79 

80Set `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` in your environment or in `settings.json`:

81 

82```json theme={null}

83{

84 "env": {

85 "CLAUDE_CODE_USE_POWERSHELL_TOOL": "1"

86 }

87}

88```

89 

90Claude 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.

91 

92### Shell selection in settings, hooks, and skills

93 

94Three additional settings control where PowerShell is used:

95 

96* `"defaultShell": "powershell"` in [`settings.json`](/en/settings#available-settings): routes interactive `!` commands through PowerShell. Requires the PowerShell tool to be enabled.

97* `"shell": "powershell"` on individual [command hooks](/en/hooks#command-hook-fields): runs that hook in PowerShell. Hooks spawn PowerShell directly, so this works regardless of `CLAUDE_CODE_USE_POWERSHELL_TOOL`.

98* `shell: powershell` in [skill frontmatter](/en/skills#frontmatter-reference): runs `` !`command` `` blocks in PowerShell. Requires the PowerShell tool to be enabled.

99 

100### Preview limitations

101 

102The PowerShell tool has the following known limitations during the preview:

103 

104* Auto mode does not work with the PowerShell tool yet

105* PowerShell profiles are not loaded

106* Sandboxing is not supported

107* Only supported on native Windows, not WSL

108* Git Bash is still required to start Claude Code

109 

110## Check which tools are available

111 

112Your exact tool set depends on your provider, platform, and settings. To check what's loaded in a running session, ask Claude directly:

113 

114```text theme={null}

115What tools do you have access to?

116```

117 

118Claude gives a conversational summary. For exact MCP tool names, run `/mcp`.

119 

120## See also

121 

122* [MCP servers](/en/mcp): add custom tools by connecting external servers

123* [Permissions](/en/permissions): permission system, rule syntax, and tool-specific patterns

124* [Subagents](/en/sub-agents): configure tool access for subagents

125* [Hooks](/en/hooks-guide): run custom commands before or after tool execution

troubleshooting.md +659 −89

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# Troubleshooting5# Troubleshooting

2 6 

3> Discover solutions to common issues with Claude Code installation and usage.7> Discover solutions to common issues with Claude Code installation and usage.

4 8 

9## Troubleshoot installation issues

10 

11<Tip>

12 If you'd rather skip the terminal entirely, the [Claude Code Desktop app](/en/desktop-quickstart) lets you install and use Claude Code through a graphical interface. Download it for [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) or [Windows](https://claude.com/download?utm_source=claude_code\&utm_medium=docs) and start coding without any command-line setup.

13</Tip>

14 

15Find the error message or symptom you're seeing:

16 

17| What you see | Solution |

18| :---------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------- |

19| `command not found: claude` or `'claude' is not recognized` | [Fix your PATH](#command-not-found-claude-after-installation) |

20| `syntax error near unexpected token '<'` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

21| `curl: (56) Failure writing output to destination` | [Download script first, then run it](#curl-56-failure-writing-output-to-destination) |

22| `Killed` during install on Linux | [Add swap space for low-memory servers](#install-killed-on-low-memory-linux-servers) |

23| `TLS connect error` or `SSL/TLS secure channel` | [Update CA certificates](#tls-or-ssl-connection-errors) |

24| `Failed to fetch version` or can't reach download server | [Check network and proxy settings](#check-network-connectivity) |

25| `irm is not recognized` or `&& is not valid` | [Use the right command for your shell](#windows-irm-or--not-recognized) |

26| `Claude Code on Windows requires git-bash` | [Install or configure Git Bash](#windows-claude-code-on-windows-requires-git-bash) |

27| `Error loading shared library` | [Wrong binary variant for your system](#linux-wrong-binary-variant-installed-muslglibc-mismatch) |

28| `Illegal instruction` on Linux | [Architecture mismatch](#illegal-instruction-on-linux) |

29| `dyld: cannot load` or `Abort trap` on macOS | [Binary incompatibility](#dyld-cannot-load-on-macos) |

30| `Invoke-Expression: Missing argument in parameter list` | [Install script returns HTML](#install-script-returns-html-instead-of-a-shell-script) |

31| `App unavailable in region` | Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries). |

32| `unable to get local issuer certificate` | [Configure corporate CA certificates](#tls-or-ssl-connection-errors) |

33| `OAuth error` or `403 Forbidden` | [Fix authentication](#authentication-issues) |

34 

35If your issue isn't listed, work through these diagnostic steps.

36 

37## Debug installation problems

38 

39### Check network connectivity

40 

41The installer downloads from `storage.googleapis.com`. Verify you can reach it:

42 

43```bash theme={null}

44curl -sI https://storage.googleapis.com

45```

46 

47If this fails, your network may be blocking the connection. Common causes:

48 

49* Corporate firewalls or proxies blocking Google Cloud Storage

50* Regional network restrictions: try a VPN or alternative network

51* TLS/SSL issues: update your system's CA certificates, or check if `HTTPS_PROXY` is configured

52 

53If you're behind a corporate proxy, set `HTTPS_PROXY` and `HTTP_PROXY` to your proxy's address before installing. Ask your IT team for the proxy URL if you don't know it, or check your browser's proxy settings.

54 

55This example sets both proxy variables, then runs the installer through your proxy:

56 

57```bash theme={null}

58export HTTP_PROXY=http://proxy.example.com:8080

59export HTTPS_PROXY=http://proxy.example.com:8080

60curl -fsSL https://claude.ai/install.sh | bash

61```

62 

63### Verify your PATH

64 

65If installation succeeded but you get a `command not found` or `not recognized` error when running `claude`, the install directory isn't in your PATH. Your shell searches for programs in directories listed in PATH, and the installer places `claude` at `~/.local/bin/claude` on macOS/Linux or `%USERPROFILE%\.local\bin\claude.exe` on Windows.

66 

67Check if the install directory is in your PATH by listing your PATH entries and filtering for `local/bin`:

68 

69<Tabs>

70 <Tab title="macOS/Linux">

71 ```bash theme={null}

72 echo $PATH | tr ':' '\n' | grep local/bin

73 ```

74 

75 If there's no output, the directory is missing. Add it to your shell configuration:

76 

77 ```bash theme={null}

78 # Zsh (macOS default)

79 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

80 source ~/.zshrc

81 

82 # Bash (Linux default)

83 echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

84 source ~/.bashrc

85 ```

86 

87 Alternatively, close and reopen your terminal.

88 

89 Verify the fix worked:

90 

91 ```bash theme={null}

92 claude --version

93 ```

94 </Tab>

95 

96 <Tab title="Windows PowerShell">

97 ```powershell theme={null}

98 $env:PATH -split ';' | Select-String 'local\\bin'

99 ```

100 

101 If there's no output, add the install directory to your User PATH:

102 

103 ```powershell theme={null}

104 $currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')

105 [Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User')

106 ```

107 

108 Restart your terminal for the change to take effect.

109 

110 Verify the fix worked:

111 

112 ```powershell theme={null}

113 claude --version

114 ```

115 </Tab>

116 

117 <Tab title="Windows CMD">

118 ```batch theme={null}

119 echo %PATH% | findstr /i "local\bin"

120 ```

121 

122 If there's no output, open System Settings, go to Environment Variables, and add `%USERPROFILE%\.local\bin` to your User PATH variable. Restart your terminal.

123 

124 Verify the fix worked:

125 

126 ```batch theme={null}

127 claude --version

128 ```

129 </Tab>

130</Tabs>

131 

132### Check for conflicting installations

133 

134Multiple Claude Code installations can cause version mismatches or unexpected behavior. Check what's installed:

135 

136<Tabs>

137 <Tab title="macOS/Linux">

138 List all `claude` binaries found in your PATH:

139 

140 ```bash theme={null}

141 which -a claude

142 ```

143 

144 Check whether the native installer and npm versions are present:

145 

146 ```bash theme={null}

147 ls -la ~/.local/bin/claude

148 ```

149 

150 ```bash theme={null}

151 ls -la ~/.claude/local/

152 ```

153 

154 ```bash theme={null}

155 npm -g ls @anthropic-ai/claude-code 2>/dev/null

156 ```

157 </Tab>

158 

159 <Tab title="Windows PowerShell">

160 ```powershell theme={null}

161 where.exe claude

162 Test-Path "$env:LOCALAPPDATA\Claude Code\claude.exe"

163 ```

164 </Tab>

165</Tabs>

166 

167If you find multiple installations, keep only one. The native install at `~/.local/bin/claude` is recommended. Remove any extra installations:

168 

169Uninstall an npm global install:

170 

171```bash theme={null}

172npm uninstall -g @anthropic-ai/claude-code

173```

174 

175Remove a Homebrew install on macOS:

176 

177```bash theme={null}

178brew uninstall --cask claude-code

179```

180 

181### Check directory permissions

182 

183The installer needs write access to `~/.local/bin/` and `~/.claude/`. If installation fails with permission errors, check whether these directories are writable:

184 

185```bash theme={null}

186test -w ~/.local/bin && echo "writable" || echo "not writable"

187test -w ~/.claude && echo "writable" || echo "not writable"

188```

189 

190If either directory isn't writable, create the install directory and set your user as the owner:

191 

192```bash theme={null}

193sudo mkdir -p ~/.local/bin

194sudo chown -R $(whoami) ~/.local

195```

196 

197### Verify the binary works

198 

199If `claude` is installed but crashes or hangs on startup, run these checks to narrow down the cause.

200 

201Confirm the binary exists and is executable:

202 

203```bash theme={null}

204ls -la $(which claude)

205```

206 

207On Linux, check for missing shared libraries. If `ldd` shows missing libraries, you may need to install system packages. On Alpine Linux and other musl-based distributions, see [Alpine Linux setup](/en/setup#alpine-linux-and-musl-based-distributions).

208 

209```bash theme={null}

210ldd $(which claude) | grep "not found"

211```

212 

213Run a quick sanity check that the binary can execute:

214 

215```bash theme={null}

216claude --version

217```

218 

5## Common installation issues219## Common installation issues

6 220 

221These are the most frequently encountered installation problems and their solutions.

222 

223### Install script returns HTML instead of a shell script

224 

225When running the install command, you may see one of these errors:

226 

227```text theme={null}

228bash: line 1: syntax error near unexpected token `<'

229bash: line 1: `<!DOCTYPE html>'

230```

231 

232On PowerShell, the same problem appears as:

233 

234```text theme={null}

235Invoke-Expression: Missing argument in parameter list.

236```

237 

238This means the install URL returned an HTML page instead of the install script. If the HTML page says "App unavailable in region," Claude Code is not available in your country. See [supported countries](https://www.anthropic.com/supported-countries).

239 

240Otherwise, this can happen due to network issues, regional routing, or a temporary service disruption.

241 

242**Solutions:**

243 

2441. **Use an alternative install method**:

245 

246 On macOS or Linux, install via Homebrew:

247 

248 ```bash theme={null}

249 brew install --cask claude-code

250 ```

251 

252 On Windows, install via WinGet:

253 

254 ```powershell theme={null}

255 winget install Anthropic.ClaudeCode

256 ```

257 

2582. **Retry after a few minutes**: the issue is often temporary. Wait and try the original command again.

259 

260### `command not found: claude` after installation

261 

262The install finished but `claude` doesn't work. The exact error varies by platform:

263 

264| Platform | Error message |

265| :---------- | :--------------------------------------------------------------------- |

266| macOS | `zsh: command not found: claude` |

267| Linux | `bash: claude: command not found` |

268| Windows CMD | `'claude' is not recognized as an internal or external command` |

269| PowerShell | `claude : The term 'claude' is not recognized as the name of a cmdlet` |

270 

271This means the install directory isn't in your shell's search path. See [Verify your PATH](#verify-your-path) for the fix on each platform.

272 

273### `curl: (56) Failure writing output to destination`

274 

275The `curl ... | bash` command downloads the script and passes it directly to Bash for execution using a pipe (`|`). This error means the connection broke before the script finished downloading. Common causes include network interruptions, the download being blocked mid-stream, or system resource limits.

276 

277**Solutions:**

278 

2791. **Check network stability**: Claude Code binaries are hosted on Google Cloud Storage. Test that you can reach it:

280 ```bash theme={null}

281 curl -fsSL https://storage.googleapis.com -o /dev/null

282 ```

283 If the command completes silently, your connection is fine and the issue is likely intermittent. Retry the install command. If you see an error, your network may be blocking the download.

284 

2852. **Try an alternative install method**:

286 

287 On macOS or Linux:

288 

289 ```bash theme={null}

290 brew install --cask claude-code

291 ```

292 

293 On Windows:

294 

295 ```powershell theme={null}

296 winget install Anthropic.ClaudeCode

297 ```

298 

299### TLS or SSL connection errors

300 

301Errors like `curl: (35) TLS connect error`, `schannel: next InitializeSecurityContext failed`, or PowerShell's `Could not establish trust relationship for the SSL/TLS secure channel` indicate TLS handshake failures.

302 

303**Solutions:**

304 

3051. **Update your system CA certificates**:

306 

307 On Ubuntu/Debian:

308 

309 ```bash theme={null}

310 sudo apt-get update && sudo apt-get install ca-certificates

311 ```

312 

313 On macOS via Homebrew:

314 

315 ```bash theme={null}

316 brew install ca-certificates

317 ```

318 

3192. **On Windows, enable TLS 1.2** in PowerShell before running the installer:

320 ```powershell theme={null}

321 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

322 irm https://claude.ai/install.ps1 | iex

323 ```

324 

3253. **Check for proxy or firewall interference**: corporate proxies that perform TLS inspection can cause these errors, including `unable to get local issuer certificate`. Set `NODE_EXTRA_CA_CERTS` to your corporate CA certificate bundle:

326 ```bash theme={null}

327 export NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem

328 ```

329 Ask your IT team for the certificate file if you don't have it. You can also try on a direct connection to confirm the proxy is the cause.

330 

331### `Failed to fetch version from storage.googleapis.com`

332 

333The installer couldn't reach the download server. This typically means `storage.googleapis.com` is blocked on your network.

334 

335**Solutions:**

336 

3371. **Test connectivity directly**:

338 ```bash theme={null}

339 curl -sI https://storage.googleapis.com

340 ```

341 

3422. **If behind a proxy**, set `HTTPS_PROXY` so the installer can route through it. See [proxy configuration](/en/network-config#proxy-configuration) for details.

343 ```bash theme={null}

344 export HTTPS_PROXY=http://proxy.example.com:8080

345 curl -fsSL https://claude.ai/install.sh | bash

346 ```

347 

3483. **If on a restricted network**, try a different network or VPN, or use an alternative install method:

349 

350 On macOS or Linux:

351 

352 ```bash theme={null}

353 brew install --cask claude-code

354 ```

355 

356 On Windows:

357 

358 ```powershell theme={null}

359 winget install Anthropic.ClaudeCode

360 ```

361 

362### Windows: `irm` or `&&` not recognized

363 

364If you see `'irm' is not recognized` or `The token '&&' is not valid`, you're running the wrong command for your shell.

365 

366* **`irm` not recognized**: you're in CMD, not PowerShell. You have two options:

367 

368 Open PowerShell by searching for "PowerShell" in the Start menu, then run the original install command:

369 

370 ```powershell theme={null}

371 irm https://claude.ai/install.ps1 | iex

372 ```

373 

374 Or stay in CMD and use the CMD installer instead:

375 

376 ```batch theme={null}

377 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

378 ```

379 

380* **`&&` not valid**: you're in PowerShell but ran the CMD installer command. Use the PowerShell installer:

381 ```powershell theme={null}

382 irm https://claude.ai/install.ps1 | iex

383 ```

384 

385### Install killed on low-memory Linux servers

386 

387If you see `Killed` during installation on a VPS or cloud instance:

388 

389```text theme={null}

390Setting up Claude Code...

391Installing Claude Code native build latest...

392bash: line 142: 34803 Killed "$binary_path" install ${TARGET:+"$TARGET"}

393```

394 

395The Linux OOM killer terminated the process because the system ran out of memory. Claude Code requires at least 4 GB of available RAM.

396 

397**Solutions:**

398 

3991. **Add swap space** if your server has limited RAM. Swap uses disk space as overflow memory, letting the install complete even with low physical RAM.

400 

401 Create a 2 GB swap file and enable it:

402 

403 ```bash theme={null}

404 sudo fallocate -l 2G /swapfile

405 sudo chmod 600 /swapfile

406 sudo mkswap /swapfile

407 sudo swapon /swapfile

408 ```

409 

410 Then retry the installation:

411 

412 ```bash theme={null}

413 curl -fsSL https://claude.ai/install.sh | bash

414 ```

415 

4162. **Close other processes** to free memory before installing.

417 

4183. **Use a larger instance** if possible. Claude Code requires at least 4 GB of RAM.

419 

420### Install hangs in Docker

421 

422When installing Claude Code in a Docker container, installing as root into `/` can cause hangs.

423 

424**Solutions:**

425 

4261. **Set a working directory** before running the installer. When run from `/`, the installer scans the entire filesystem, which causes excessive memory usage. Setting `WORKDIR` limits the scan to a small directory:

427 ```dockerfile theme={null}

428 WORKDIR /tmp

429 RUN curl -fsSL https://claude.ai/install.sh | bash

430 ```

431 

4322. **Increase Docker memory limits** if using Docker Desktop:

433 ```bash theme={null}

434 docker build --memory=4g .

435 ```

436 

437### Windows: Claude Desktop overrides `claude` CLI command

438 

439If you installed an older version of Claude Desktop, it may register a `Claude.exe` in the `WindowsApps` directory that takes PATH priority over Claude Code CLI. Running `claude` opens the Desktop app instead of the CLI.

440 

441Update Claude Desktop to the latest version to fix this issue.

442 

443### Windows: "Claude Code on Windows requires git-bash"

444 

445Claude Code on native Windows needs [Git for Windows](https://git-scm.com/downloads/win), which includes Git Bash.

446 

447**If Git is not installed**, download and install it from [git-scm.com/downloads/win](https://git-scm.com/downloads/win). During setup, select "Add to PATH." Restart your terminal after installing.

448 

449**If Git is already installed** but Claude Code still can't find it, set the path in your [settings.json file](/en/settings):

450 

451```json theme={null}

452{

453 "env": {

454 "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe"

455 }

456}

457```

458 

459If your Git is installed somewhere else, find the path by running `where.exe git` in PowerShell and use the `bin\bash.exe` path from that directory.

460 

461### Linux: wrong binary variant installed (musl/glibc mismatch)

462 

463If you see errors about missing shared libraries like `libstdc++.so.6` or `libgcc_s.so.1` after installation, the installer may have downloaded the wrong binary variant for your system.

464 

465```text theme={null}

466Error loading shared library libstdc++.so.6: No such file or directory

467```

468 

469This can happen on glibc-based systems that have musl cross-compilation packages installed, causing the installer to misdetect the system as musl.

470 

471**Solutions:**

472 

4731. **Check which libc your system uses**:

474 ```bash theme={null}

475 ldd /bin/ls | head -1

476 ```

477 If it shows `linux-vdso.so` or references to `/lib/x86_64-linux-gnu/`, you're on glibc. If it shows `musl`, you're on musl.

478 

4792. **If you're on glibc but got the musl binary**, remove the installation and reinstall. You can also manually download the correct binary from the GCS bucket at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json`. File a [GitHub issue](https://github.com/anthropics/claude-code/issues) with the output of `ldd /bin/ls` and `ls /lib/libc.musl*`.

480 

4813. **If you're actually on musl** (Alpine Linux), install the required packages:

482 ```bash theme={null}

483 apk add libgcc libstdc++ ripgrep

484 ```

485 

486### `Illegal instruction` on Linux

487 

488If the installer prints `Illegal instruction` instead of the OOM `Killed` message, the downloaded binary doesn't match your CPU architecture. This commonly happens on ARM servers that receive an x86 binary, or on older CPUs that lack required instruction sets.

489 

490```text theme={null}

491bash: line 142: 2238232 Illegal instruction "$binary_path" install ${TARGET:+"$TARGET"}

492```

493 

494**Solutions:**

495 

4961. **Verify your architecture**:

497 ```bash theme={null}

498 uname -m

499 ```

500 `x86_64` means 64-bit Intel/AMD, `aarch64` means ARM64. If the binary doesn't match, [file a GitHub issue](https://github.com/anthropics/claude-code/issues) with the output.

501 

5022. **Try an alternative install method** while the architecture issue is resolved:

503 ```bash theme={null}

504 brew install --cask claude-code

505 ```

506 

507### `dyld: cannot load` on macOS

508 

509If you see `dyld: cannot load` or `Abort trap: 6` during installation, the binary is incompatible with your macOS version or hardware.

510 

511```text theme={null}

512dyld: cannot load 'claude-2.1.42-darwin-x64' (load command 0x80000034 is unknown)

513Abort trap: 6

514```

515 

516**Solutions:**

517 

5181. **Check your macOS version**: Claude Code requires macOS 13.0 or later. Open the Apple menu and select About This Mac to check your version.

519 

5202. **Update macOS** if you're on an older version. The binary uses load commands that older macOS versions don't support.

521 

5223. **Try Homebrew** as an alternative install method:

523 ```bash theme={null}

524 brew install --cask claude-code

525 ```

526 

7### Windows installation issues: errors in WSL527### Windows installation issues: errors in WSL

8 528 

9You might encounter the following issues in WSL:529You might encounter the following issues in WSL:

10 530 

11**OS/platform detection issues**: If you receive an error during installation, WSL may be using Windows `npm`. Try:531**OS/platform detection issues**: if you receive an error during installation, WSL may be using Windows `npm`. Try:

12 532 

13* Run `npm config set os linux` before installation533* Run `npm config set os linux` before installation

14* Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check` (Do NOT use `sudo`)534* Install with `npm install -g @anthropic-ai/claude-code --force --no-os-check`. Do not use `sudo`.

15 535 

16**Node not found errors**: If you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).536**Node not found errors**: if you see `exec: node: not found` when running `claude`, your WSL environment may be using a Windows installation of Node.js. You can confirm this with `which npm` and `which node`, which should point to Linux paths starting with `/usr/` rather than `/mnt/c/`. To fix this, try installing Node via your Linux distribution's package manager or via [`nvm`](https://github.com/nvm-sh/nvm).

17 537 

18**nvm version conflicts**: If you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation.538**nvm version conflicts**: if you have nvm installed in both WSL and Windows, you may experience version conflicts when switching Node versions in WSL. This happens because WSL imports the Windows PATH by default, causing Windows nvm/npm to take priority over the WSL installation.

19 539 

20You can identify this issue by:540You can identify this issue by:

21 541 


50```570```

51 571 

52<Warning>572<Warning>

53 Avoid disabling Windows PATH importing (`appendWindowsPath = false`) as this breaks the ability to easily call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.573 Avoid disabling Windows PATH importing via `appendWindowsPath = false` as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.

54</Warning>574</Warning>

55 575 

56### Linux and Mac installation issues: permission or command not found errors576### WSL2 sandbox setup

57 577 

58When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.578[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:

59You may also encounter permission errors if your npm global prefix is not user writable (eg. `/usr`, or `/usr/local`).

60 579 

61#### Recommended solution: Native Claude Code installation580<Tabs>

581 <Tab title="Ubuntu/Debian">

582 ```bash theme={null}

583 sudo apt-get install bubblewrap socat

584 ```

585 </Tab>

586 

587 <Tab title="Fedora">

588 ```bash theme={null}

589 sudo dnf install bubblewrap socat

590 ```

591 </Tab>

592</Tabs>

62 593 

63Claude Code has a native installation that doesn't depend on npm or Node.js.594WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing.

64 595 

65<Note>596### Permission errors during installation

66 The native Claude Code installer is currently in beta.

67</Note>

68 597 

69Use the following command to run the native installer.598If the native installer fails with permission errors, the target directory may not be writable. See [Check directory permissions](#check-directory-permissions).

70 599 

71**macOS, Linux, WSL:**600If you previously installed with npm and are hitting npm-specific permission errors, switch to the native installer:

72 601 

73```bash theme={null}602```bash theme={null}

74# Install stable version (default)

75curl -fsSL https://claude.ai/install.sh | bash603curl -fsSL https://claude.ai/install.sh | bash

604```

76 605 

77# Install latest version606## Permissions and authentication

78curl -fsSL https://claude.ai/install.sh | bash -s latest

79 607 

80# Install specific version number608These sections address login failures, token issues, and permission prompt behavior.

81curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58

82```

83 609 

84**Windows PowerShell:**610### Repeated permission prompts

85 611 

86```powershell theme={null}612If you find yourself repeatedly approving the same commands, you can allow specific tools

87# Install stable version (default)613to run without approval using the `/permissions` command. See [Permissions docs](/en/permissions#manage-permissions).

88irm https://claude.ai/install.ps1 | iex

89 614 

90# Install latest version615### Authentication issues

91& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest

92 616 

93# Install specific version number617If you're experiencing authentication problems:

94& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58

95 618 

96```6191. Run `/logout` to sign out completely

6202. Close Claude Code

6213. Restart with `claude` and complete the authentication process again

97 622 

98This command installs the appropriate build of Claude Code for your operating system and architecture and adds a symlink to the installation at `~/.local/bin/claude`.623If the browser doesn't open automatically during login, press `c` to copy the OAuth URL to your clipboard, then paste it into your browser manually.

99 624 

100<Tip>625### OAuth error: Invalid code

101 Make sure that you have the installation directory in your system PATH.

102</Tip>

103 626 

104#### Alternative solution: Migrate to local installation627If you see `OAuth error: Invalid code. Please make sure the full code was copied`, the login code expired or was truncated during copy-paste.

105 628 

106Alternatively, if Claude Code will run, you can migrate to a local installation:629**Solutions:**

107 630 

108```bash theme={null}631* Press Enter to retry and complete the login quickly after the browser opens

109claude migrate-installer632* Type `c` to copy the full URL if the browser doesn't open automatically

110```633* If using a remote/SSH session, the browser may open on the wrong machine. Copy the URL displayed in the terminal and open it in your local browser instead.

634 

635### 403 Forbidden after login

111 636 

112This moves Claude Code to `~/.claude/local/` and sets up an alias in your shell configuration. No `sudo` is required for future updates.637If you see `API Error: 403 {"error":{"type":"forbidden","message":"Request not allowed"}}` after logging in:

113 638 

114After migration, restart your shell, and then verify your installation:639* **Claude Pro/Max users**: verify your subscription is active at [claude.ai/settings](https://claude.ai/settings)

640* **Console users**: confirm your account has the "Claude Code" or "Developer" role assigned by your admin

641* **Behind a proxy**: corporate proxies can interfere with API requests. See [network configuration](/en/network-config) for proxy setup.

115 642 

116On macOS/Linux/WSL:643### "This organization has been disabled" with an active subscription

644 

645If 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.

646 

647When `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.

648 

649To use your subscription instead, unset the environment variable and remove it from your shell profile:

117 650 

118```bash theme={null}651```bash theme={null}

119which claude # Should show an alias to ~/.claude/local/claude652unset ANTHROPIC_API_KEY

653claude

120```654```

121 655 

122On Windows:656Check `~/.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.

123 657 

124```powershell theme={null}658### OAuth login fails in WSL2

125where claude # Should show path to claude executable

126```

127 659 

128Verify installation:660Browser-based login in WSL2 may fail if WSL can't open your Windows browser. Set the `BROWSER` environment variable:

129 661 

130```bash theme={null}662```bash theme={null}

131claude doctor # Check installation health663export BROWSER="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe"

664claude

132```665```

133 666 

134## Permissions and authentication667Or copy the URL manually: when the login prompt appears, press `c` to copy the OAuth URL, then paste it into your Windows browser.

135 668 

136### Repeated permission prompts669### "Not logged in" or token expired

137 670 

138If you find yourself repeatedly approving the same commands, you can allow specific tools671If Claude Code prompts you to log in again after a session, your OAuth token may have expired.

139to run without approval using the `/permissions` command. See [Permissions docs](/en/docs/claude-code/iam#configuring-permissions).

140 672 

141### Authentication issues673Run `/login` to re-authenticate. If this happens frequently, check that your system clock is accurate, as token validation depends on correct timestamps.

142 674 

143If you're experiencing authentication problems:675## Configuration file locations

144 676 

1451. Run `/logout` to sign out completely677Claude Code stores configuration in several locations:

1462. Close Claude Code678 

1473. Restart with `claude` and complete the authentication process again679| File | Purpose |

680| :---------------------------- | :----------------------------------------------------------------------------------------------------- |

681| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |

682| `.claude/settings.json` | Project settings (checked into source control) |

683| `.claude/settings.local.json` | Local project settings (not committed) |

684| `~/.claude.json` | Global state (theme, OAuth, MCP servers) |

685| `.mcp.json` | Project MCP servers (checked into source control) |

686| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |

687| Managed settings | [Managed settings](/en/settings#settings-files) (server-managed, MDM/OS-level policies, or file-based) |

148 688 

149If problems persist, try:689On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`.

690 

691For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp).

692 

693### Resetting configuration

694 

695To reset Claude Code to default settings, you can remove the configuration files:

150 696 

151```bash theme={null}697```bash theme={null}

152rm -rf ~/.config/claude-code/auth.json698# Reset all user settings and state

153claude699rm ~/.claude.json

700rm -rf ~/.claude/

701 

702# Reset project-specific settings

703rm -rf .claude/

704rm .mcp.json

154```705```

155 706 

156This removes your stored authentication information and forces a clean login.707<Warning>

708 This will remove all your settings, MCP server configurations, and session history.

709</Warning>

157 710 

158## Performance and stability711## Performance and stability

159 712 

713These sections cover issues related to resource usage, responsiveness, and search behavior.

714 

160### High CPU or memory usage715### High CPU or memory usage

161 716 

162Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you're experiencing performance issues:717Claude Code is designed to work with most development environments, but may consume significant resources when processing large codebases. If you're experiencing performance issues:


174 729 

175### Search and discovery issues730### Search and discovery issues

176 731 

177If Search tool, `@file` mentions, custom agents, and custom slash commands aren't working, install system `ripgrep`:732If Search tool, `@file` mentions, custom agents, and custom skills aren't working, install system `ripgrep`:

178 733 

179```bash theme={null}734```bash theme={null}

180# macOS (Homebrew) 735# macOS (Homebrew)


193pacman -S ripgrep748pacman -S ripgrep

194```749```

195 750 

196Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/docs/claude-code/settings#environment-variables).751Then set `USE_BUILTIN_RIPGREP=0` in your [environment](/en/env-vars).

197 752 

198### Slow or incomplete search results on WSL753### Slow or incomplete search results on WSL

199 754 

200Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches (but not a complete lack of search functionality) when using Claude Code on WSL.755Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches when using Claude Code on WSL. Search still functions, but returns fewer results than on a native filesystem.

201 756 

202<Note>757<Note>

203 `/doctor` will show Search as OK in this case.758 `/doctor` will show Search as OK in this case.


205 760 

206**Solutions:**761**Solutions:**

207 762 

2081. **Submit more specific searches**: Reduce the number of files searched by specifying directories or file types: "Search for JWT validation logic in the auth-service package" or "Find use of md5 hash in JS files".7631. **Submit more specific searches**: reduce the number of files searched by specifying directories or file types: "Search for JWT validation logic in the auth-service package" or "Find use of md5 hash in JS files".

209 764 

2102. **Move project to Linux filesystem**: If possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`).7652. **Move project to Linux filesystem**: if possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`).

211 766 

2123. **Use native Windows instead**: Consider running Claude Code natively on Windows instead of through WSL, for better file system performance.7673. **Use native Windows instead**: consider running Claude Code natively on Windows instead of through WSL, for better file system performance.

213 768 

214## IDE integration issues769## IDE integration issues

215 770 

771If Claude Code does not connect to your IDE or behaves unexpectedly within an IDE terminal, try the solutions below.

772 

216### JetBrains IDE not detected on WSL2773### JetBrains IDE not detected on WSL2

217 774 

218If 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.775If 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.


2261. Find your WSL2 IP address:7831. Find your WSL2 IP address:

227 ```bash theme={null}784 ```bash theme={null}

228 wsl hostname -I785 wsl hostname -I

229 # Example output: 172.21.123.456786 # Example output: 172.21.123.45

230 ```787 ```

231 788 

2322. Open PowerShell as Administrator and create a firewall rule:7892. Open PowerShell as Administrator and create a firewall rule:

233 ```powershell theme={null}790 ```powershell theme={null}

234 New-NetFirewallRule -DisplayName "Allow WSL2 Internal Traffic" -Direction Inbound -Protocol TCP -Action Allow -RemoteAddress 172.21.0.0/16 -LocalAddress 172.21.0.0/16791 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

235 ```792 ```

236 (Adjust the IP range based on your WSL2 subnet from step 1)793 Adjust the IP range based on your WSL2 subnet from step 1.

237 794 

2383. Restart both your IDE and Claude Code7953. Restart both your IDE and Claude Code

239 796 


252 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.809 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.

253</Note>810</Note>

254 811 

255For additional JetBrains configuration tips, see our [IDE integration guide](/en/docs/claude-code/ide-integrations#jetbrains-plugin-settings).812For additional JetBrains configuration tips, see the [JetBrains IDE guide](/en/jetbrains#plugin-settings).

813 

814### Report Windows IDE integration issues

256 815 

257### Reporting Windows IDE integration issues (both native and WSL)816If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information:

258 817 

259If you're experiencing IDE integration problems on Windows, please [create an issue](https://github.com/anthropics/claude-code/issues) with the following information: whether you are native (git bash), or WSL1/WSL2, WSL networking mode (NAT or mirrored), IDE name/version, Claude Code extension/plugin version, and shell type (bash/zsh/etc)818* Environment type: native Windows (Git Bash) or WSL1/WSL2

819* WSL networking mode, if applicable: NAT or mirrored

820* IDE name and version

821* Claude Code extension/plugin version

822* Shell type: Bash, Zsh, PowerShell, etc.

260 823 

261### ESC key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals824### Escape key not working in JetBrains IDE terminals

262 825 

263If 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.826If 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.

264 827 

265To fix this issue:828To fix this issue:

266 829 


270 * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut833 * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut

2713. Apply the changes8343. Apply the changes

272 835 

273This allows the ESC key to properly interrupt Claude Code operations.836This allows the `Esc` key to properly interrupt Claude Code operations.

274 837 

275## Markdown formatting issues838## Markdown formatting issues

276 839 


300 863 

301**Solutions:**864**Solutions:**

302 865 

3031. **Ask Claude to add language tags**: Simply request "Please add appropriate language tags to all code blocks in this markdown file."8661. **Ask Claude to add language tags**: request "Add appropriate language tags to all code blocks in this markdown file."

304 867 

3052. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See the [markdown formatting hook example](/en/docs/claude-code/hooks-guide#markdown-formatting-hook) for implementation details.8682. **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.

306 869 

3073. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.8703. **Manual verification**: after generating markdown files, review them for proper code block formatting and request corrections if needed.

308 871 

309### Inconsistent spacing and formatting872### Inconsistent spacing and formatting

310 873 


312 875 

313**Solutions:**876**Solutions:**

314 877 

3151. **Request formatting corrections**: Ask Claude to "Fix spacing and formatting issues in this markdown file."8781. **Request formatting corrections**: ask Claude to "Fix spacing and formatting issues in this markdown file."

316 879 

3172. **Use formatting tools**: Set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files.8802. **Use formatting tools**: set up hooks to run markdown formatters like `prettier` or custom formatting scripts on generated markdown files.

318 881 

3193. **Specify formatting preferences**: Include formatting requirements in your prompts or project [memory](/en/docs/claude-code/memory) files.8823. **Specify formatting preferences**: include formatting requirements in your prompts or project [memory](/en/memory) files.

320 883 

321### Best practices for markdown generation884### Reduce markdown formatting issues

322 885 

323To minimize formatting issues:886To minimize formatting issues:

324 887 

325* **Be explicit in requests**: Ask for "properly formatted markdown with language-tagged code blocks"888* **Be explicit in requests**: ask for "properly formatted markdown with language-tagged code blocks"

326* **Use project conventions**: Document your preferred markdown style in [CLAUDE.md](/en/docs/claude-code/memory)889* **Use project conventions**: document your preferred markdown style in [`CLAUDE.md`](/en/memory)

327* **Set up validation hooks**: Use post-processing hooks to automatically verify and fix common formatting issues890* **Set up validation hooks**: use post-processing hooks to automatically verify and fix common formatting issues

328 891 

329## Getting more help892## Get more help

330 893 

331If you're experiencing issues not covered here:894If you're experiencing issues not covered here:

332 895 

3331. Use the `/bug` command within Claude Code to report problems directly to Anthropic8961. Use the `/feedback` command within Claude Code to report problems directly to Anthropic

3342. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues8972. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues

3353. Run `/doctor` to check the health of your Claude Code installation8983. Run `/doctor` to diagnose issues. It checks:

899 * Installation type, version, and search functionality

900 * Auto-update status and available versions

901 * Invalid settings files (malformed JSON, incorrect types)

902 * MCP server configuration errors

903 * Keybinding configuration problems

904 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)

905 * Plugin and agent loading errors

3364. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation9064. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation

ultraplan.md +83 −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# Plan in the cloud with ultraplan

6 

7> Start a plan from your CLI, draft it on Claude Code on the web, then execute it remotely or back in your terminal

8 

9<Note>

10 Ultraplan is in research preview. Behavior and capabilities may change based on feedback.

11</Note>

12 

13Ultraplan hands a planning task from your local CLI to a [Claude Code on the web](/en/claude-code-on-the-web) session running in [plan mode](/en/permission-modes#analyze-before-you-edit-with-plan-mode). Claude drafts the plan in the cloud while you keep working in your terminal. When the plan is ready, you open it in your browser to comment on specific sections, ask for revisions, and choose where to execute it.

14 

15This is useful when you want a richer review surface than the terminal offers:

16 

17* **Targeted feedback**: comment on individual sections of the plan instead of replying to the whole thing

18* **Hands-off drafting**: the plan is generated remotely, so your terminal stays free for other work

19* **Flexible execution**: approve the plan to run on the web and open a pull request, or send it back to your terminal

20 

21Ultraplan requires a [Claude Code on the web](/en/claude-code-on-the-web#who-can-use-claude-code-on-the-web) account and a GitHub repository. The cloud session runs in your account's default [cloud environment](/en/claude-code-on-the-web#cloud-environment).

22 

23## Launch ultraplan from the CLI

24 

25From your local CLI session, you can launch ultraplan in three ways:

26 

27* **Command**: run `/ultraplan` followed by your prompt

28* **Keyword**: include the word `ultraplan` anywhere in a normal prompt

29* **From a local plan**: when Claude finishes a local plan and shows the approval dialog, choose **No, refine with Ultraplan on Claude Code on the web** to send the draft to the cloud for further iteration

30 

31For example, to plan a service migration with the command:

32 

33```

34/ultraplan migrate the auth service from sessions to JWTs

35```

36 

37The command and keyword paths open a confirmation dialog before launching. The local plan path skips this dialog because that selection already serves as confirmation. If [Remote Control](/en/remote-control) is active, it disconnects when ultraplan starts because both features occupy the claude.ai/code interface and only one can be connected at a time.

38 

39After the cloud session launches, your CLI's prompt input shows a status indicator while the remote session works:

40 

41| Status | Meaning |

42| :----------------------------- | :----------------------------------------------------------------- |

43| `◇ ultraplan` | Claude is researching your codebase and drafting the plan |

44| `◇ ultraplan needs your input` | Claude has a clarifying question; open the session link to respond |

45| `◆ ultraplan ready` | The plan is ready to review in your browser |

46 

47Run `/tasks` and select the ultraplan entry to open a detail view with the session link, agent activity, and a **Stop ultraplan** action. Stopping archives the cloud session and clears the indicator; nothing is saved to your terminal.

48 

49## Review and revise the plan in your browser

50 

51When the status changes to `◆ ultraplan ready`, open the session link to view the plan on claude.ai. The plan appears in a dedicated review view:

52 

53* **Inline comments**: highlight any passage and leave a comment for Claude to address

54* **Emoji reactions**: react to a section to signal approval or concern without writing a full comment

55* **Outline sidebar**: jump between sections of the plan

56 

57When you ask Claude to address your comments, it revises the plan and presents an updated draft. You can iterate as many times as needed before choosing where to execute.

58 

59## Choose where to execute

60 

61When the plan looks right, you choose from the browser whether Claude implements it in the same cloud session or sends it back to your waiting terminal.

62 

63### Execute on the web

64 

65Select **Approve Claude's plan and start coding** in your browser to have Claude implement it in the same Claude Code on the web session. Your terminal shows a confirmation, the status indicator clears, and the work continues in the cloud. When the implementation finishes, [review the diff](/en/claude-code-on-the-web#review-changes-with-diff-view) and create a pull request from the web interface.

66 

67### Send the plan back to your terminal

68 

69Select **Approve plan and teleport back to terminal** in your browser to implement the plan locally with full access to your environment. This option appears when the session was launched from your CLI and the terminal is still polling. The web session is archived so it doesn't continue working in parallel.

70 

71Your terminal shows the plan in a dialog titled **Ultraplan approved** with three options:

72 

73* **Implement here**: inject the plan into your current conversation and continue from where you left off

74* **Start new session**: clear the current conversation and begin fresh with only the plan as context

75* **Cancel**: save the plan to a file without executing it; Claude prints the file path so you can return to it later

76 

77If you start a new session, Claude prints a `claude --resume` command at the top so you can return to your previous conversation later.

78 

79## Related resources

80 

81* [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 session

83* [Remote Control](/en/remote-control): use the claude.ai/code interface with a session running on your own machine

voice-dictation.md +138 −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# Voice dictation

6 

7> Use push-to-talk voice dictation to speak your prompts instead of typing them in the Claude Code CLI.

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.

10 

11<Note>

12 Voice dictation requires Claude Code v2.1.69 or later. Check your version with `claude --version`.

13</Note>

14 

15## Requirements

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.

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.

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.

22 

23## Enable voice dictation

24 

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.

26 

27```

28/voice

29Voice mode enabled. Hold Space to record. Dictation language: en (/config to change).

30```

31 

32Voice dictation persists across sessions. Run `/voice` again to turn it off, or set it directly in your [user settings file](/en/settings):

33 

34```json theme={null}

35{

36 "voiceEnabled": true

37}

38```

39 

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.

41 

42## Record a prompt

43 

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.

45 

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.

47 

48<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.

50</Tip>

51 

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:

53 

54```

55> refactor the auth middleware to ▮

56 # hold Space, speak "use the new token validation helper"

57> refactor the auth middleware to use the new token validation helper▮

58```

59 

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.

61 

62## Change the dictation language

63 

64Voice dictation uses the same [`language` setting](/en/settings) that controls Claude's response language. If that setting is empty, dictation defaults to English.

65 

66<Accordion title="Supported dictation languages">

67 | Language | Code |

68 | :--------- | :--- |

69 | Czech | `cs` |

70 | Danish | `da` |

71 | Dutch | `nl` |

72 | English | `en` |

73 | French | `fr` |

74 | German | `de` |

75 | Greek | `el` |

76 | Hindi | `hi` |

77 | Indonesian | `id` |

78 | Italian | `it` |

79 | Japanese | `ja` |

80 | Korean | `ko` |

81 | Norwegian | `no` |

82 | Polish | `pl` |

83 | Portuguese | `pt` |

84 | Russian | `ru` |

85 | Spanish | `es` |

86 | Swedish | `sv` |

87 | Turkish | `tr` |

88 | Ukrainian | `uk` |

89</Accordion>

90 

91Set the language in `/config` or directly in settings. You can use either the [BCP 47 language code](https://en.wikipedia.org/wiki/IETF_language_tag) or the language name:

92 

93```json theme={null}

94{

95 "language": "japanese"

96}

97```

98 

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.

100 

101## Rebind the push-to-talk key

102 

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):

104 

105```json theme={null}

106{

107 "bindings": [

108 {

109 "context": "Chat",

110 "bindings": {

111 "meta+k": "voice:pushToTalk",

112 "space": null

113 }

114 }

115 ]

116}

117```

118 

119Setting `"space": null` removes the default binding. Omit it if you want both keys active.

120 

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.

122 

123## Troubleshooting

124 

125Common issues when voice dictation does not activate or record:

126 

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.

128* **`Microphone access is denied`**: grant microphone permission to your terminal in system settings. On macOS, go to System Settings → Privacy & Security → Microphone. On Windows, go to Settings → Privacy → Microphone. Then run `/voice` again.

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`.

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.

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).

132 

133## See also

134 

135* [Customize keyboard shortcuts](/en/keybindings): rebind `voice:pushToTalk` and other CLI keyboard actions

136* [Configure settings](/en/settings): full reference for `voiceEnabled`, `language`, and other settings keys

137* [Interactive mode](/en/interactive-mode): keyboard shortcuts, input modes, and session controls

138* [Built-in commands](/en/commands): reference for `/voice`, `/config`, and all other commands

vs-code.md +435 −82

Details

1# Visual Studio Code1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

2 4 

3> Use Claude Code with Visual Studio Code through our native extension or CLI integration5# Use Claude Code in VS Code

4 6 

5<img src="https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=600835067c8b03557a0529978e3f0261" alt="Claude Code VS Code Extension Interface" data-og-width="2500" width="2500" data-og-height="1155" height="1155" data-path="images/vs-code-extension-interface.jpg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=280&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=c11a25932f84ca58124a368156b476d2 280w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=560&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=3642697ed4d8a6c02396c403bf7aae44 560w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=840&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=fb3cb16e752060fbeb0f5e8ba775798b 840w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=1100&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=1c6073edc8fcfcbc8e237cbf5f25cdc6 1100w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=1650&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=152628678fe3301018b79e932706c430 1650w, https://mintcdn.com/anthropic-claude-docs/Xfpgr-ckk38MZnw3/images/vs-code-extension-interface.jpg?w=2500&fit=max&auto=format&n=Xfpgr-ckk38MZnw3&q=85&s=7ac83b2db00366c9a745380571a748ab 2500w" />7> Install and configure the Claude Code extension for VS Code. Get AI coding assistance with inline diffs, @-mentions, plan review, and keyboard shortcuts.

6 8 

7## VS Code Extension (Beta)9<img src="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=300652d5678c63905e6b0ea9e50835f8" alt="VS Code editor with the Claude Code extension panel open on the right side, showing a conversation with Claude" width="2500" height="1155" data-path="images/vs-code-extension-interface.jpg" />

8 10 

9The VS Code extension, available in beta, lets you see Claude's changes in real-time through a native graphical interface integrated directly into your IDE. The VS Code extension makes it easier to access and interact with Claude Code for users who prefer a visual interface over the terminal.11The VS Code extension provides a native graphical interface for Claude Code, integrated directly into your IDE. This is the recommended way to use Claude Code in VS Code.

10 12 

11### Features13With the extension, you can review and edit Claude's plans before accepting them, auto-accept edits as they're made, @-mention files with specific line ranges from your selection, access conversation history, and open multiple conversations in separate tabs or windows.

12 14 

13The VS Code extension provides:15## Prerequisites

14 16 

15* **Native IDE experience**: Dedicated Claude Code sidebar panel accessed via the Spark icon17Before installing, make sure you have:

16* **Plan mode with editing**: Review and edit Claude's plans before accepting them

17* **Auto-accept edits mode**: Automatically apply Claude's changes as they're made

18* **File management**: @-mention files or attach files and images using the system file picker

19* **MCP server usage**: Use Model Context Protocol servers configured through the CLI

20* **Conversation history**: Easy access to past conversations

21* **Multiple sessions**: Run multiple Claude Code sessions simultaneously

22* **Keyboard shortcuts**: Support for most shortcuts from the CLI

23* **Slash commands**: Access most CLI slash commands directly in the extension

24 

25### Requirements

26 18 

27* VS Code 1.98.0 or higher19* VS Code 1.98.0 or higher

20* An Anthropic account (you'll sign in when you first open the extension). If you're using a third-party provider like Amazon Bedrock or Google Vertex AI, see [Use third-party providers](#use-third-party-providers) instead.

21 

22<Tip>

23 The extension includes the CLI (command-line interface), which you can access from VS Code's integrated terminal for advanced features. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details.

24</Tip>

25 

26## Install the extension

27 

28Click the link for your IDE to install directly:

29 

30* [Install for VS Code](vscode:extension/anthropic.claude-code)

31* [Install for Cursor](cursor:extension/anthropic.claude-code)

28 32 

29### Installation33Or 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**.

30 34 

31Download and install the extension from the [Visual Studio Code Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code).35<Note>If the extension doesn't appear after installation, restart VS Code or run "Developer: Reload Window" from the Command Palette.</Note>

32 36 

33### How It Works37## Get started

34 38 

35Once installed, you can start using Claude Code through the VS Code interface:39Once installed, you can start using Claude Code through the VS Code interface:

36 40 

371. Click the Spark icon in your editor's sidebar to open the Claude Code panel41<Steps>

382. Prompt Claude Code in the same way you would in the terminal42 <Step title="Open the Claude Code panel">

393. Watch as Claude analyzes your code and suggests changes43 Throughout VS Code, the Spark icon indicates Claude Code: <img src="https://mintcdn.com/claude-code/c5r9_6tjPMzFdDDT/images/vs-code-spark-icon.svg?fit=max&auto=format&n=c5r9_6tjPMzFdDDT&q=85&s=3ca45e00deadec8c8f4b4f807da94505" alt="Spark icon" style={{display: "inline", height: "0.85em", verticalAlign: "middle"}} width="16" height="16" data-path="images/vs-code-spark-icon.svg" />

404. Review and accept edits directly in the interface44 

41 * **Tip**: Drag the sidebar wider to see inline diffs, then click on them to expand for full details45 The quickest way to open Claude is to click the Spark icon in the **Editor Toolbar** (top-right corner of the editor). The icon only appears when you have a file open.

46 

47 <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=eb4540325d94664c51776dbbfec4cf02" alt="VS Code editor showing the Spark icon in the Editor Toolbar" width="2796" height="734" data-path="images/vs-code-editor-icon.png" />

48 

49 Other ways to open Claude Code:

50 

51 * **Activity Bar**: click the Spark icon in the left sidebar to open the sessions list. Click any session to open it as a full editor tab, or start a new one. This icon is always visible in the Activity Bar.

52 * **Command Palette**: `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux), type "Claude Code", and select an option like "Open in New Tab"

53 * **Status Bar**: click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open.

54 

55 When you first open the panel, a **Learn Claude Code** checklist appears. Work through each item by clicking **Show me**, or dismiss it with the X. To reopen it later, uncheck **Hide Onboarding** in VS Code settings under Extensions → Claude Code.

56 

57 You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.

58 </Step>

59 

60 <Step title="Send a prompt">

61 Ask Claude to help with your code or files, whether that's explaining how something works, debugging an issue, or making changes.

62 

63 <Tip>Claude automatically sees your selected text. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to also insert an @-mention reference (like `@file.ts#5-10`) into your prompt.</Tip>

64 

65 Here's an example of asking about a particular line in a file:

66 

67 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ede3ed8d8d5f940e01c5de636d009cfd" alt="VS Code editor with lines 2-3 selected in a Python file, and the Claude Code panel showing a question about those lines with an @-mention reference" width="3288" height="1876" data-path="images/vs-code-send-prompt.png" />

68 </Step>

69 

70 <Step title="Review changes">

71 When Claude wants to edit a file, it shows a side-by-side comparison of the original and proposed changes, then asks for permission. You can accept, reject, or tell Claude what to do instead.

72 

73 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" width="3292" height="1876" data-path="images/vs-code-edits.png" />

74 </Step>

75</Steps>

76 

77For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows).

78 

79<Tip>

80 Run "Claude Code: Open Walkthrough" from the Command Palette for a guided tour of the basics.

81</Tip>

82 

83## Use the prompt box

84 

85The prompt box supports several features:

86 

87* **Permission modes**: click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. VS Code automatically opens the plan as a full markdown document where you can add inline comments to give feedback before Claude begins. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`.

88* **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.

89* **Context indicator**: the prompt box shows how much of Claude's context window you're using. Claude automatically compacts when needed, or you can run `/compact` manually.

90* **Extended thinking**: lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). See [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) for details.

91* **Multi-line input**: press `Shift+Enter` to add a new line without sending. This also works in the "Other" free-text input of question dialogs.

92 

93### Reference files and folders

94 

95Use @-mentions to give Claude context about specific files or folders. When you type `@` followed by a file or folder name, Claude reads that content and can answer questions about it or make changes to it. Claude Code supports fuzzy matching, so you can type partial names to find what you need:

96 

97```text theme={null}

98> Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.)

99> What's in @src/components/ (include a trailing slash for folders)

100```

101 

102For large PDFs, you can ask Claude to read specific pages instead of the whole file: a single page, a range like pages 1-10, or an open-ended range like page 3 onward.

103 

104When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to insert an @-mention with the file path and line numbers (e.g., `@app.ts#5-10`). Click the selection indicator to toggle whether Claude can see your highlighted text - the eye-slash icon means the selection is hidden from Claude.

105 

106You can also hold `Shift` while dragging files into the prompt box to add them as attachments. Click the X on any attachment to remove it from context.

107 

108### Resume past conversations

109 

110Click the dropdown at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. 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).

111 

112### Resume remote sessions from Claude.ai

113 

114If 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.

115 

116<Steps>

117 <Step title="Open Past Conversations">

118 Click the **Past Conversations** dropdown at the top of the Claude Code panel.

119 </Step>

120 

121 <Step title="Select the Remote tab">

122 The dialog shows two tabs: Local and Remote. Click **Remote** to see sessions from claude.ai.

123 </Step>

124 

125 <Step title="Select a session to resume">

126 Browse or search your remote sessions. Click any session to download it and continue the conversation locally.

127 </Step>

128</Steps>

129 

130<Note>

131 Only web sessions started with a GitHub repository appear in the Remote tab. Resuming loads the conversation history locally; changes are not synced back to claude.ai.

132</Note>

133 

134## Customize your workflow

135 

136Once you're up and running, you can reposition the Claude panel, run multiple sessions, or switch to terminal mode.

137 

138### Choose where Claude lives

139 

140You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel's tab or title bar and drag it to:

141 

142* **Secondary sidebar**: the right side of the window. Keeps Claude visible while you code.

143* **Primary sidebar**: the left sidebar with icons for Explorer, Search, etc.

144* **Editor area**: opens Claude as a tab alongside your files. Useful for side tasks.

145 

146<Tip>

147 Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. The Activity Bar sessions list icon is separate from the Claude panel: the sessions list is always visible in the Activity Bar, while the Claude panel icon only appears there when the panel is docked to the left sidebar.

148</Tip>

149 

150### Run multiple conversations

151 

152Use **Open in New Tab** or **Open in New Window** from the Command Palette to start additional conversations. Each conversation maintains its own history and context, allowing you to work on different tasks in parallel.

153 

154When using tabs, a small colored dot on the spark icon indicates status: blue means a permission request is pending, orange means Claude finished while the tab was hidden.

155 

156### Switch to terminal mode

157 

158By default, the extension opens a graphical chat panel. If you prefer the CLI-style interface, open the [Use Terminal setting](vscode://settings/claudeCode.useTerminal) and check the box.

159 

160You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), go to Extensions → Claude Code, and check **Use Terminal**.

161 

162## Manage plugins

163 

164The VS Code extension includes a graphical interface for installing and managing [plugins](/en/plugins). Type `/plugins` in the prompt box to open the **Manage plugins** interface.

165 

166### Install plugins

167 

168The plugin dialog shows two tabs: **Plugins** and **Marketplaces**.

169 

170In the Plugins tab:

171 

172* **Installed plugins** appear at the top with toggle switches to enable or disable them

173* **Available plugins** from your configured marketplaces appear below

174* Search to filter plugins by name or description

175* Click **Install** on any available plugin

176 

177When you install a plugin, choose the installation scope:

178 

179* **Install for you**: available in all your projects (user scope)

180* **Install for this project**: shared with project collaborators (project scope)

181* **Install locally**: only for you, only in this repository (local scope)

182 

183### Manage marketplaces

184 

185Switch to the **Marketplaces** tab to add or remove plugin sources:

186 

187* Enter a GitHub repo, URL, or local path to add a new marketplace

188* Click the refresh icon to update a marketplace's plugin list

189* Click the trash icon to remove a marketplace

190 

191After making changes, a banner prompts you to restart Claude Code to apply the updates.

192 

193<Note>

194 Plugin management in VS Code uses the same CLI commands under the hood. Plugins and marketplaces you configure in the extension are also available in the CLI, and vice versa.

195</Note>

196 

197For more about the plugin system, see [Plugins](/en/plugins) and [Plugin marketplaces](/en/plugin-marketplaces).

198 

199## Automate browser tasks with Chrome

200 

201Connect Claude to your Chrome browser to test web apps, debug with console logs, and automate browser workflows without leaving VS Code. This requires the [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher.

202 

203Type `@browser` in the prompt box followed by what you want Claude to do:

204 

205```text theme={null}

206@browser go to localhost:3000 and check the console for errors

207```

208 

209You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content.

210 

211Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into.

42 212 

43### Using Third-Party Providers (Vertex and Bedrock)213For setup instructions, the full list of capabilities, and troubleshooting, see [Use Claude Code with Chrome](/en/chrome).

44 214 

45The VS Code extension supports using Claude Code with third-party providers like Amazon Bedrock and Google Vertex AI. When configured with these providers, the extension will not prompt for login. To use third-party providers, configure environment variables in the VS Code extension settings:215## VS Code commands and shortcuts

46 216 

471. Open VS Code settings217Open the Command Palette (`Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows/Linux) and type "Claude Code" to see all available VS Code commands for the Claude Code extension.

482. Search for "Claude Code: Environment Variables"

493. Add the required environment variables

50 218 

51#### Environment Variables219Some shortcuts depend on which panel is "focused" (receiving keyboard input). When your cursor is in a code file, the editor is focused. When your cursor is in Claude's prompt box, Claude is focused. Use `Cmd+Esc` / `Ctrl+Esc` to toggle between them.

52 220 

53| Variable | Description | Required | Example |221<Note>

54| :---------------------------- | :------------------------------------- | :--------------------- | :----------------------------------------------- |222 These are VS Code commands for controlling the extension. Not all built-in Claude Code commands are available in the extension. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details.

55| `CLAUDE_CODE_USE_BEDROCK` | Enable Amazon Bedrock integration | Required for Bedrock | `"1"` or `"true"` |223</Note>

56| `CLAUDE_CODE_USE_VERTEX` | Enable Google Vertex AI integration | Required for Vertex AI | `"1"` or `"true"` |

57| `ANTHROPIC_API_KEY` | API key for third-party access | Required | `"your-api-key"` |

58| `AWS_REGION` | AWS region for Bedrock | | `"us-east-2"` |

59| `AWS_PROFILE` | AWS profile for Bedrock authentication | | `"your-profile"` |

60| `CLOUD_ML_REGION` | Region for Vertex AI | | `"global"` or `"us-east5"` |

61| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI | | `"your-project-id"` |

62| `ANTHROPIC_MODEL` | Override primary model | Override model ID | `"us.anthropic.claude-sonnet-4-5-20250929-v1:0"` |

63| `ANTHROPIC_SMALL_FAST_MODEL` | Override small/fast model | Optional | `"us.anthropic.claude-3-5-haiku-20241022-v1:0"` |

64| `CLAUDE_CODE_SKIP_AUTH_LOGIN` | Disable all prompts to login | Optional | `"1"` or `"true"` |

65 224 

66For detailed setup instructions and additional configuration options, see:225| Command | Shortcut | Description |

226| -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------ |

227| Focus Input | `Cmd+Esc` (Mac) / `Ctrl+Esc` (Windows/Linux) | Toggle focus between editor and Claude |

228| Open in Side Bar | - | Open Claude in the left sidebar |

229| Open in Terminal | - | Open Claude in terminal mode |

230| Open in New Tab | `Cmd+Shift+Esc` (Mac) / `Ctrl+Shift+Esc` (Windows/Linux) | Open a new conversation as an editor tab |

231| Open in New Window | - | Open a new conversation in a separate window |

232| New Conversation | `Cmd+N` (Mac) / `Ctrl+N` (Windows/Linux) | Start a new conversation (requires Claude to be focused) |

233| Insert @-Mention Reference | `Option+K` (Mac) / `Alt+K` (Windows/Linux) | Insert a reference to the current file and selection (requires editor to be focused) |

234| Show Logs | - | View extension debug logs |

235| Logout | - | Sign out of your Anthropic account |

67 236 

68* [Claude Code on Amazon Bedrock](/en/docs/claude-code/amazon-bedrock)237### Launch a VS Code tab from other tools

69* [Claude Code on Google Vertex AI](/en/docs/claude-code/google-vertex-ai)

70 238 

71### Not Yet Implemented239The 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.

72 240 

73The following features are not yet available in the VS Code extension:241Invoke the handler with your operating system's URL opener. On macOS:

74 242 

75* **Full MCP server configuration**: You need to [configure MCP servers through the CLI](/en/docs/claude-code/mcp) first, then the extension will use them243```bash theme={null}

76* **Subagents configuration**: Configure [subagents through the CLI](/en/docs/claude-code/sub-agents) to use them in VS Code244open "vscode://anthropic.claude-code/open"

77* **Checkpoints**: Save and restore conversation state at specific points245```

78* **Advanced shortcuts**:

79 * `#` shortcut to add to memory

80 * `!` shortcut to run bash commands directly

81* **Tab completion**: File path completion with tab key

82 246 

83We are working on adding these features in future updates.247Use `xdg-open` on Linux or `start` on Windows.

84 248 

85## Security Considerations249The handler accepts two optional query parameters:

86 250 

87When Claude Code runs in VS Code 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.251| Parameter | Description |

252| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

253| `prompt` | Text to pre-fill in the prompt box. Must be URL-encoded. The prompt is pre-filled but not submitted automatically. |

254| `session` | A session ID to resume instead of starting a new conversation. The session must belong to the workspace currently open in VS Code. If the session isn't found, a fresh conversation starts instead. If the session is already open in a tab, that tab is focused. To capture a session ID programmatically, see [Continue conversations](/en/headless#continue-conversations). |

88 255 

89When running in VS Code, consider:256For example, to open a tab pre-filled with "review my changes":

90 257 

91* Enabling [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces258```text theme={null}

92* Using manual approval mode for edits259vscode://anthropic.claude-code/open?prompt=review%20my%20changes

93* Taking extra care to ensure Claude is only used with trusted prompts260```

94 261 

95## Legacy CLI Integration262## Configure settings

96 263 

97The first VS Code integration that we released allows Claude Code running in the terminal to interact with your IDE. It provides selection context sharing (current selection/tab is automatically shared with Claude Code), diff viewing in the IDE instead of terminal, file reference shortcuts (`Cmd+Option+K` on Mac or `Alt+Ctrl+K` on Windows/Linux to insert file references like @File#L1-99), and automatic diagnostic sharing (lint and syntax errors).264The extension has two types of settings:

98 265 

99The legacy integration auto-installs when you run `claude` from VS Code's integrated terminal. Simply run `claude` from the terminal and all features activate. For external terminals, use the `/ide` command to connect Claude Code to your VS Code instance. To configure, run `claude`, enter `/config`, and set the diff tool to `auto` for automatic IDE detection.266* **Extension settings** in VS Code: control the extension's behavior within VS Code. Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions Claude Code. You can also type `/` and select **General Config** to open settings.

267* **Claude Code settings** in `~/.claude/settings.json`: shared between the extension and CLI. Use for allowed commands, environment variables, hooks, and MCP servers. See [Settings](/en/settings) for details.

100 268 

101Both the extension and CLI integration work with Visual Studio Code, Cursor, Windsurf, and VSCodium.269<Tip>

270 Add `"$schema": "https://json.schemastore.org/claude-code-settings.json"` to your `settings.json` to get autocomplete and inline validation for all available settings directly in VS Code.

271</Tip>

102 272 

103## Troubleshooting273### Extension settings

104 274 

105### Extension Not Installing275| Setting | Default | Description |

276| --------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

277| `selectedModel` | `default` | Model for new conversations. Change per-session with `/model`. |

278| `useTerminal` | `false` | Launch Claude in terminal mode instead of graphical panel |

279| `initialPermissionMode` | `default` | Controls approval prompts for new conversations: `default`, `plan`, `acceptEdits`, or `bypassPermissions`. See [permission modes](/en/permission-modes). |

280| `preferredLocation` | `panel` | Where Claude opens: `sidebar` (right) or `panel` (new tab) |

281| `autosave` | `true` | Auto-save files before Claude reads or writes them |

282| `useCtrlEnterToSend` | `false` | Use Ctrl/Cmd+Enter instead of Enter to send prompts |

283| `enableNewConversationShortcut` | `true` | Enable Cmd/Ctrl+N to start a new conversation |

284| `hideOnboarding` | `false` | Hide the onboarding checklist (graduation cap icon) |

285| `respectGitIgnore` | `true` | Exclude .gitignore patterns from file searches |

286| `environmentVariables` | `[]` | Set environment variables for the Claude process. Use Claude Code settings instead for shared config. |

287| `disableLoginPrompt` | `false` | Skip authentication prompts (for third-party provider setups) |

288| `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. |

289| `claudeProcessWrapper` | - | Executable path used to launch the Claude process |

106 290 

107* Ensure you have a compatible version of VS Code (1.85.0 or later)291## VS Code extension vs. Claude Code CLI

292 

293Claude Code is available as both a VS Code extension (graphical panel) and a CLI (command-line interface in the terminal). Some features are only available in the CLI. If you need a CLI-only feature, run `claude` in VS Code's integrated terminal.

294 

295| Feature | CLI | VS Code Extension |

296| ------------------- | ------------------- | ------------------------------------------------------------------------------------ |

297| Commands and skills | [All](/en/commands) | Subset (type `/` to see available) |

298| MCP server config | Yes | Partial (add servers via CLI; manage existing servers with `/mcp` in the chat panel) |

299| Checkpoints | Yes | Yes |

300| `!` bash shortcut | Yes | No |

301| Tab completion | Yes | No |

302 

303### Rewind with checkpoints

304 

305The VS Code extension supports checkpoints, which track Claude's file edits and let you rewind to a previous state. Hover over any message to reveal the rewind button, then choose from three options:

306 

307* **Fork conversation from here**: start a new conversation branch from this message while keeping all code changes intact

308* **Rewind code to here**: revert file changes back to this point in the conversation while keeping the full conversation history

309* **Fork conversation and rewind code**: start a new conversation branch and revert file changes to this point

310 

311For full details on how checkpoints work and their limitations, see [Checkpointing](/en/checkpointing).

312 

313### Run CLI in VS Code

314 

315To use the CLI while staying in VS Code, open the integrated terminal (`` Ctrl+` `` on Windows/Linux or `` Cmd+` `` on Mac) and run `claude`. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing.

316 

317If using an external terminal, run `/ide` inside Claude Code to connect it to VS Code.

318 

319### Switch between extension and CLI

320 

321The extension and CLI share the same conversation history. To continue an extension conversation in the CLI, run `claude --resume` in the terminal. This opens an interactive picker where you can search for and select your conversation.

322 

323### Include terminal output in prompts

324 

325Reference terminal output in your prompts using `@terminal:name` where `name` is the terminal's title. This lets Claude see command output, error messages, or logs without copy-pasting.

326 

327### Monitor background processes

328 

329When Claude runs long-running commands, the extension shows progress in the status bar. However, visibility for background tasks is limited compared to the CLI. For better visibility, have Claude output the command so you can run it in VS Code's integrated terminal.

330 

331### Connect to external tools with MCP

332 

333MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs.

334 

335To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run:

336 

337```bash theme={null}

338claude mcp add --transport http github https://api.githubcopilot.com/mcp/

339```

340 

341Once configured, ask Claude to use the tools (e.g., "Review PR #456").

342 

343To manage MCP servers without leaving VS Code, type `/mcp` in the chat panel. The MCP management dialog lets you enable or disable servers, reconnect to a server, and manage OAuth authentication. See the [MCP documentation](/en/mcp) for available servers.

344 

345## Work with git

346 

347Claude Code integrates with git to help with version control workflows directly in VS Code. Ask Claude to commit changes, create pull requests, or work across branches.

348 

349### Create commits and pull requests

350 

351Claude can stage changes, write commit messages, and create pull requests based on your work:

352 

353```text theme={null}

354> commit my changes with a descriptive message

355> create a pr for this feature

356> summarize the changes I've made to the auth module

357```

358 

359When creating pull requests, Claude generates descriptions based on the actual code changes and can add context about testing or implementation decisions.

360 

361### Use git worktrees for parallel tasks

362 

363Use the `--worktree` (`-w`) flag to start Claude in an isolated worktree with its own files and branch:

364 

365```bash theme={null}

366claude --worktree feature-auth

367```

368 

369Each 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).

370 

371## Use third-party providers

372 

373By default, Claude Code connects directly to Anthropic's API. If your organization uses Amazon Bedrock, Google Vertex AI, or Microsoft Foundry to access Claude, configure the extension to use your provider instead:

374 

375<Steps>

376 <Step title="Disable login prompt">

377 Open the [Disable Login Prompt setting](vscode://settings/claudeCode.disableLoginPrompt) and check the box.

378 

379 You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), search for "Claude Code login", and check **Disable Login Prompt**.

380 </Step>

381 

382 <Step title="Configure your provider">

383 Follow the setup guide for your provider:

384 

385 * [Claude Code on Amazon Bedrock](/en/amazon-bedrock)

386 * [Claude Code on Google Vertex AI](/en/google-vertex-ai)

387 * [Claude Code on Microsoft Foundry](/en/microsoft-foundry)

388 

389 These guides cover configuring your provider in `~/.claude/settings.json`, which ensures your settings are shared between the VS Code extension and the CLI.

390 </Step>

391</Steps>

392 

393## Security and privacy

394 

395Your code stays private. Claude Code processes your code to provide assistance but does not use it to train models. For details on data handling and how to opt out of logging, see [Data and privacy](/en/data-usage).

396 

397With auto-edit permissions enabled, Claude Code can modify VS Code configuration files (like `settings.json` or `tasks.json`) that VS Code may execute automatically. To reduce risk when working with untrusted code:

398 

399* Enable [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces

400* Use manual approval mode instead of auto-accept for edits

401* Review changes carefully before accepting them

402 

403### The built-in IDE MCP server

404 

405When the extension is active, it runs a local MCP server that the CLI connects to automatically. This is how the CLI opens diffs in VS Code's native diff viewer, reads your current selection for `@`-mentions, and — when you're working in a Jupyter notebook — asks VS Code to execute cells.

406 

407The server is named `ide` and is hidden from `/mcp` because there's nothing to configure. If your organization uses a `PreToolUse` hook to allowlist MCP tools, though, you'll need to know it exists.

408 

409**Transport and authentication.** The server binds to `127.0.0.1` on a random high port and is not reachable from other machines. Each extension activation generates a fresh random auth token that the CLI must present to connect. The token is written to a lock file under `~/.claude/ide/` with `0600` permissions in a `0700` directory, so only the user running VS Code can read it.

410 

411**Tools exposed to the model.** The server hosts a dozen tools, but only two are visible to the model. The rest are internal RPC the CLI uses for its own UI — opening diffs, reading selections, saving files — and are filtered out before the tool list reaches Claude.

412 

413| Tool name (as seen by hooks) | What it does | Writes? |

414| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------- |

415| `mcp__ide__getDiagnostics` | Returns language-server diagnostics — the errors and warnings in VS Code's Problems panel. Optionally scoped to one file. | No |

416| `mcp__ide__executeCode` | Runs Python code in the active Jupyter notebook's kernel. See confirmation flow below. | Yes |

417 

418**Jupyter execution always asks first.** `mcp__ide__executeCode` can't run anything silently. On each call, the code is inserted as a new cell at the end of the active notebook, VS Code scrolls it into view, and a native Quick Pick asks you to **Execute** or **Cancel**. Cancelling — or dismissing the picker with `Esc` — returns an error to Claude and nothing runs. The tool also refuses outright when there's no active notebook, when the Jupyter extension (`ms-toolsai.jupyter`) isn't installed, or when the kernel isn't Python.

419 

420<Note>

421 The Quick Pick confirmation is separate from `PreToolUse` hooks. An allowlist entry for `mcp__ide__executeCode` lets Claude *propose* running a cell; the Quick Pick inside VS Code is what lets it *actually* run.

422</Note>

423 

424## Fix common issues

425 

426### Extension won't install

427 

428* Ensure you have a compatible version of VS Code (1.98.0 or later)

108* Check that VS Code has permission to install extensions429* Check that VS Code has permission to install extensions

109* Try installing directly from the marketplace website430* Try installing directly from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code)

431 

432### Spark icon not visible

433 

434The Spark icon appears in the **Editor Toolbar** (top-right of editor) when you have a file open. If you don't see it:

435 

4361. **Open a file**: The icon requires a file to be open. Having just a folder open isn't enough.

4372. **Check VS Code version**: Requires 1.98.0 or higher (Help → About)

4383. **Restart VS Code**: Run "Developer: Reload Window" from the Command Palette

4394. **Disable conflicting extensions**: Temporarily disable other AI extensions (Cline, Continue, etc.)

4405. **Check workspace trust**: The extension doesn't work in Restricted Mode

441 

442Alternatively, 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".

443 

444### Claude Code never responds

445 

446If Claude Code isn't responding to your prompts:

447 

4481. **Check your internet connection**: Ensure you have a stable internet connection

4492. **Start a new conversation**: Try starting a fresh conversation to see if the issue persists

4503. **Try the CLI**: Run `claude` from the terminal to see if you get more detailed error messages

451 

452If problems persist, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error.

453 

454## Uninstall the extension

455 

456To uninstall the Claude Code extension:

457 

4581. Open the Extensions view (`Cmd+Shift+X` on Mac or `Ctrl+Shift+X` on Windows/Linux)

4592. Search for "Claude Code"

4603. Click **Uninstall**

461 

462To also remove extension data and reset all settings:

463 

464```bash theme={null}

465rm -rf ~/.vscode/globalStorage/anthropic.claude-code

466```

467 

468For additional help, see the [troubleshooting guide](/en/troubleshooting).

110 469 

111### Legacy Integration Not Working470## Next steps

112 471 

113* Ensure you're running Claude Code from VS Code's integrated terminal472Now that you have Claude Code set up in VS Code:

114* Ensure the CLI for your IDE variant is installed:

115 * VS Code: `code` command should be available

116 * Cursor: `cursor` command should be available

117 * Windsurf: `windsurf` command should be available

118 * VSCodium: `codium` command should be available

119* If the command isn't installed:

120 1. Open command palette with `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux)

121 2. Search for "Shell Command: Install 'code' command in PATH" (or equivalent for your IDE)

122 473 

123For additional help, see our [troubleshooting guide](/en/docs/claude-code/troubleshooting).474* [Explore common workflows](/en/common-workflows) to get the most out of Claude Code

475* [Set up MCP servers](/en/mcp) to extend Claude's capabilities with external tools. Add servers using the CLI, then manage them with `/mcp` in the chat panel.

476* [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.

web-scheduled-tasks.md +154 −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# Schedule tasks on the web

6 

7> Automate recurring work with cloud scheduled tasks

8 

9A scheduled task runs a prompt on a recurring cadence using Anthropic-managed infrastructure. Tasks keep working even when your computer is off.

10 

11A few examples of recurring work you can automate:

12 

13* Reviewing open pull requests each morning

14* Analyzing CI failures overnight and surfacing summaries

15* Syncing documentation after PRs merge

16* Running dependency audits every week

17 

18Scheduled tasks are available to all Claude Code on the web users, including Pro, Max, Team, and Enterprise.

19 

20## Compare scheduling options

21 

22Claude Code offers three ways to schedule recurring work:

23 

24| | [Cloud](/en/web-scheduled-tasks) | [Desktop](/en/desktop-scheduled-tasks) | [`/loop`](/en/scheduled-tasks) |

25| :------------------------- | :------------------------------- | :------------------------------------- | :----------------------------- |

26| Runs on | Anthropic cloud | Your machine | Your machine |

27| Requires machine on | No | Yes | Yes |

28| Requires open session | No | No | Yes |

29| Persistent across restarts | Yes | Yes | No (session-scoped) |

30| Access to local files | No (fresh clone) | Yes | Yes |

31| MCP servers | Connectors configured per task | [Config files](/en/mcp) and connectors | Inherits from session |

32| Permission prompts | No (runs autonomously) | Configurable per task | Inherits from session |

33| Customizable schedule | Via `/schedule` in the CLI | Yes | Yes |

34| Minimum interval | 1 hour | 1 minute | 1 minute |

35 

36<Tip>

37 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.

38</Tip>

39 

40## Create a scheduled task

41 

42You can create a scheduled task from three places:

43 

44* **Web**: visit [claude.ai/code/scheduled](https://claude.ai/code/scheduled) and click **New scheduled task**

45* **Desktop app**: open the **Schedule** page, click **New task**, and choose **New remote task**. See [Desktop scheduled tasks](/en/desktop-scheduled-tasks) for details.

46* **CLI**: run `/schedule` in any session. Claude walks you through the setup conversationally. You can also pass a description directly, like `/schedule daily PR review at 9am`.

47 

48The web and Desktop entry points open a form. The CLI collects the same information through a guided conversation.

49 

50The steps below walk through the web interface.

51 

52<Steps>

53 <Step title="Open the creation form">

54 Visit [claude.ai/code/scheduled](https://claude.ai/code/scheduled) and click **New scheduled task**.

55 </Step>

56 

57 <Step title="Name the task and write the prompt">

58 Give the task a descriptive name and write the prompt Claude runs each time. The prompt is the most important part: the task runs autonomously, so the prompt must be self-contained and explicit about what to do and what success looks like.

59 

60 The prompt input includes a model selector. Claude uses this model for each run of the task.

61 </Step>

62 

63 <Step title="Select repositories">

64 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.

65 </Step>

66 

67 <Step title="Select an environment">

68 Select a [cloud environment](/en/claude-code-on-the-web#cloud-environment) for the task. Environments control what the cloud session has access to:

69 

70 * **Network access**: set the level of internet access available during each run

71 * **Environment variables**: provide API keys, tokens, or other secrets Claude can use

72 * **Setup script**: run install commands before each session starts, like installing dependencies or configuring tools

73 

74 A **Default** environment is available out of the box. To use a custom environment, [create one](/en/claude-code-on-the-web#cloud-environment) before creating the task.

75 </Step>

76 

77 <Step title="Choose a schedule">

78 Pick how often the task runs from the [frequency options](#frequency-options). The default is daily at 9:00 AM in your local time zone. Tasks may run a few minutes after their scheduled time due to stagger.

79 

80 If the preset options don't fit your needs, pick the closest one and update the schedule from the CLI with `/schedule update` to set a specific schedule.

81 </Step>

82 

83 <Step title="Review connectors">

84 All of your connected [MCP connectors](/en/mcp) are included by default. Remove any that the task doesn't need. Connectors give Claude access to external services like Slack, Linear, or Google Drive during each run.

85 </Step>

86 

87 <Step title="Create the task">

88 Click **Create**. The task appears in the scheduled tasks list and runs automatically at the next scheduled time. Each run creates a new session alongside your other sessions, where you can see what Claude did, review changes, and create a pull request. To trigger a run immediately, click **Run now** from the task's detail page.

89 </Step>

90</Steps>

91 

92### Frequency options

93 

94The schedule picker offers preset frequencies that handle time zone conversion for you. Pick a time in your local zone and the task runs at that wall-clock time regardless of where the cloud infrastructure is located.

95 

96<Note>

97 Tasks may run a few minutes after their scheduled time. The offset is consistent for each task.

98</Note>

99 

100| Frequency | Description |

101| :-------- | :------------------------------------------------------------------------- |

102| Hourly | Runs every hour. |

103| Daily | Runs once per day at the time you specify. Defaults to 9:00 AM local time. |

104| Weekdays | Same as Daily but skips Saturday and Sunday. |

105| Weekly | Runs once per week on the day and time you specify. |

106 

107For custom intervals like every 2 hours or first of each month, pick the closest preset and update the schedule from the CLI with `/schedule update` to set a specific cron expression. The minimum interval is 1 hour. Expressions that fire more frequently, such as `*/30 * * * *`, are rejected.

108 

109### Repositories and branch permissions

110 

111Each repository you add is cloned on every run. Claude starts from the repository's default branch unless your prompt specifies otherwise.

112 

113By default, Claude can only push to branches prefixed with `claude/`. This prevents scheduled tasks from accidentally modifying protected or long-lived branches.

114 

115To remove this restriction for a specific repository, enable **Allow unrestricted branch pushes** for that repository when creating or editing the task.

116 

117### Connectors

118 

119Scheduled tasks can use your connected MCP connectors to read from and write to external services during each run. For example, a task that triages support requests might read from a Slack channel and create issues in Linear.

120 

121When you create a task, all of your currently connected connectors are included by default. Remove any that aren't needed to limit which tools Claude has access to during the run. You can also add connectors directly from the task form.

122 

123To manage or add connectors outside of the task form, visit **Settings > Connectors** on claude.ai or use `/schedule update` in the CLI.

124 

125### Environments

126 

127Each task runs in a [cloud environment](/en/claude-code-on-the-web#cloud-environment) that controls network access, environment variables, and setup scripts. Configure environments before creating a task to give Claude access to APIs, install dependencies, or restrict network scope. See [cloud environment](/en/claude-code-on-the-web#cloud-environment) for the full setup guide.

128 

129## Manage scheduled tasks

130 

131Click a task in the **Scheduled** list to open its detail page. The detail page shows the task's repositories, connectors, prompt, schedule, and a list of past runs.

132 

133### View and interact with runs

134 

135Click 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.

136 

137### Edit and control tasks

138 

139From the task detail page you can:

140 

141* Click **Run now** to start a run immediately without waiting for the next scheduled time.

142* Use the toggle in the **Repeats** section to pause or resume the schedule. Paused tasks keep their configuration but don't run until you re-enable them.

143* Click the edit icon to change the name, prompt, schedule, repositories, environment, or connectors.

144* Click the delete icon to remove the task. Past sessions created by the task remain in your session list.

145 

146You can also manage tasks from the CLI with `/schedule`. Run `/schedule list` to see all tasks, `/schedule update` to change a task, or `/schedule run` to trigger one immediately.

147 

148## Related resources

149 

150* [Desktop scheduled tasks](/en/desktop-scheduled-tasks): schedule tasks that run on your machine with access to local files. The Desktop app's **Schedule** page shows both local and remote tasks in the same grid.

151* [`/loop` and CLI scheduled tasks](/en/scheduled-tasks): lightweight scheduling within a CLI session

152* [Cloud environment](/en/claude-code-on-the-web#cloud-environment): configure the runtime environment for cloud tasks

153* [MCP connectors](/en/mcp): connect external services like Slack, Linear, and Google Drive

154* [GitHub Actions](/en/github-actions): run Claude in your CI pipeline on repo events

whats-new.md +25 −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# What's new

6 

7> A weekly digest of notable Claude Code features, with code snippets, demos, and context on why they matter.

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).

10 

11<Update label="Week 14" description="March 30 – April 3, 2026" tags={["v2.1.86–v2.1.91"]}>

12 **Computer use** comes to the CLI in research preview: Claude can open native apps, click through UI, and verify changes from your terminal. Best for closing the loop on things only a GUI can verify.

13 

14 Also this week: `/powerup` interactive lessons, flicker-free alt-screen rendering, a per-tool MCP result-size override up to 500K, and plugin executables on the Bash tool's `PATH`.

15 

16 [Read the Week 14 digest →](/en/whats-new/2026-w14)

17</Update>

18 

19<Update label="Week 13" description="March 23–27, 2026" tags={["v2.1.83–v2.1.85"]}>

20 **Auto mode** lands in research preview: a classifier handles your permission prompts so safe actions run without interruption and risky ones get blocked. The middle ground between approving everything and `--dangerously-skip-permissions`.

21 

22 Also this week: computer use in the Desktop app, PR auto-fix on Web, transcript search with `/`, a native PowerShell tool for Windows, and conditional `if` hooks.

23 

24 [Read the Week 13 digest →](/en/whats-new/2026-w13)

25</Update>

whats-new/2026-w13.md +164 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Week 13 · March 23–27, 2026

6 

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 

9<div className="digest-meta">

10 <span>Releases <a href="/en/changelog#2-1-83">v2.1.83 → v2.1.85</a></span>

11 <span>6 features · March 23–27</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Auto mode</span>

17 <span className="digest-feature-pill">research preview</span>

18 </div>

19 

20 <p className="digest-feature-lede">Auto mode hands your permission prompts to a classifier. Safe edits and commands run without interrupting you; anything destructive or suspicious gets blocked and surfaced. It's the middle ground between approving every file write and running with <code>--dangerously-skip-permissions</code>.</p>

21 

22 <Frame>

23 <img src="https://mintcdn.com/claude-code/CfffsX01JHFnIKvD/images/whats-new/auto-mode.png?fit=max&auto=format&n=CfffsX01JHFnIKvD&q=85&s=367c9e9d4ba5bc57ec4b935154bf1fbb" alt="Claude Code prompt footer showing 'auto mode on (shift+tab to cycle)' indicator in yellow" width="2400" height="691" data-path="images/whats-new/auto-mode.png" />

24 </Frame>

25 

26 <p className="digest-feature-try">Cycle to auto with Shift+Tab, or set it as your default:</p>

27 

28 ```json .claude/settings.json {3} theme={null}

29 {

30 "permissions": {

31 "defaultMode": "auto"

32 }

33 }

34 ```

35 

36 <a className="digest-feature-link" href="/en/permission-modes">Permission modes guide</a>

37</div>

38 

39<div className="digest-feature">

40 <div className="digest-feature-header">

41 <span className="digest-feature-title">Computer use</span>

42 <span className="digest-feature-pill">Desktop</span>

43 </div>

44 

45 <p className="digest-feature-lede">Claude can now control your actual desktop from the Claude Code Desktop app: open native apps, click through the iOS simulator, drive hardware control panels, and verify changes on screen. It's off by default and asks before each action. Best for the things nothing else can reach: apps without an API, proprietary tools, anything that only exists as a GUI.</p>

46 

47 <Frame>

48 <img src="https://mintcdn.com/claude-code/CfffsX01JHFnIKvD/images/whats-new/computer-use.png?fit=max&auto=format&n=CfffsX01JHFnIKvD&q=85&s=d631de2017edafff463505f8ddbc0f51" alt="Claude Desktop settings with the Computer use toggle enabled, showing the option to let Claude take screenshots and control your keyboard and mouse in apps you allow" width="2376" height="1210" data-path="images/whats-new/computer-use.png" />

49 </Frame>

50 

51 <p className="digest-feature-try">Enable it in Settings, grant the OS permissions, then ask Claude to verify a change end to end:</p>

52 

53 ```text Claude Code theme={null}

54 > Open the iOS simulator, tap through the onboarding flow, and screenshot each step

55 ```

56 

57 <a className="digest-feature-link" href="/en/desktop#let-claude-use-your-computer">Computer use guide</a>

58</div>

59 

60<div className="digest-feature">

61 <div className="digest-feature-header">

62 <span className="digest-feature-title">PR auto-fix</span>

63 <span className="digest-feature-pill">Web</span>

64 </div>

65 

66 <p className="digest-feature-lede">Flip a switch when you open a PR and walk away. Claude watches CI, fixes the failures, handles the nits, and pushes until it's green. No more babysitting a PR through six rounds of lint errors.</p>

67 

68 <Frame>

69 <img src="https://mintcdn.com/claude-code/CfffsX01JHFnIKvD/images/whats-new/auto-fix.png?fit=max&auto=format&n=CfffsX01JHFnIKvD&q=85&s=c62b181c6c5d96929f0b43525f9f3584" alt="Claude Code web CI panel showing the Auto fix toggle enabled, with description 'Proactively fix CI failures and review comments'" width="960" height="444" data-path="images/whats-new/auto-fix.png" />

70 </Frame>

71 

72 <p className="digest-feature-try">After creating a PR on Claude Code web, toggle Auto fix in the CI panel.</p>

73 

74 <a className="digest-feature-link" href="/en/claude-code-on-the-web#auto-fix-pull-requests">Auto-fix pull requests</a>

75</div>

76 

77<div className="digest-feature">

78 <div className="digest-feature-header">

79 <span className="digest-feature-title">Transcript search</span>

80 <span className="digest-feature-pill">v2.1.83</span>

81 </div>

82 

83 <p className="digest-feature-lede">Press <code>/</code> in transcript mode to search your conversation. <code>n</code> and <code>N</code> step through matches. Finally a way to find that one Bash command Claude ran 400 messages ago.</p>

84 

85 <p className="digest-feature-try">Open transcript mode and search:</p>

86 

87 ```text Claude Code theme={null}

88 Ctrl+O # open transcript

89 /migrate # search for "migrate"

90 n # next match

91 N # previous match

92 ```

93 

94 <a className="digest-feature-link" href="/en/fullscreen#search-and-review-the-conversation">Fullscreen guide</a>

95</div>

96 

97<div className="digest-feature">

98 <div className="digest-feature-header">

99 <span className="digest-feature-title">PowerShell tool</span>

100 <span className="digest-feature-pill">preview</span>

101 <span className="digest-feature-pill">v2.1.84</span>

102 </div>

103 

104 <p className="digest-feature-lede">Windows gets a native PowerShell tool alongside Bash. Claude can run cmdlets, pipe objects, and work with Windows-native paths without translating everything through Git Bash.</p>

105 

106 <p className="digest-feature-try">Opt in from settings:</p>

107 

108 ```json .claude/settings.json {3} theme={null}

109 {

110 "env": {

111 "CLAUDE_CODE_USE_POWERSHELL_TOOL": "1"

112 }

113 }

114 ```

115 

116 <a className="digest-feature-link" href="/en/tools-reference#powershell-tool">PowerShell tool docs</a>

117</div>

118 

119<div className="digest-feature">

120 <div className="digest-feature-header">

121 <span className="digest-feature-title">Conditional hooks</span>

122 <span className="digest-feature-pill">v2.1.85</span>

123 </div>

124 

125 <p className="digest-feature-lede">Hooks can now declare an <code>if</code> field using permission rule syntax. Your pre-commit check only spawns for <code>Bash(git commit \*)</code> instead of every bash call, cutting the process overhead on busy sessions.</p>

126 

127 <p className="digest-feature-try">Scope a hook to git commits only:</p>

128 

129 ```json .claude/settings.json {5} theme={null}

130 {

131 "hooks": {

132 "PreToolUse": [{

133 "hooks": [{

134 "if": "Bash(git commit *)",

135 "type": "command",

136 "command": ".claude/hooks/lint-staged.sh"

137 }]

138 }]

139 }

140 }

141 ```

142 

143 <a className="digest-feature-link" href="/en/hooks">Hooks reference</a>

144</div>

145 

146<div className="digest-wins">

147 <p className="digest-wins-title">Other wins</p>

148 

149 <div className="digest-wins-grid">

150 <div>Plugin <code>userConfig</code> now public: prompt for settings at enable time, keychain-backed secrets</div>

151 <div>Pasted images insert <code>\[Image #N]</code> chips you can reference positionally</div>

152 <div><code>managed-settings.d/</code> drop-in directory for layered policy fragments</div>

153 <div><code>CwdChanged</code> and <code>FileChanged</code> hook events for direnv-style setups</div>

154 <div>Agents can declare <code>initialPrompt</code> in frontmatter to auto-submit a first turn</div>

155 <div><code>Ctrl+X Ctrl+E</code> opens your external editor, matching readline</div>

156 <div>Interrupting before any response restores your input automatically</div>

157 <div><code>/status</code> now works while Claude is responding</div>

158 <div>Deep links open in your preferred terminal, not first-detected</div>

159 <div>Idle-return nudge to <code>/clear</code> after 75+ minutes away</div>

160 <div>VS Code: rate limit banner, Esc-twice rewind picker</div>

161 </div>

162</div>

163 

164[Full changelog for v2.1.83–v2.1.85 →](/en/changelog#2-1-83)

whats-new/2026-w14.md +138 −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 14 · March 30 – April 3, 2026

6 

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 

9<div className="digest-meta">

10 <span>Releases <a href="/en/changelog#2-1-86">v2.1.86 → v2.1.91</a></span>

11 <span>5 features · March 30 – April 3</span>

12</div>

13 

14<div className="digest-feature">

15 <div className="digest-feature-header">

16 <span className="digest-feature-title">Computer use in the CLI</span>

17 <span className="digest-feature-pill">research preview</span>

18 </div>

19 

20 <p className="digest-feature-lede">Last week computer use landed in the Desktop app. This week it's in the CLI: Claude can open native apps, click through UI, test its own changes, and fix what breaks, all from your terminal. Web apps already had verification loops; native iOS, macOS, and other GUI-only apps didn't. Now they do. Best for closing the loop on apps and tools where there's no API to call. Still early; expect rough edges.</p>

21 

22 <Frame>

23 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/CfffsX01JHFnIKvD/images/whats-new/cli-computer-use.mp4?fit=max&auto=format&n=CfffsX01JHFnIKvD&q=85&s=c17a337902308d7c9121013ded0494db" data-path="images/whats-new/cli-computer-use.mp4" />

24 </Frame>

25 

26 <p className="digest-feature-try">Run <code>/mcp</code>, find <code>computer-use</code>, and toggle it on. Then ask Claude to verify a change end to end:</p>

27 

28 ```text Claude Code theme={null}

29 > Open the iOS simulator, tap through onboarding, and screenshot each step

30 ```

31 

32 <a className="digest-feature-link" href="/en/computer-use">Computer use guide</a>

33</div>

34 

35<div className="digest-feature">

36 <div className="digest-feature-header">

37 <span className="digest-feature-title">/powerup</span>

38 <span className="digest-feature-pill">v2.1.90</span>

39 </div>

40 

41 <p className="digest-feature-lede">Interactive lessons that teach Claude Code features through animated demos, right inside your terminal. Claude Code releases frequently, and features that would have changed how you work last month can slip by. Run <code>/powerup</code> once and you'll know what's there.</p>

42 

43 <Frame>

44 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/CfffsX01JHFnIKvD/images/whats-new/powerup.mp4?fit=max&auto=format&n=CfffsX01JHFnIKvD&q=85&s=fb88beddc0ecc8029da5ab029e4b28f1" data-path="images/whats-new/powerup.mp4" />

45 </Frame>

46 

47 <p className="digest-feature-try">Run it:</p>

48 

49 ```text Claude Code theme={null}

50 > /powerup

51 ```

52 

53 <a className="digest-feature-link" href="/en/commands">Commands reference</a>

54</div>

55 

56<div className="digest-feature">

57 <div className="digest-feature-header">

58 <span className="digest-feature-title">Flicker-free rendering</span>

59 <span className="digest-feature-pill">v2.1.89</span>

60 </div>

61 

62 <p className="digest-feature-lede">Opt into a new alt-screen renderer with virtualized scrollback. The prompt input stays pinned to the bottom, mouse selection works across long conversations, and the flicker on redraw is gone. Unset <code>CLAUDE\_CODE\_NO\_FLICKER</code> to roll back.</p>

63 

64 <Frame>

65 <video autoPlay muted loop playsInline className="w-full" src="https://mintcdn.com/claude-code/CfffsX01JHFnIKvD/images/whats-new/flicker-free.mp4?fit=max&auto=format&n=CfffsX01JHFnIKvD&q=85&s=7719e35e52a3f9734b0cf69edac333ad" data-path="images/whats-new/flicker-free.mp4" />

66 </Frame>

67 

68 <p className="digest-feature-try">Set the env var and restart Claude Code:</p>

69 

70 ```bash theme={null}

71 export CLAUDE_CODE_NO_FLICKER=1

72 claude

73 ```

74 

75 <a className="digest-feature-link" href="/en/fullscreen">Fullscreen rendering</a>

76</div>

77 

78<div className="digest-feature">

79 <div className="digest-feature-header">

80 <span className="digest-feature-title">MCP result-size override</span>

81 <span className="digest-feature-pill">v2.1.91</span>

82 </div>

83 

84 <p className="digest-feature-lede">MCP server authors can now raise the truncation cap on a specific tool by setting <code>anthropic/maxResultSizeChars</code> in the tool's <code>tools/list</code> entry, up to a hard ceiling of 500K characters. The cap used to be global, so tools that occasionally returned inherently large payloads like database schemas or full file trees hit the default limit and got persisted to disk with a file reference. Per-tool overrides keep those results inline when the tool really needs them.</p>

85 

86 <p className="digest-feature-try">Annotate the tool in your server's <code>tools/list</code> response:</p>

87 

88 ```json highlight={5} theme={null}

89 {

90 "name": "get_schema",

91 "description": "Returns the full database schema",

92 "_meta": {

93 "anthropic/maxResultSizeChars": 500000

94 }

95 }

96 ```

97 

98 <a className="digest-feature-link" href="/en/mcp#override-result-size-per-tool">MCP reference</a>

99</div>

100 

101<div className="digest-feature">

102 <div className="digest-feature-header">

103 <span className="digest-feature-title">Plugin executables on PATH</span>

104 <span className="digest-feature-pill">v2.1.91</span>

105 </div>

106 

107 <p className="digest-feature-lede">Place an executable in a <code>bin/</code> directory at your plugin root and Claude Code adds that directory to the Bash tool's <code>PATH</code> while the plugin is enabled. Claude can then invoke the binary as a bare command from any Bash tool call, with no absolute path or wrapper script needed. Handy for packaging CLI helpers next to the commands, agents, and hooks that call them.</p>

108 

109 <p className="digest-feature-try">Add a <code>bin/</code> directory at the plugin root:</p>

110 

111 ```text highlight={4, 5} theme={null}

112 my-plugin/

113 ├── .claude-plugin/

114 │ └── plugin.json

115 └── bin/

116 └── my-tool

117 ```

118 

119 <a className="digest-feature-link" href="/en/plugins-reference#file-locations-reference">Plugins reference</a>

120</div>

121 

122<div className="digest-wins">

123 <p className="digest-wins-title">Other wins</p>

124 

125 <div className="digest-wins-grid">

126 <div>Auto mode follow-ups: new <code>PermissionDenied</code> hook fires on classifier denials (return <code>retry: true</code> to let Claude try a different approach), and <code>/permissions</code> → Recent lets you retry manually with <code>r</code></div>

127 <div>New <code>defer</code> value for <code>permissionDecision</code> in <code>PreToolUse</code> hooks: <code>-p</code> sessions pause at a tool call and exit with a <code>deferred\_tool\_use</code> payload so an SDK app or custom UI can surface it, then resume with <code>--resume</code></div>

128 <div><code>/buddy</code>: hatch a small creature that watches you code (April 1st)</div>

129 <div><code>disableSkillShellExecution</code> setting blocks inline shell from skills, slash commands, and plugin commands</div>

130 <div>Edit tool now works on files viewed via <code>cat</code> or <code>sed -n</code> without a separate Read</div>

131 <div>Hook output over 50K saved to disk with a path + preview instead of injected into context</div>

132 <div>Thinking summaries off by default in interactive sessions (<code>showThinkingSummaries: true</code> to restore)</div>

133 <div>Voice mode: push-to-talk modifier combos, Windows WebSocket, macOS Apple Silicon mic permission</div>

134 <div><code>claude-cli://</code> deep links accept multi-line prompts (encoded <code>%0A</code>)</div>

135 </div>

136</div>

137 

138[Full changelog for v2.1.86–v2.1.91 →](/en/changelog#2-1-86)

zero-data-retention.md +66 −0 added

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# Zero data retention

6 

7> Learn about Zero Data Retention (ZDR) for Claude Code on Claude for Enterprise, including scope, disabled features, and how to request enablement.

8 

9Zero Data Retention (ZDR) is available for Claude Code when used through Claude for Enterprise. When ZDR is enabled, prompts and model responses generated during Claude Code sessions are processed in real time and not stored by Anthropic after the response is returned, except where needed to comply with law or combat misuse.

10 

11ZDR on Claude for Enterprise gives enterprise customers the ability to use Claude Code with zero data retention and access administrative capabilities:

12 

13* Cost controls per user

14* [Analytics](/en/analytics) dashboard

15* [Server-managed settings](/en/server-managed-settings)

16* Audit logs

17 

18ZDR for Claude Code on Claude for Enterprise applies only to Anthropic's direct platform. For Claude deployments on AWS Bedrock, Google Vertex AI, or Microsoft Foundry, refer to those platforms' data retention policies.

19 

20## ZDR scope

21 

22ZDR covers Claude Code inference on Claude for Enterprise.

23 

24<Warning>

25 ZDR is enabled on a per-organization basis. Each new organization requires ZDR to be enabled separately by your Anthropic account team. ZDR does not automatically apply to new organizations created under the same account. Contact your account team to enable ZDR for any new organizations.

26</Warning>

27 

28### What ZDR covers

29 

30ZDR covers model inference calls made through Claude Code on Claude for Enterprise. When you use Claude Code in your terminal, the prompts you send and the responses Claude generates are not retained by Anthropic. This applies regardless of which Claude model is used.

31 

32### What ZDR does not cover

33 

34ZDR does not extend to the following, even for organizations with ZDR enabled. These features follow [standard data retention policies](/en/data-usage#data-retention):

35 

36| Feature | Details |

37| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

38| Chat on claude.ai | Chat conversations through the Claude for Enterprise web interface are not covered by ZDR. |

39| Cowork | Cowork sessions are not covered by ZDR. |

40| Claude Code Analytics | Does not store prompts or model responses, but collects productivity metadata such as account emails and usage statistics. Contribution metrics are not available for ZDR organizations; the [analytics dashboard](/en/analytics) shows usage metrics only. |

41| User and seat management | Administrative data such as account emails and seat assignments is retained under standard policies. |

42| Third-party integrations | Data processed by third-party tools, MCP servers, or other external integrations is not covered by ZDR. Review those services' data handling practices independently. |

43 

44## Features disabled under ZDR

45 

46When ZDR is enabled for a Claude Code organization on Claude for Enterprise, certain features that require storing prompts or completions are automatically disabled at the backend level:

47 

48| Feature | Reason |

49| ------------------------------------------------------------------- | ----------------------------------------------------------------------- |

50| [Claude Code on the Web](/en/claude-code-on-the-web) | Requires server-side storage of conversation history. |

51| [Remote sessions](/en/desktop#remote-sessions) from the Desktop app | Requires persistent session data that includes prompts and completions. |

52| Feedback submission (`/feedback`) | Submitting feedback sends conversation data to Anthropic. |

53 

54These features are blocked in the backend regardless of client-side display. If you see a disabled feature in the Claude Code terminal during startup, attempting to use it returns an error indicating the organization's policies do not allow that action.

55 

56Future features may also be disabled if they require storing prompts or completions.

57 

58## Data retention for policy violations

59 

60Even with ZDR enabled, Anthropic may retain data where required by law or to address Usage Policy violations. If a session is flagged for a policy violation, Anthropic may retain the associated inputs and outputs for up to 2 years, consistent with Anthropic's standard ZDR policy.

61 

62## Request ZDR

63 

64To request ZDR for Claude Code on Claude for Enterprise, contact your Anthropic account team. Your account team will submit the request internally, and Anthropic will review and enable ZDR on your organization after confirming eligibility. All enablement actions are audit-logged.

65 

66If you are currently using ZDR for Claude Code via pay-as-you-go API keys, you can transition to Claude for Enterprise to gain access to administrative features while maintaining ZDR for Claude Code. Contact your account team to coordinate the migration.