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

agent-teams.md +387 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Orchestrate teams of Claude Code sessions

6 

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

8 

9<Warning>

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

11</Warning>

12 

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

14 

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

16 

17This page covers:

18 

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

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

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

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

23 

24## When to use agent teams

25 

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

27 

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

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

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

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

32 

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

34 

35### Compare with subagents

36 

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

38 

39| | Subagents | Agent teams |

40| :---------------- | :----------------------------------------------- | :-------------------------------------------------- |

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

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

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

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

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

46 

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

48 

49## Enable agent teams

50 

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

52 

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

54{

55 "env": {

56 "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"

57 }

58}

59```

60 

61## Start your first agent team

62 

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

64 

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

66 

67```

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

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

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

71```

72 

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

74 

75The lead's terminal lists all teammates and what they're working on. Use Shift+Up/Down to select a teammate and message them directly.

76 

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

78 

79## Control your agent team

80 

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

82 

83### Choose a display mode

84 

85Agent teams support two display modes:

86 

87* **In-process**: all teammates run inside your main terminal. Use Shift+Up/Down to select a teammate and type to message them directly. Works in any terminal, no extra setup required.

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

89 

90<Note>

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

92</Note>

93 

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

95 

96```json theme={null}

97{

98 "teammateMode": "in-process"

99}

100```

101 

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

103 

104```bash theme={null}

105claude --teammate-mode in-process

106```

107 

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

109 

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

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

112 

113### Specify teammates and models

114 

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

116 

117```

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

119Use Sonnet for each teammate.

120```

121 

122### Require plan approval for teammates

123 

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

125 

126```

127Spawn an architect teammate to refactor the authentication module.

128Require plan approval before they make any changes.

129```

130 

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

132 

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

134 

135### Use delegate mode

136 

137Without delegate mode, the lead sometimes starts implementing tasks itself instead of waiting for teammates. Delegate mode prevents this by restricting the lead to coordination-only tools: spawning, messaging, shutting down teammates, and managing tasks.

138 

139This is useful when you want the lead to focus entirely on orchestration, such as breaking down work, assigning tasks, and synthesizing results, without touching code directly.

140 

141To enable it, start a team first, then press Shift+Tab to cycle into delegate mode.

142 

143### Talk to teammates directly

144 

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

146 

147* **In-process mode**: use Shift+Up/Down to select a teammate, 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.

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

149 

150### Assign and claim tasks

151 

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

153 

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

155 

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

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

158 

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

160 

161### Shut down teammates

162 

163To gracefully end a teammate's session:

164 

165```

166Ask the researcher teammate to shut down

167```

168 

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

170 

171### Clean up the team

172 

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

174 

175```

176Clean up the team

177```

178 

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

180 

181<Warning>

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

183</Warning>

184 

185### Enforce quality gates with hooks

186 

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

188 

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

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

191 

192## How agent teams work

193 

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

195 

196### How Claude starts agent teams

197 

198There are two ways agent teams get started:

199 

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

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

202 

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

204 

205### Architecture

206 

207An agent team consists of:

208 

209| Component | Role |

210| :------------ | :----------------------------------------------------------------------------------------- |

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

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

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

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

215 

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

217 

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

219 

220Teams and tasks are stored locally:

221 

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

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

224 

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

226 

227### Permissions

228 

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

230 

231### Context and communication

232 

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

234 

235**How teammates share information:**

236 

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

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

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

240 

241**Teammate messaging:**

242 

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

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

245 

246### Token usage

247 

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

249 

250## Use case examples

251 

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

253 

254### Run a parallel code review

255 

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

257 

258```

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

260- One focused on security implications

261- One checking performance impact

262- One validating test coverage

263Have them each review and report findings.

264```

265 

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

267 

268### Investigate with competing hypotheses

269 

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

271 

272```

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

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

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

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

277```

278 

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

280 

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

282 

283## Best practices

284 

285### Give teammates enough context

286 

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

288 

289```

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

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

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

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

294```

295 

296### Size tasks appropriately

297 

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

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

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

301 

302<Tip>

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

304</Tip>

305 

306### Wait for teammates to finish

307 

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

309 

310```

311Wait for your teammates to complete their tasks before proceeding

312```

313 

314### Start with research and review

315 

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

317 

318### Avoid file conflicts

319 

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

321 

322### Monitor and steer

323 

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

325 

326## Troubleshooting

327 

328### Teammates not appearing

329 

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

331 

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

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

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

335 ```bash theme={null}

336 which tmux

337 ```

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

339 

340### Too many permission prompts

341 

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

343 

344### Teammates stopping on errors

345 

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

347 

348* Give them additional instructions directly

349* Spawn a replacement teammate to continue the work

350 

351### Lead shuts down before work is done

352 

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

354 

355### Orphaned tmux sessions

356 

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

358 

359```bash theme={null}

360tmux ls

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

362```

363 

364## Limitations

365 

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

367 

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

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

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

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

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

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

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

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

376 

377<Tip>

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

379</Tip>

380 

381## Next steps

382 

383Explore related approaches for parallel work and delegation:

384 

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

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

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

amazon-bedrock.md +32 −26

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


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

49```53```

50 54 

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

56 

57```bash theme={null}

58aws login

59```

60 

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

62 

63**Option E: Bedrock API keys**

52 64 

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

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


75 87 

76##### Configuration settings explained88##### Configuration settings explained

77 89 

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.90**`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 91 

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:92**`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 93 

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

83{95{


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

103```115```

104 116 

105**For VS Code Extension users**: Configure environment variables in the VS Code extension settings instead of exporting them in your shell. See [Using Third-Party Providers in VS Code](/en/vs-code#using-third-party-providers-vertex-and-bedrock) for detailed instructions. All environment variables shown in this guide should work when configured through the VS Code extension settings.

106 

107When enabling Bedrock for Claude Code, keep the following in mind:117When enabling Bedrock for Claude Code, keep the following in mind:

108 118 

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


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

121 131 

122<Note>132<Note>

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

124</Note>134</Note>

125 135 

126To customize models, use one of these methods:136To customize models, use one of these methods:


137export DISABLE_PROMPT_CACHING=1147export DISABLE_PROMPT_CACHING=1

138```148```

139 149 

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

141 [Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) may not be available in all regions

142</Note>

143 

144### 5. Output token configuration

145 

146When using Claude Code with Amazon Bedrock, we recommend the following token settings:

147 

148```bash theme={null}

149# Recommended output token settings for Bedrock

150export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096

151export MAX_THINKING_TOKENS=1024

152```

153 

154**Why these values:**

155 

156* **`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.

157 

158* **`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.

159 151 

160## IAM configuration152## IAM configuration

161 153 


205 We recommend creating a dedicated AWS account for Claude Code to simplify cost tracking and access control.197 We recommend creating a dedicated AWS account for Claude Code to simplify cost tracking and access control.

206</Note>198</Note>

207 199 

200## AWS Guardrails

201 

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

203 

204Example configuration:

205 

206```json theme={null}

207{

208 "env": {

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

210 }

211}

212```

213 

208## Troubleshooting214## Troubleshooting

209 215 

210If you encounter region issues:216If you encounter region issues:

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-teams-and-enterprise) |

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

15 

16## Access analytics for Teams and Enterprise

17 

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

19 

20The Teams and Enterprise dashboard includes:

21 

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

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

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

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

26 

27### Enable contribution metrics

6 28 

7<Note>29<Note>

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

9</Note>31</Note>

10 32 

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

34 

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

36 

37<Warning>

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

39</Warning>

40 

41<Steps>

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

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

44 </Step>

45 

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

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

48 </Step>

49 

50 <Step title="Enable GitHub analytics">

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

52 </Step>

53 

54 <Step title="Authenticate with GitHub">

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

56 </Step>

57</Steps>

12 58 

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

14 60 

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

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

16 63 

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

18* **Owner**65 

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

20* **Admin**

21* **Developer**

22 67 

23<Note>68<Note>

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

25</Note>70</Note>

26 71 

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

73 

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

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

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

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

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

79 

80### Explore the charts

81 

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

83 

84#### Track adoption

85 

86The Adoption chart shows daily usage trends:

87 

88* **users**: daily active users

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

90 

91#### Measure PRs per user

92 

93This chart displays individual developer activity over time:

94 

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

96* **users**: daily active users

97 

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

99 

100#### View pull requests breakdown

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/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/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 +104 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Authentication

6 

7> Learn how to configure user authentication and credential management for Claude Code in your organization.

8 

9## Authentication methods

10 

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

12 

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

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

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

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

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

18 

19### Claude for Teams or Enterprise

20 

21[Claude for Teams](https://claude.com/pricing#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales) provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management.

22 

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

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

25 

26<Steps>

27 <Step title="Subscribe">

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

29 </Step>

30 

31 <Step title="Invite team members">

32 Invite team members from the admin dashboard.

33 </Step>

34 

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

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

37 </Step>

38</Steps>

39 

40### Claude Console authentication

41 

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

43 

44<Steps>

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

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

47 </Step>

48 

49 <Step title="Add users">

50 You can add users through either method:

51 

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

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

54 </Step>

55 

56 <Step title="Assign roles">

57 When inviting users, assign one of:

58 

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

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

61 </Step>

62 

63 <Step title="Users complete setup">

64 Each invited user needs to:

65 

66 * Accept the Console invite

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

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

69 * Log in with Console account credentials

70 </Step>

71</Steps>

72 

73### Cloud provider authentication

74 

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

76 

77<Steps>

78 <Step title="Follow provider setup">

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

80 </Step>

81 

82 <Step title="Distribute configuration">

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

84 </Step>

85 

86 <Step title="Install Claude Code">

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

88 </Step>

89</Steps>

90 

91## Credential management

92 

93Claude Code securely manages your authentication credentials:

94 

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

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

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

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

99 

100## See also

101 

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

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

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

best-practices.md +599 −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. 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, or name it `CLAUDE.local.md` and `.gitignore` it

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

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

201 

202### Configure permissions

203 

204<Tip>

205 Use `/permissions` to allowlist safe commands or `/sandbox` for OS-level isolation. This reduces interruptions while keeping you in control.

206</Tip>

207 

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

209 

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

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

212 

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

214 

215<Warning>

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

217</Warning>

218 

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

220 

221### Use CLI tools

222 

223<Tip>

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

225</Tip>

226 

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

228 

229Claude 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.`

230 

231### Connect MCP servers

232 

233<Tip>

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

235</Tip>

236 

237With [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.

238 

239### Set up hooks

240 

241<Tip>

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

243</Tip>

244 

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

246 

247Claude can write hooks for you. Try prompts like *"Write a hook that runs eslint after every file edit"* or *"Write a hook that blocks writes to the migrations folder."* Run `/hooks` for interactive configuration, or edit `.claude/settings.json` directly.

248 

249### Create skills

250 

251<Tip>

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

253</Tip>

254 

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

256 

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

258 

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

260---

261name: api-conventions

262description: REST API design conventions for our services

263---

264# API Conventions

265- Use kebab-case for URL paths

266- Use camelCase for JSON properties

267- Always include pagination for list endpoints

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

269```

270 

271Skills can also define repeatable workflows you invoke directly:

272 

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

274---

275name: fix-issue

276description: Fix a GitHub issue

277disable-model-invocation: true

278---

279Analyze and fix the GitHub issue: $ARGUMENTS.

280 

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

2822. Understand the problem described in the issue

2833. Search the codebase for relevant files

2844. Implement the necessary changes to fix the issue

2855. Write and run tests to verify the fix

2866. Ensure code passes linting and type checking

2877. Create a descriptive commit message

2888. Push and create a PR

289```

290 

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

292 

293### Create custom subagents

294 

295<Tip>

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

297</Tip>

298 

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

300 

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

302---

303name: security-reviewer

304description: Reviews code for security vulnerabilities

305tools: Read, Grep, Glob, Bash

306model: opus

307---

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

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

310- Authentication and authorization flaws

311- Secrets or credentials in code

312- Insecure data handling

313 

314Provide specific line references and suggested fixes.

315```

316 

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

318 

319### Install plugins

320 

321<Tip>

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

323</Tip>

324 

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

326 

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

328 

329***

330 

331## Communicate effectively

332 

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

334 

335### Ask codebase questions

336 

337<Tip>

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

339</Tip>

340 

341When 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:

342 

343* How does logging work?

344* How do I make a new API endpoint?

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

346* What edge cases does `CustomerOnboardingFlowImpl` handle?

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

348 

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

350 

351### Let Claude interview you

352 

353<Tip>

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

355</Tip>

356 

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

358 

359```

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

361 

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

363 

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

365```

366 

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

368 

369***

370 

371## Manage your session

372 

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

374 

375### Course-correct early and often

376 

377<Tip>

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

379</Tip>

380 

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

382 

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

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

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

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

387 

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

389 

390### Manage context aggressively

391 

392<Tip>

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

394</Tip>

395 

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

397 

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

399 

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

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

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

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

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

405 

406### Use subagents for investigation

407 

408<Tip>

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

410</Tip>

411 

412Since 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:

413 

414```

415Use subagents to investigate how our authentication system handles token

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

417```

418 

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

420 

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

422 

423```

424use a subagent to review this code for edge cases

425```

426 

427### Rewind with checkpoints

428 

429<Tip>

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

431</Tip>

432 

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

434 

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

436 

437<Warning>

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

439</Warning>

440 

441### Resume conversations

442 

443<Tip>

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

445</Tip>

446 

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

448 

449```bash theme={null}

450claude --continue # Resume the most recent conversation

451claude --resume # Select from recent conversations

452```

453 

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

455 

456***

457 

458## Automate and scale

459 

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

461 

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

463 

464### Run headless mode

465 

466<Tip>

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

468</Tip>

469 

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

471 

472```bash theme={null}

473# One-off queries

474claude -p "Explain what this project does"

475 

476# Structured output for scripts

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

478 

479# Streaming for real-time processing

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

481```

482 

483### Run multiple Claude sessions

484 

485<Tip>

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

487</Tip>

488 

489There are three main ways to run parallel sessions:

490 

491* [Claude Desktop](/en/desktop): Manage multiple local sessions visually. Each session gets its own isolated worktree.

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

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

494 

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

496 

497For example, use a Writer/Reviewer pattern:

498 

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

500| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

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

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

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

504 

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

506 

507### Fan out across files

508 

509<Tip>

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

511</Tip>

512 

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

514 

515<Steps>

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

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

518 </Step>

519 

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

521 ```bash theme={null}

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

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

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

525 done

526 ```

527 </Step>

528 

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

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

531 </Step>

532</Steps>

533 

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

535 

536```bash theme={null}

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

538```

539 

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

541 

542### Safe Autonomous Mode

543 

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

545 

546<Warning>

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

548 

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

550</Warning>

551 

552***

553 

554## Avoid common failure patterns

555 

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

557 

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

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

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

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

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

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

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

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

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

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

568 

569***

570 

571## Develop your intuition

572 

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

574 

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

576 

577Pay 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?

578 

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

580 

581## Related resources

582 

583<CardGroup cols={2}>

584 <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">

585 Understand the agentic loop, tools, and context management

586 </Card>

587 

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

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

590 </Card>

591 

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

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

594 </Card>

595 

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

597 Store project conventions and persistent context

598 </Card>

599</CardGroup>

checkpointing.md +34 −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# 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 


61## See also85## See also

62 86 

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

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

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

chrome.md +223 −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 only. 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/) browser

34* [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher

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 

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

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

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

186 

187### Browser not responding

188 

189If Claude's browser commands stop working:

190 

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

1922. Ask Claude to create a new tab and try again

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

194 

195### Connection drops during long sessions

196 

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

198 

199### Windows-specific issues

200 

201On Windows, you may encounter:

202 

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

204* **Native messaging host errors**: if the native messaging host crashes on startup, try reinstalling Claude Code to regenerate the host configuration.

205 

206### Common error messages

207 

208These are the most frequently encountered errors and how to resolve them:

209 

210| Error | Cause | Fix |

211| ------------------------------------ | ------------------------------------------------ | --------------------------------------------------------------- |

212| "Browser extension is not connected" | Native messaging host cannot reach the extension | Restart Chrome and Claude Code, then run `/chrome` to reconnect |

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

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

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

216 

217## See also

218 

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

220* [CLI reference](/en/cli-reference): command-line flags including `--chrome`

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

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

223* [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 iOS app 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 move between local and remote development: [send tasks from your terminal to run on the web](#from-terminal-to-web) with the `&` prefix, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally.

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* **Team premium seat users**33* **Team users**

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

34 35 

35## Getting started36## Getting started

36 37 


393. Install the Claude GitHub app in your repositories403. Install the Claude GitHub app in your repositories

404. Select your default environment414. Select your default environment

415. Submit your coding task425. Submit your coding task

426. Review changes and create a pull request in GitHub436. Review changes in diff view, iterate with comments, then create a pull request

43 44 

44## How it works45## How it works

45 46 


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

536. **Results**: Changes are pushed to a branch, ready for pull request creation546. **Results**: Changes are pushed to a branch, ready for pull request creation

54 55 

56## Review changes with diff view

57 

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

59 

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

61 

62From the diff view, you can:

63 

64* Review changes file by file

65* Comment on specific changes to request modifications

66* Continue iterating with Claude based on what you see

67 

68This lets you refine changes through multiple rounds of feedback without creating draft PRs or switching to GitHub.

69 

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

56 71 

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

73 

74<Note>

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

76</Note>

77 

78### From terminal to web

79 

80Start a message with `&` inside Claude Code to send a task to run on the web:

81 

82```

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

84```

85 

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

87 

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

89 

90```bash theme={null}

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

92```

93 

94#### Tips for background tasks

95 

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

97 

98```bash theme={null}

99claude --permission-mode plan

100```

101 

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

103 

104```

105& Execute the migration plan we discussed

106```

107 

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

109 

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

111 

112```

113& Fix the flaky test in auth.spec.ts

114& Update the API documentation

115& Refactor the logger to use structured output

116```

117 

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

119 

57### From web to terminal120### From web to terminal

58 121 

59After starting a task on the web:122There are several ways to pull a web session into your terminal:

123 

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

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

126* **From `/tasks`**: Run `/tasks` to see your background sessions, then press `t` to teleport into one

127* **From the web interface**: Click "Open in CLI" to copy a command you can paste into your terminal

128 

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

130 

131#### Requirements for teleporting

132 

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

134 

135| Requirement | Details |

136| ------------------ | ---------------------------------------------------------------------------------------------------------------------- |

137| Clean git state | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed. |

138| Correct repository | You must run `--teleport` from a checkout of the same repository, not a fork. |

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

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

141 

142### Sharing sessions

143 

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

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

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

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

60 148 

611. Click the "Open in CLI" button149#### Sharing from an Enterprise or Teams account

622. Paste and run the command in your terminal in a checkout of the repo150 

633. Any existing local changes will be stashed, and the remote session will be loaded151For Enterprise and Teams accounts, the two visibility options are **Private**

644. Continue working locally152and **Team**. Team visibility makes the session visible to other members of your

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

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

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

156sessions are automatically shared with Team visibility.

157 

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

159 

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

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

162into claude.ai.

163 

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

165code and credentials from private GitHub repositories. Repository access

166verification is not enabled by default.

167 

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

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

65 170 

66## Cloud environment171## Cloud environment

67 172 


127 232 

128**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.233**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.

129 234 

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

236 

130<Note>237<Note>

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

132 239 


138 245 

139### Dependency management246### Dependency management

140 247 

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

249 

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

142 251 

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

144{253{


160 269 

161Create the corresponding script at `scripts/install_pkgs.sh`:270Create the corresponding script at `scripts/install_pkgs.sh`:

162 271 

163```bash theme={null}

164#!/bin/bash

165npm install

166pip install -r requirements.txt

167exit 0

168```

169 

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

171 

172#### Local vs remote execution

173 

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

175 

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

177#!/bin/bash273#!/bin/bash

178 274 

179# Example: Only run in remote environments275# Only run in remote environments

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

181 exit 0277 exit 0

182fi278fi

183 279 

184npm install280npm install

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

282exit 0

186```283```

187 284 

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

286 

287#### Persist environment variables

189 288 

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

290 

291#### Dependency management limitations

292 

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

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

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

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

191 297 

192## Network access and security298## Network access and security

193 299 


223 329 

224* api.anthropic.com330* api.anthropic.com

225* statsig.anthropic.com331* statsig.anthropic.com

332* platform.claude.com

333* code.claude.com

226* claude.ai334* claude.ai

227 335 

228#### Version Control336#### Version Control


230* github.com338* github.com

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

232* api.github.com340* api.github.com

341* npm.pkg.github.com

233* raw\.githubusercontent.com342* raw\.githubusercontent.com

343* pkg-npm.githubusercontent.com

234* objects.githubusercontent.com344* objects.githubusercontent.com

235* codeload.github.com345* codeload.github.com

236* avatars.githubusercontent.com346* avatars.githubusercontent.com


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

253* production.cloudflare.docker.com363* production.cloudflare.docker.com

254* download.docker.com364* download.docker.com

365* gcr.io

255* \*.gcr.io366* \*.gcr.io

256* ghcr.io367* ghcr.io

257* mcr.microsoft.com368* mcr.microsoft.com

258* \*.data.mcr.microsoft.com369* \*.data.mcr.microsoft.com

370* public.ecr.aws

259 371 

260#### Cloud Platforms372#### Cloud Platforms

261 373 


276* dot.net388* dot.net

277* visualstudio.com389* visualstudio.com

278* dev.azure.com390* dev.azure.com

391* \*.amazonaws.com

392* \*.api.aws

279* oracle.com393* oracle.com

280* [www.oracle.com](http://www.oracle.com)394* [www.oracle.com](http://www.oracle.com)

281* java.com395* java.com


325 439 

326* crates.io440* crates.io

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

442* index.crates.io

328* static.crates.io443* static.crates.io

329* rustup.rs444* rustup.rs

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


350* gradle.org465* gradle.org

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

352* services.gradle.org467* services.gradle.org

468* plugins.gradle.org

469* kotlin.org

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

353* spring.io471* spring.io

354* repo.spring.io472* repo.spring.io

355 473 


423* statsig.com541* statsig.com

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

425* api.statsig.com543* api.statsig.com

544* sentry.io

426* \*.sentry.io545* \*.sentry.io

546* http-intake.logs.datadoghq.com

547* \*.datadoghq.com

548* \*.datadoghq.eu

427 549 

428#### Content Delivery & Mirrors550#### Content Delivery & Mirrors

429 551 

552* sourceforge.net

430* \*.sourceforge.net553* \*.sourceforge.net

431* packagecloud.io554* packagecloud.io

432* \*.packagecloud.io555* \*.packagecloud.io


438* json.schemastore.org561* json.schemastore.org

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

440 563 

564#### Model Context Protocol

565 

566* \*.modelcontextprotocol.io

567 

441<Note>568<Note>

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

443</Note>570</Note>


473 600 

474## Best practices601## Best practices

475 602 

4761. **Use Claude Code hooks**: Configure [sessionStart hooks](/en/hooks#sessionstart) to automate environment setup and dependency installation.6031. **Use Claude Code hooks**: Configure [SessionStart hooks](/en/hooks#sessionstart) to automate environment setup and dependency installation.

4772. **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.6042. **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.

478 605 

479## Related resources606## Related resources

cli-reference.md +69 −34

Details

1> ## Documentation Index

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

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

4 

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


5## CLI commands9## CLI commands

6 10 

7| Command | Description | Example |11| Command | Description | Example |

8| :--------------------------------- | :--------------------------------------------- | :------------------------------------------------ |12| :------------------------------ | :----------------------------------------------------- | :------------------------------------------------ |

9| `claude` | Start interactive REPL | `claude` |13| `claude` | Start interactive REPL | `claude` |

10| `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` |14| `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` |

11| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |15| `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"` |16| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |

13| `claude -c` | Continue most recent conversation | `claude -c` |17| `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"` |18| `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"` |19| `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` |20| `claude update` | Update to latest version | `claude update` |

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

18 22 


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

22 26 

23| Flag | Description | Example |27| Flag | Description | Example |

24| :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------- |28| :------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- |

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

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

26| `--agents` | Define custom [subagents](/en/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |31| `--agents` | Define custom [subagents](/en/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |

27| `--allowedTools` | A list of tools that should be allowed without prompting the user for permission, in addition to [settings.json files](/en/settings) | `"Bash(git log:*)" "Bash(git diff:*)" "Read"` |32| `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |

28| `--disallowedTools` | A list of tools that should be disallowed without prompting the user for permission, in addition to [settings.json files](/en/settings) | `"Bash(git log:*)" "Bash(git diff:*)" "Edit"` |33| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"` |

29| `--print`, `-p` | Print response without interactive mode (see [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) for programmatic usage details) | `claude -p "query"` |34| `--append-system-prompt` | Append custom text to the end of the default system prompt (works in both interactive and print modes) | `claude --append-system-prompt "Always use TypeScript"` |

30| `--system-prompt` | Replace the entire system prompt with custom text (works in both interactive and print modes; added in v2.0.14) | `claude --system-prompt "You are a Python expert"` |35| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt (print mode only) | `claude -p --append-system-prompt-file ./extra-rules.txt "query"` |

31| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt (print mode only; added in v1.0.54) | `claude -p --system-prompt-file ./custom-prompt.txt "query"` |36| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |

32| `--append-system-prompt` | Append custom text to the end of the default system prompt (works in both interactive and print modes; added in v1.0.55) | `claude --append-system-prompt "Always use TypeScript"` |37| `--chrome` | Enable [Chrome browser integration](/en/chrome) for web automation and testing | `claude --chrome` |

33| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |38| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` |

34| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |39| `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` |

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

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

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

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

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

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

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

47| `--init` | Run initialization hooks and start interactive mode | `claude --init` |

48| `--init-only` | Run initialization hooks and exit (no interactive session) | `claude --init-only` |

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

36| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |50| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |

37| `--max-turns` | Limit the number of agentic turns in non-interactive mode | `claude -p --max-turns 3 "query"` |51| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](https://platform.claude.com/docs/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |

52| `--maintenance` | Run maintenance hooks and exit | `claude --maintenance` |

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

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

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

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

39| `--permission-mode` | Begin in a specified [permission mode](/en/iam#permission-modes) | `claude --permission-mode plan` |57| `--no-chrome` | Disable [Chrome browser integration](/en/chrome) for this session | `claude --no-chrome` |

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

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

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

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

41| `--resume` | Resume a specific session by ID, or by choosing in interactive mode | `claude --resume abc123 "query"` |62| `--plugin-dir` | Load plugins from directories for this session only (repeatable) | `claude --plugin-dir ./my-plugins` |

42| `--continue` | Load the most recent conversation in the current directory | `claude --continue` |63| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |

43| `--dangerously-skip-permissions` | Skip permission prompts (use with caution) | `claude --dangerously-skip-permissions` |64| `--remote` | Create a new [web session](/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |

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

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

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

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

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

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

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

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

73| `--teammate-mode` | Set how [agent team](/en/agent-teams) teammates display: `auto` (default), `in-process`, or `tmux`. See [set up agent teams](/en/agent-teams#set-up-agent-teams) | `claude --teammate-mode in-process` |

74| `--tools` | Restrict which built-in tools Claude can use (works in both interactive and print modes). Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |

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

76| `--version`, `-v` | Output the version number | `claude -v` |

44 77 

45<Tip>78<Tip>

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


52The `--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:85The `--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:

53 86 

54| Field | Required | Description |87| Field | Required | Description |

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

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

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

58| `tools` | No | Array of specific tools the subagent can use (e.g., `["Read", "Edit", "Bash"]`). If omitted, inherits all tools |91| `tools` | No | Array of specific tools the subagent can use, for example `["Read", "Edit", "Bash"]`. If omitted, inherits all tools. Supports [`Task(agent_type)`](/en/sub-agents#restrict-which-subagents-can-be-spawned) syntax |

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

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

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

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

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

60 97 

61Example:98Example:

62 99 


79 116 

80### System prompt flags117### System prompt flags

81 118 

82Claude Code provides three flags for customizing the system prompt, each serving a different purpose:119Claude Code provides four flags for customizing the system prompt, each serving a different purpose:

83 120 

84| Flag | Behavior | Modes | Use Case |121| Flag | Behavior | Modes | Use Case |

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

86| `--system-prompt` | **Replaces** entire default prompt | Interactive + Print | Complete control over Claude's behavior and instructions |123| `--system-prompt` | **Replaces** entire default prompt | Interactive + Print | Complete control over Claude's behavior and instructions |

87| `--system-prompt-file` | **Replaces** with file contents | Print only | Load prompts from files for reproducibility and version control |124| `--system-prompt-file` | **Replaces** with file contents | Print only | Load prompts from files for reproducibility and version control |

88| `--append-system-prompt` | **Appends** to default prompt | Interactive + Print | Add specific instructions while keeping default Claude Code behavior |125| `--append-system-prompt` | **Appends** to default prompt | Interactive + Print | Add specific instructions while keeping default Claude Code behavior |

126| `--append-system-prompt-file` | **Appends** file contents to default prompt | Print only | Load additional instructions from files while keeping defaults |

89 127 

90**When to use each:**128**When to use each:**

91 129 


104 claude --append-system-prompt "Always use TypeScript and include JSDoc comments"142 claude --append-system-prompt "Always use TypeScript and include JSDoc comments"

105 ```143 ```

106 144 

107<Note>145* **`--append-system-prompt-file`**: Use when you want to append instructions from a file while keeping Claude Code's defaults. Useful for version-controlled additions.

108 `--system-prompt` and `--system-prompt-file` are mutually exclusive. You cannot use both flags simultaneously.146 ```bash theme={null}

109</Note>147 claude -p --append-system-prompt-file ./prompts/style-rules.txt "Review this PR"

148 ```

110 149 

111<Tip>150`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag.

112 For most use cases, `--append-system-prompt` is recommended as it preserves Claude Code's built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt.

113</Tip>

114 151 

115For detailed information about print mode (`-p`) including output formats,152For most use cases, `--append-system-prompt` or `--append-system-prompt-file` is recommended as they preserve Claude Code's built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt.

116streaming, verbose logging, and programmatic usage, see the

117[SDK documentation](https://docs.claude.com/en/docs/agent-sdk).

118 153 

119## See also154## See also

120 155 

156* [Chrome extension](/en/chrome) - Browser automation and web testing

121* [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features157* [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features

122* [Slash commands](/en/slash-commands) - Interactive session commands

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

124* [Common workflows](/en/common-workflows) - Advanced workflows and patterns159* [Common workflows](/en/common-workflows) - Advanced workflows and patterns

125* [Settings](/en/settings) - Configuration options160* [Settings](/en/settings) - Configuration options

126* [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) - Programmatic usage and integrations161* [Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview) - Programmatic usage and integrations

common-workflows.md +137 −225

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 


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


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

179 > review my recent code changes for security issues184 > review my recent code changes for security issues


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 


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/settings#tools-available-to-claude) 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`. When an [agent team](/en/agent-teams) is active, the cycle also includes Delegate Mode.

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


263> I need to refactor our authentication system to use OAuth2. Create a detailed migration plan.268> I 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 

268```273```

269> What about backward compatibility?274> What about backward compatibility?

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

271```276```

272 277 

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

279 

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

274 281 

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


315 </Step>322 </Step>

316</Steps>323</Steps>

317 324 

318<Tip>325Claude 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 326 

321 * Ask for tests that cover edge cases and error conditions327For 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 328 

326***329***

327 330 

328## Create pull requests331## Create pull requests

329 332 

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

334 

335```

336> /commit-push-pr

337```

338 

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

340 

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

331 342 

332<Steps>343<Steps>

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


336 ```347 ```

337 </Step>348 </Step>

338 349 

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

340 ```351 ```

341 > create a pr352 > create a pr

342 ```353 ```


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

348 ```359 ```

349 </Step>360 </Step>

350 

351 <Step title="Add testing details">

352 ```

353 > add information about how these changes were tested

354 ```

355 </Step>

356</Steps>361</Steps>

357 362 

358<Tip>363When you create a PR using `gh pr create`, the session is automatically linked to that PR. You can resume it later with `claude --from-pr <number>`.

359 Tips:

360 364 

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

362 * Review Claude's generated PR before submitting366 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>367</Tip>

365 368 

366## Handle documentation369## Handle documentation


458 * Include screenshots of errors, UI designs, or diagrams for better context461 * Include screenshots of errors, UI designs, or diagrams for better context

459 * You can work with multiple images in a conversation462 * You can work with multiple images in a conversation

460 * Image analysis works with diagrams, screenshots, mockups, and more463 * Image analysis works with diagrams, screenshots, mockups, and more

464 * 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>465</Tip>

462 466 

463***467***


496 Tips:500 Tips:

497 501 

498 * File paths can be relative or absolute502 * File paths can be relative or absolute

499 * @ file references add CLAUDE.md in the file's directory and parent directories to context503 * @ file references add `CLAUDE.md` in the file's directory and parent directories to context

500 * Directory references show file listings, not contents504 * Directory references show file listings, not contents

501 * You can reference multiple files in a single message (e.g., "@file1.js and @file2.js")505 * You can reference multiple files in a single message (for example, "@file1.js and @file2.js")

502</Tip>506</Tip>

503 507 

504***508***

505 509 

506## Use extended thinking510## Use extended thinking (thinking mode)

507 511 

508Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning.512[Extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) is enabled by default, giving Claude space to reason through complex problems step-by-step before responding. This reasoning is visible in verbose mode, which you can toggle on with `Ctrl+O`.

509 513 

510<Note>514Additionally, Opus 4.6 introduces adaptive reasoning: instead of a fixed thinking token budget, the model dynamically allocates thinking based on your [effort level](/en/model-config#adjust-effort-level) setting. Extended thinking and adaptive reasoning work together to give you control over how deeply Claude reasons before responding.

511 [Extended thinking](https://docs.claude.com/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/settings#environment-variables) in your settings.

512</Note>

513 515 

514<Steps>516Extended 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 517 

520 Claude will gather relevant information from your codebase and518<Note>

521 use extended thinking, which will be visible in the interface.519 Phrases like "think", "think hard", "ultrathink", and "think more" are interpreted as regular prompt instructions and don't allocate thinking tokens.

522 </Step>520</Note>

523 521 

524 <Step title="Refine the thinking with follow-up prompts">522### Configure thinking mode

525 ```

526 > think about potential security vulnerabilities in this approach

527 ```

528 523 

529 ```524Thinking 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 525 

535<Tip>526| Scope | How to configure | Details |

536 Tips to get the most value out of extended thinking:527| ---------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |

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

529| **Toggle shortcut** | Press `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle thinking on/off for the current session (all models). May require [terminal configuration](/en/terminal-config) to enable Option key shortcuts |

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

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

537 532 

538 [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is most valuable for complex tasks such as:533To view Claude's thinking process, press `Ctrl+O` to toggle verbose mode and see the internal reasoning displayed as gray italic text.

539 534 

540 * Planning complex architectural changes535### 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 536 

546 Use `Tab` to toggle Thinking on and off during a session.537Extended thinking controls how much internal reasoning Claude performs before responding. More thinking provides more space to explore solutions, analyze edge cases, and self-correct mistakes.

547 538 

548 The way you prompt for thinking results in varying levels of thinking depth:539**With Opus 4.6**, thinking uses adaptive reasoning: the model dynamically allocates thinking tokens based on the [effort level](/en/model-config#adjust-effort-level) you select (low, medium, high). This is the recommended way to tune the tradeoff between speed and reasoning depth.

549 540 

550 * "think" triggers basic extended thinking541**With other models**, thinking uses a fixed budget of up to 31,999 tokens from your output budget. You can limit this with the [`MAX_THINKING_TOKENS`](/en/settings#environment-variables) environment variable, or disable thinking entirely via `/config` or the `Option+T`/`Alt+T` toggle.

551 * intensifying phrases such as "keep hard", "think more", "think a lot", or "think longer" triggers deeper thinking

552 542 

553 For more extended thinking prompting tips, see [Extended thinking tips](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips).543`MAX_THINKING_TOKENS` is ignored when using Opus 4.6, since adaptive reasoning controls thinking depth instead. The one exception: setting `MAX_THINKING_TOKENS=0` still disables thinking entirely on any model.

554</Tip>

555 544 

556<Note>545<Warning>

557 Claude will display its thinking process as italic gray text above the546 You're charged for all thinking tokens used, even though Claude 4 models show summarized thinking

558 response.547</Warning>

559</Note>

560 548 

561***549***

562 550 

563## Resume previous conversations551## Resume previous conversations

564 552 

565Suppose you've been working on a task with Claude Code and need to continue where you left off in a later session.553When starting Claude Code, you can resume a previous session:

554 

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

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

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

558 

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

560 

561Sessions are stored per project directory. The `/resume` picker shows sessions from the same git repository, including worktrees.

566 562 

567Claude Code provides two options for resuming previous conversations:563### Name your sessions

568 564 

569* `--continue` to automatically continue the most recent conversation565Give sessions descriptive names to find them later. This is a best practice when working on multiple tasks or features.

570* `--resume` to display a conversation picker

571 566 

572<Steps>567<Steps>

573 <Step title="Continue the most recent conversation">568 <Step title="Name the current session">

574 ```bash theme={null}569 Use `/rename` during a session to give it a memorable name:

575 claude --continue570 

571 ```

572 > /rename auth-refactor

576 ```573 ```

577 574 

578 This immediately resumes your most recent conversation without any prompts.575 You can also rename any session from the picker: run `/resume`, navigate to a session, and press `R`.

579 </Step>576 </Step>

580 577 

581 <Step title="Continue in non-interactive mode">578 <Step title="Resume by name later">

579 From the command line:

580 

582 ```bash theme={null}581 ```bash theme={null}

583 claude --continue --print "Continue with my task"582 claude --resume auth-refactor

584 ```583 ```

585 584 

586 Use `--print` with `--continue` to resume the most recent conversation in non-interactive mode, perfect for scripts or automation.585 Or from inside an active session:

587 </Step>

588 586 

589 <Step title="Show conversation picker">

590 ```bash theme={null}

591 claude --resume

592 ```587 ```

588 > /resume auth-refactor

589 ```

590 </Step>

591</Steps>

593 592 

594 This displays an interactive conversation selector with a clean list view showing:593### Use the session picker

595 594 

596 * Session summary (or initial prompt)595The `/resume` command (or `claude --resume` without arguments) opens an interactive session picker with these features:

597 * Metadata: time elapsed, message count, and git branch

598 596 

599 Use arrow keys to navigate and press Enter to select a conversation. Press Esc to exit.597**Keyboard shortcuts in the picker:**

600 </Step>598 

601</Steps>599| Shortcut | Action |

600| :-------- | :------------------------------------------------ |

601| `↑` / `↓` | Navigate between sessions |

602| `→` / `←` | Expand or collapse grouped sessions |

603| `Enter` | Select and resume the highlighted session |

604| `P` | Preview the session content |

605| `R` | Rename the highlighted session |

606| `/` | Search to filter sessions |

607| `A` | Toggle between current directory and all projects |

608| `B` | Filter to sessions from your current git branch |

609| `Esc` | Exit the picker or search mode |

610 

611**Session organization:**

612 

613The picker displays sessions with helpful metadata:

614 

615* Session name or initial prompt

616* Time elapsed since last activity

617* Message count

618* Git branch (if applicable)

619 

620Forked sessions (created with `/rewind` or `--fork-session`) are grouped together under their root session, making it easier to find related conversations.

602 621 

603<Tip>622<Tip>

604 Tips:623 Tips:

605 624 

606 * Conversation history is stored locally on your machine625 * **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 conversation626 * 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 conversation627 * Use `--resume session-name` when you know which session you need

609 * When resuming, you'll see the entire conversation history before continuing628 * Use `--resume` (without a name) when you need to browse and select

629 * For scripts, use `claude --continue --print "prompt"` to resume in non-interactive mode

630 * 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 original631 * The resumed conversation starts with the same model and configuration as the original

611 632 

612 How it works:633 How it works:


615 2. **Message Deserialization**: When resuming, the entire message history is restored to maintain context636 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 preserved637 3. **Tool State**: Tool usage and results from the previous conversation are preserved

617 4. **Context Restoration**: The conversation resumes with all previous context intact638 4. **Context Restoration**: The conversation resumes with all previous context intact

618 

619 Examples:

620 

621 ```bash theme={null}

622 # Continue most recent conversation

623 claude --continue

624 

625 # Continue most recent conversation with a specific prompt

626 claude --continue --print "Show me our progress"

627 

628 # Show conversation picker

629 claude --resume

630 

631 # Continue most recent conversation in non-interactive mode

632 claude --continue --print "Run the tests again"

633 ```

634</Tip>639</Tip>

635 640 

636***641***


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

703</Tip>708</Tip>

704 709 

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

711 

705***712***

706 713 

707## Use Claude as a unix-style utility714## Use Claude as a unix-style utility


789 796 

790***797***

791 798 

792## Create custom slash commands

793 

794Claude Code supports custom slash commands that you can create to quickly execute specific prompts or tasks.

795 

796For more details, see the [Slash commands](/en/slash-commands) reference page.

797 

798### Create project-specific commands

799 

800Suppose you want to create reusable slash commands for your project that all team members can use.

801 

802<Steps>

803 <Step title="Create a commands directory in your project">

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 

857<Tip>

858 Tips:

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>

898 

899***

900 

901## Ask Claude about its capabilities799## Ask Claude about its capabilities

902 800 

903Claude has built-in access to its documentation and can answer questions about its own features and limitations.801Claude has built-in access to its documentation and can answer questions about its own features and limitations.


913```811```

914 812 

915```813```

916> what slash commands are available?814> what skills are available?

917```815```

918 816 

919```817```


944 842 

945## Next steps843## Next steps

946 844 

947<Card title="Claude Code reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">845<CardGroup cols={2}>

948 Clone our development container reference implementation.846 <Card title="Best practices" icon="lightbulb" href="/en/best-practices">

949</Card>847 Patterns for getting the most out of Claude Code

848 </Card>

849 

850 <Card title="How Claude Code works" icon="gear" href="/en/how-claude-code-works">

851 Understand the agentic loop and context management

852 </Card>

853 

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

855 Add skills, hooks, MCP, subagents, and plugins

856 </Card>

857 

858 <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">

859 Clone our development container reference implementation

860 </Card>

861</CardGroup>

costs.md +128 −57

Details

1> ## Documentation Index

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

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

4 

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

4 8 

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.9Claude Code consumes tokens for each interaction. Costs vary based on codebase size, query complexity, and conversation length. The average cost is \$6 per developer per day, with daily costs remaining below \$12 for 90% of users.

6 10 

7For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.5 though there is large variance depending on how many instances users are running and whether they're using it in automation.11For team usage, Claude Code charges by API token consumption. On average, Claude Code costs \~\$100-200/developer per month with Sonnet 4.5 though there is large variance depending on how many instances users are running and whether they're using it in automation.

8 12 

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

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:


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/third-party-integrations#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` feature102Each MCP server adds tool definitions to your context, even when idle. 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 more context-efficient than MCP servers because they don't add persistent tool definitions. Claude can run CLI commands directly without the overhead.

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

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

99 107 

100## Tracking version changes and updates108### Install code intelligence plugins for typed languages

101 109 

102### Current version information110[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 111 

104To check your current Claude Code version and installation details:112### Offload processing to hooks and skills

105 113 

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

107claude doctor

108```

109 115 

110This command shows your version, installation type, and system information.116A [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 117 

112### Understanding changes in Claude Code behavior118For example, this PreToolUse hook filters test output to show only failures:

113 119 

114Claude Code regularly receives updates that may change how features work, including cost reporting:120<Tabs>

121 <Tab title="settings.json">

122 Add this to your [settings.json](/en/settings#settings-files) to run the hook before every Bash command:

115 123 

116* **Version tracking**: Use `claude doctor` to see your current version124 ```json theme={null}

117* **Behavior changes**: Features like `/cost` may display information differently across versions125 {

118* **Documentation access**: Claude always has access to the latest documentation, which can help explain current feature behavior126 "hooks": {

127 "PreToolUse": [

128 {

129 "matcher": "Bash",

130 "hooks": [

131 {

132 "type": "command",

133 "command": "~/.claude/hooks/filter-test-output.sh"

134 }

135 ]

136 }

137 ]

138 }

139 }

140 ```

141 </Tab>

142 

143 <Tab title="filter-test-output.sh">

144 The hook calls this script, which checks if the command is a test runner and modifies it to show only failures:

145 

146 ```bash theme={null}

147 #!/bin/bash

148 input=$(cat)

149 cmd=$(echo "$input" | jq -r '.tool_input.command')

150 

151 # If running tests, filter to show only failures

152 if [[ "$cmd" =~ ^(npm test|pytest|go test) ]]; then

153 filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"

154 echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"$filtered_cmd\"}}}"

155 else

156 echo "{}"

157 fi

158 ```

159 </Tab>

160</Tabs>

119 161 

120### When cost reporting changes162### Move instructions from CLAUDE.md to skills

121 163 

122If you notice changes in how costs are displayed (such as the `/cost` command showing different information):164Your [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 \~500 lines by including only essentials.

123 165 

1241. **Verify your version**: Run `claude doctor` to confirm your current version166### 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 167 

128<Note>168Extended thinking is enabled by default with a budget of 31,999 tokens because it significantly improves performance on complex planning and reasoning tasks. However, thinking tokens are billed as output tokens, so for simpler tasks where deep reasoning isn't needed, you can reduce costs by lowering the [effort level](/en/model-config#adjust-effort-level) in `/model` for Opus 4.6, disabling thinking in `/config`, or lowering the budget (for example, `MAX_THINKING_TOKENS=8000`).

129 For team deployments, we recommend starting with a small pilot group to169 

130 establish usage patterns before wider rollout.170### Delegate verbose operations to subagents

131</Note>171 

172Running tests, fetching documentation, or processing log files can consume significant context. Delegate these to [subagents](/en/sub-agents#isolate-high-volume-operations) so the verbose output stays in the subagent's context while only a summary returns to your main conversation.

173 

174### Manage agent team costs

175 

176Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode, because each teammate maintains its own context window and runs as a separate Claude instance. Keep team tasks small and self-contained to limit per-teammate token usage. See [agent teams](/en/agent-teams) for details.

177 

178### Write specific prompts

179 

180Vague requests like "improve this codebase" trigger broad scanning. Specific requests like "add input validation to the login function in auth.ts" let Claude work efficiently with minimal file reads.

181 

182### Work efficiently on complex tasks

183 

184For longer or more complex work, these habits help avoid wasted tokens from going down the wrong path:

185 

186* **Use plan mode for complex tasks**: Press Shift+Tab to enter [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) before implementation. Claude explores the codebase and proposes an approach for your approval, preventing expensive re-work when the initial direction is wrong.

187* **Course-correct early**: If Claude starts heading the wrong direction, press Escape to stop immediately. Use `/rewind` or double-tap Escape to restore conversation and code to a previous checkpoint.

188* **Give verification targets**: Include test cases, paste screenshots, or define expected output in your prompt. When Claude can verify its own work, it catches issues before you need to request fixes.

189* **Test incrementally**: Write one file, test it, then continue. This catches issues early when they're cheap to fix.

190 

191## Background token usage

192 

193Claude Code uses tokens for some background functionality even when idle:

194 

195* **Conversation summarization**: Background jobs that summarize previous conversations for the `claude --resume` feature

196* **Command processing**: Some commands like `/cost` may generate requests to check status

197 

198These background processes consume a small amount of tokens (typically under \$0.04 per session) even without active interaction.

199 

200## Understanding changes in Claude Code behavior

201 

202Claude Code regularly receives updates that may change how features work, including cost reporting. Run `claude --version` to check your current version. For specific billing questions, contact Anthropic support through your [Console account](https://platform.claude.com/login). For team deployments, start with a small pilot group to establish usage patterns before wider rollout.

data-usage.md +28 −28

Details

1> ## Documentation Index

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

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

4 

1# 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 15 

14* If you're a current user, you can select your preference now and your selection will immediately go into effect.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)).

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 

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

21 17 

22### Development Partner Program18### Development Partner Program

23 19 


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

33 29 

30To disable these surveys, set `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1`. The survey is also automatically disabled when using third-party providers (Bedrock, Vertex, Foundry) or when telemetry is disabled.

31 

34### Data retention32### Data retention

35 33 

36Anthropic retains Claude Code data based on your account type and preferences.34Anthropic retains Claude Code data based on your account type and preferences.


51 49 

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).50For 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 51 

54## Data flow and dependencies52## Data access

55 53 

56<img src="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=4672f138596e864633b4b7c7ae4ae812" 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/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?w=280&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=5d9bdaf7ea50fc38dc01bbde7b952835 280w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?w=560&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=525736e5860ac9f262de4b40c9c68a0e 560w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?w=840&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=5262f9d1a1d0cffb0d5944e49b2d72be 840w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?w=1100&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=ec74e6b2f87b667f6d0e2278c20944de 1100w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?w=1650&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=05f11b1d061b6ddbb69969d4e535547a 1650w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/claude-code-data-flow.png?w=2500&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=9b9cce0fb5989bd1d27f143825be73ff 2500w" />54For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.

55 

56## Local Claude Code: Data flow and dependencies

57 

58The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.

59 

60<img src="https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=9e77f476347e7c9983f6e211d27cf6a9" alt="Diagram showing Claude Code's external connections: install/update connects to NPM, and user requests connect to Anthropic services including Console auth, public-api, and optionally Statsig, Sentry, and bug reporting" data-og-width="720" width="720" data-og-height="520" height="520" data-path="images/claude-code-data-flow.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=280&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=94c033b9b6db3d10b9e2d7c6d681d9dc 280w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=560&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=430aaaf77c28c501d5753ffa456ee227 560w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=840&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=63c3c3f160b522220a8291fe2f93f970 840w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=1100&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=a7f6e838482f4a1a0a0b4683439369ea 1100w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=1650&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=5fbf749c2f94babb3ef72edfb7aba1e9 1650w, https://mintcdn.com/claude-code/I9Dpo7RZuIbc86cX/images/claude-code-data-flow.svg?w=2500&fit=max&auto=format&n=I9Dpo7RZuIbc86cX&q=85&s=7a1babbdccc4986957698d9c5c30c4a8 2500w" />

57 61 

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.62Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.

59 63 

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).64Claude 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 65 

62### Cloud execution66### 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 67 

68When 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:68When 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 69 

70* **Code storage**: Your repository is cloned to an isolated VM and automatically deleted after session completion70* **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 sandbox71* **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 prevention72* **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 type73* **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 74 

76For security details about cloud execution, see [Security](/en/security#cloud-execution-security).75For security details about cloud execution, see [Security](/en/security#cloud-execution-security).

77 76 


85 84 

86## Default behaviors by API provider85## Default behaviors by API provider

87 86 

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:87By default, we disable all non-essential traffic (including error reporting, telemetry, bug reporting functionality, and session quality surveys) when using Bedrock, Vertex, or Foundry. You can also opt out of all of these at once by setting the `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` environment variable. Here are the full default behaviors:

89 88 

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

91| ------------------------------- | -------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |90| ------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------ |

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. |91| **Statsig (Metrics)** | Default on.<br />`DISABLE_TELEMETRY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

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. |92| **Sentry (Errors)** | Default on.<br />`DISABLE_ERROR_REPORTING=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

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. |93| **Claude API (`/bug` reports)** | Default on.<br />`DISABLE_BUG_COMMAND=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

94| **Session quality surveys** | Default on.<br />`CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY=1` to disable. | Default off.<br />`CLAUDE_CODE_USE_VERTEX` must be 1. | Default off.<br />`CLAUDE_CODE_USE_BEDROCK` must be 1. | Default off.<br />`CLAUDE_CODE_USE_FOUNDRY` must be 1. |

95 95 

96All environment variables can be checked into `settings.json` ([read more](/en/settings)).96All environment variables can be checked into `settings.json` ([read more](/en/settings)).

desktop.md +306 −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 desktop

6 

7> Run Claude Code tasks locally or on secure cloud infrastructure with the Claude desktop app

8 

9<Note>

10 Claude Code on desktop is currently in preview.

11</Note>

12 

13Claude Code is an AI coding assistant that works directly with your codebase. Unlike Claude.ai chat, it can read your project files, edit code, run terminal commands, and understand how different parts of your code connect. You watch changes happen in real time.

14 

15You can use Claude Code through the terminal ([CLI](/en/quickstart)) or through the desktop app described here. Both provide the same core capabilities. The desktop app adds a graphical interface and visual session management.

16 

17<CardGroup cols={2}>

18 <Card title="New to Claude Code?" icon="rocket" href="#installation-and-setup">

19 Start here to install and make your first edit

20 </Card>

21 

22 <Card title="Coming from the CLI?" icon="terminal" href="#how-desktop-relates-to-cli">

23 See what's shared and what's different

24 </Card>

25</CardGroup>

26 

27The desktop app has three tabs:

28 

29* **Chat**: A conversational interface for general questions and tasks (like Claude.ai)

30* **Cowork**: An autonomous agent that works on tasks in the background

31* **Code**: An AI coding assistant that reads and edits your project files directly

32 

33This documentation covers the **Code** tab. For the chat interface, see the [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop).

34 

35## Installation and setup

36 

37<Steps>

38 <Step title="Download the app">

39 Download Claude for your platform. You'll need an Anthropic account ([sign up at claude.ai](https://claude.ai) if you don't have one).

40 

41 <CardGroup cols={2}>

42 <Card title="macOS" icon="apple" href="https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs">

43 Universal build for Intel and Apple Silicon

44 </Card>

45 

46 <Card title="Windows" icon="windows" href="https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs">

47 For x64 processors

48 </Card>

49 </CardGroup>

50 

51 For Windows ARM64, [download here](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs). Local sessions are not available on ARM64 devices, so use remote sessions instead.

52 

53 Linux is not currently supported.

54 </Step>

55 

56 <Step title="Open the app and sign in">

57 Launch Claude from your Applications folder (macOS) or Start menu (Windows). Sign in with your Anthropic account.

58 </Step>

59 

60 <Step title="Select the Code tab">

61 Click the **Code** tab in the top left. If clicking Code prompts you to sign in online, complete the sign-in and restart the app.

62 </Step>

63</Steps>

64 

65## Getting started

66 

67If you already use the CLI, you can skip to [How Desktop relates to CLI](#how-desktop-relates-to-cli) for a quick overview of differences.

68 

69<Steps>

70 <Step title="Choose a folder and environment">

71 Select **Local** to run Claude on your machine using your files directly. This is the best choice for getting started. Click **Select folder** and choose your project directory.

72 

73 You can also run [remote sessions](/en/claude-code-on-the-web) that continue in the cloud even if you close the app.

74 </Step>

75 

76 <Step title="Start a session">

77 Type what you want Claude to do:

78 

79 * "Find a TODO comment and fix it"

80 * "Add tests for the main function"

81 * "Create a CLAUDE.md with instructions for this codebase"

82 

83 A **session** 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.

84 </Step>

85 

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

87 By default, Code is in **Ask** mode, where Claude proposes changes and waits for your approval before applying them. You'll see:

88 

89 1. **A diff view** showing exactly what will change in each file

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

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

92 

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

94 </Step>

95</Steps>

96 

97The sections below cover commands, permission modes, parallel sessions, and ways to extend Claude Code with custom workflows and integrations.

98 

99## What you can do

100 

101Claude Code can edit files, run terminal commands, and understand how your code connects. Try prompts like:

102 

103* `Fix the bug in the login function`

104* `Run the tests and fix any failures`

105* `How does the authentication flow work?`

106 

107You can rename, resume, and archive sessions through the sidebar.

108 

109### Choose a permission mode

110 

111Control how Claude works using the mode selector next to the send button:

112 

113* **Ask** (recommended for new users): Claude asks for your approval before each file edit or command. You see a diff view and can accept or reject each change.

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

115* **Plan**: Claude creates a detailed plan for your approval before making any changes. Good for complex tasks where you want to review the approach first.

116* **Act**: Claude runs without permission checks, automatically executing file edits and terminal commands. Only use this mode in trusted environments.

117 

118<Warning title="Act mode">

119 Act runs in `bypassPermissions` mode, which disables all permission checks and should only be used in isolated environments like containers or VMs where Claude Code cannot cause damage. This mode is disabled by default. For personal accounts, enable it in [Claude Code personal settings](https://claude.ai/settings/claude-code). For Team and Enterprise plans, admins must enable it in [Claude Code admin settings](https://claude.ai/admin-settings/claude-code). Act mode does not persist across sessions.

120</Warning>

121 

122To stop Claude mid-task, click the stop button.

123 

124Remote sessions only support **Code** and **Plan** modes because they continue running in the background without requiring your active participation. See [permission modes](/en/permissions#permission-modes) for details on how these work internally.

125 

126### Work in parallel with sessions

127 

128Click **+ 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 worktrees, so changes in one session don't affect another until you commit them. Worktrees are stored in `~/.claude-worktrees/` by default.

129 

130<Note>

131 Session isolation requires [Git](https://git-scm.com/downloads). Without Git, sessions in the same directory edit the same files, so changes in one session are immediately visible in others.

132</Note>

133 

134To include files listed in your `.gitignore` (like `.env`) in new worktrees, create a `.worktreeinclude` file in your project root listing the file patterns to copy.

135 

136To manage a session, click its dropdown in the sidebar to rename it, archive it, or check context usage. When context fills up, Claude automatically summarizes the conversation. You can also ask Claude to compact if you want to free up space earlier.

137 

138### Run long-running tasks remotely

139 

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

141 

142Remote sessions support **Code** and **Plan** modes. See [Claude Code on the web](/en/claude-code-on-the-web) for details on configuring remote environments.

143 

144### Review changes with diff view

145 

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

147 

148When Claude changes files, a diff stats indicator appears showing the number of lines added and removed (for example, `+12 -1`). Click this indicator to open the diff viewer, which displays a file list on the left and the changes for each file on the right.

149 

150To comment on specific lines, click any line in the diff to open a comment box. Type your feedback and press **Enter** to send. In the full diff view, press **Enter** to accept each comment, then **Cmd+Enter** to send them all. Claude reads your comments and makes the requested changes, which appear as a new diff you can review.

151 

152## Extend Claude Code

153 

154You can extend Claude Code with custom commands, automated workflows, and external integrations.

155 

156### Connect external tools

157 

158For local sessions, click the **...** button before starting and select **Connectors** to add integrations like Google Calendar, Slack, GitHub, Linear, Notion, and more. Connectors must be configured before the session starts and are only available for local sessions. Once 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.

159 

160Connectors are [MCP (Model Context Protocol) servers](/en/mcp) with built-in setup. You can also [create custom connectors](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp) or add MCP servers manually via [configuration files](/en/mcp#configure-mcp-servers).

161 

162### Create custom skills

163 

164[Skills](/en/skills) are reusable prompts that extend Claude's capabilities. For example, you could create a `review` skill that runs your standard code review checklist, or a `deploy` skill that walks through your deployment steps. Skills are defined as markdown files in `.claude/skills/` and can include instructions, context, and even call other tools. Ask Claude what skills are available or to run a specific skill. Claude can also help you create a skill if you describe what you want, or see [skills](/en/skills) to learn how to write them yourself.

165 

166### Automate workflows with hooks

167 

168[Hooks](/en/hooks) run shell commands automatically in response to Claude Code events. For example, you could run a linter after every file edit, auto-format code, or send notifications when tasks complete. Hooks are configured in your [settings files](/en/settings). See [hooks](/en/hooks) for available events and configuration examples.

169 

170## Environment configuration

171 

172When starting a session, you choose between **Local** (runs on your machine) or **Remote** (runs on Anthropic's cloud).

173 

174**Local sessions** inherit environment variables from your shell. If you need additional variables, set them in your shell profile (`~/.zshrc`, `~/.bashrc`) and restart the desktop app. See [environment variables](/en/settings#environment-variables) for the full list of supported variables.

175 

176[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. The thinking process runs in the background but isn't displayed in the Desktop interface. To disable it or adjust the budget, set `MAX_THINKING_TOKENS` in your shell profile (use `0` to disable).

177 

178**Remote sessions** run on Anthropic's cloud infrastructure and continue even if you close the app. Usage counts toward your subscription plan limits with no separate compute charges. See [Claude Code on the web](/en/claude-code-on-the-web) for details on configuring remote environments.

179 

180## How Desktop relates to CLI

181 

182If 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 (CLAUDE.md files).

183 

184### CLI flag equivalents

185 

186If you're used to CLI flags, the table below shows the Desktop equivalent for each. Some flags have no Desktop equivalent because they're designed for scripting or automation.

187 

188| CLI | Desktop equivalent |

189| ------------------------------------- | ---------------------------------------------- |

190| `--model sonnet` | **...** menu > Model (before starting session) |

191| `--resume`, `--continue` | Click a session in the sidebar |

192| `--allowedTools`, `--disallowedTools` | Not available in Desktop |

193| `--dangerously-skip-permissions` | Not available in Desktop |

194| `--print` | Not available (Desktop is interactive) |

195 

196### Shared configuration

197 

198Desktop and CLI read the same configuration files, so your setup carries over:

199 

200* **[CLAUDE.md](/en/memory)** and **CLAUDE.local.md** files in your project are used by both

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

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

203* **[Settings](/en/settings)** in `~/.claude.json` and `~/.claude/settings.json` are shared

204* **Models** (Sonnet, Opus, Haiku) are available in both (Desktop requires selecting before starting a session)

205 

206<Note>

207 MCP servers configured for the **Claude Desktop chat app** (in `claude_desktop_config.json`) are separate from Claude Code. To use MCP servers in Claude Code, configure them in `~/.claude.json` or your project's `.mcp.json` file. See [MCP configuration](/en/mcp#configure-mcp-servers) for details.

208</Note>

209 

210### What's different

211 

212**Desktop adds:**

213 

214* Graphical interface with visual session management

215* Built-in connectors for common integrations

216* Automatic session isolation for Git repositories (each session gets its own worktree)

217 

218**CLI adds:**

219 

220* [Third-party API providers](/en/third-party-integrations) (Bedrock, Vertex, Foundry). If you use these, continue using CLI for those projects.

221* [CLI flags](/en/cli-reference) for scripting (`--print`, `--resume`, `--continue`)

222* [Programmatic usage](/en/headless) via the Agent SDK

223 

224## Troubleshooting

225 

226Solutions to common issues with the Claude desktop app. For CLI issues, see [CLI troubleshooting](/en/troubleshooting).

227 

228### Check your version

229 

230To see which version of the desktop app you're running:

231 

232* **macOS**: Click **Claude** in the menu bar, then **About Claude**

233* **Windows**: Click **Help**, then **About**

234 

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

236 

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

238 

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

240 

241```bash theme={null}

242git fetch origin <branch-name>

243git checkout <branch-name>

244```

245 

246### "Failed to load session" error

247 

248This error can occur for several reasons:

249 

250* The selected folder no longer exists or is inaccessible

251* A Git repository requires Git LFS but it's not installed (see [Git LFS errors](#git-lfs-errors))

252* File permissions prevent access to the project directory

253 

254Try selecting a different folder or restarting the desktop app.

255 

256### App won't quit

257 

258If the desktop app doesn't close properly:

259 

260* **macOS**: Press Cmd+Q. If the app doesn't respond, use Force Quit (Cmd+Option+Esc, select Claude, click Force Quit).

261* **Windows**: Use Task Manager (Ctrl+Shift+Esc) to end the Claude process.

262 

263### Windows installation issues

264 

265If the installer fails silently or doesn't complete properly:

266 

2671. **PATH not updated**: After installation, open a new terminal window. The PATH updates only apply to new terminal sessions.

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

269 

270### Session not finding installed tools

271 

272If Claude can't find tools like `npm`, `node`, or other CLI commands:

273 

2741. Verify the tools work in your regular terminal

2752. Check that your shell profile (`~/.zshrc`, `~/.bashrc`) properly sets up PATH

2763. Restart the desktop app to reload environment variables

277 

278### MCP servers not working (Windows)

279 

280If MCP server toggles don't respond or servers fail to connect on Windows:

281 

2821. Check that the MCP server is properly configured in your settings

2832. Restart the desktop app after making changes

2843. Verify the MCP server process is running (check Task Manager)

2854. Review the server logs for connection errors

286 

287### Git LFS errors

288 

289If you see "Git LFS is required by this repository but is not installed," your repository uses Git Large File Storage for large binary files. Install Git LFS before opening this repository:

290 

2911. Install Git LFS from [git-lfs.com](https://git-lfs.com/)

2922. Run `git lfs install` in your terminal

2933. Restart the desktop app

294 

295## Enterprise configuration

296 

297Organizations can disable local Claude Code use in the desktop application with the `isClaudeCodeForDesktopEnabled` [enterprise policy option](https://support.claude.com/en/articles/12622667-enterprise-configuration#h_003283c7cb). Additionally, Claude Code on the web can be disabled in your [admin settings](https://claude.ai/admin-settings/claude-code).

298 

299## Related resources

300 

301* [Claude Code on the web](/en/claude-code-on-the-web): Run remote sessions that continue in the cloud

302* [CLI reference](/en/cli-reference): Use Claude Code in your terminal with flags and scripting

303* [Common workflows](/en/common-workflows): Tutorials for debugging, refactoring, testing, and more

304* [Settings reference](/en/settings): Configure Claude Code behavior with settings files

305* [Claude Desktop support](https://support.claude.com/en/collections/16163169-claude-desktop): Help articles for the Chat tab and general desktop app usage

306* [Enterprise configuration](https://support.claude.com/en/articles/12622667-enterprise-configuration): Admin policies for organizational deployments

devcontainer.md +5 −1

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>

discover-plugins.md +393 −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.

32 

33To install a plugin from the official marketplace:

34 

35```shell theme={null}

36/plugin install plugin-name@claude-plugins-official

37```

38 

39<Note>

40 The official marketplace is maintained by Anthropic. To distribute your own plugins, [create your own marketplace](/en/plugin-marketplaces) and share it with users.

41</Note>

42 

43The official marketplace includes several categories of plugins:

44 

45### Code intelligence

46 

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

48 

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

50 

51| Language | Plugin | Binary required |

52| :--------- | :------------------ | :--------------------------- |

53| C/C++ | `clangd-lsp` | `clangd` |

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

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

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

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

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

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

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

61| Rust | `rust-analyzer-lsp` | `rust-analyzer` |

62| Swift | `swift-lsp` | `sourcekit-lsp` |

63| TypeScript | `typescript-lsp` | `typescript-language-server` |

64 

65You can also [create your own LSP plugin](/en/plugins-reference#lsp-servers) for other languages.

66 

67<Note>

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

69</Note>

70 

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

72 

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

74 

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

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

77 

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

79 

80### External integrations

81 

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

83 

84* **Source control**: `github`, `gitlab`

85* **Project management**: `atlassian` (Jira/Confluence), `asana`, `linear`, `notion`

86* **Design**: `figma`

87* **Infrastructure**: `vercel`, `firebase`, `supabase`

88* **Communication**: `slack`

89* **Monitoring**: `sentry`

90 

91### Development workflows

92 

93Plugins that add commands and agents for common development tasks:

94 

95* **commit-commands**: Git commit workflows including commit, push, and PR creation

96* **pr-review-toolkit**: Specialized agents for reviewing pull requests

97* **agent-sdk-dev**: Tools for building with the Claude Agent SDK

98* **plugin-dev**: Toolkit for creating your own plugins

99 

100### Output styles

101 

102Customize how Claude responds:

103 

104* **explanatory-output-style**: Educational insights about implementation choices

105* **learning-output-style**: Interactive learning mode for skill building

106 

107## Try it: add the demo marketplace

108 

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

110 

111<Steps>

112 <Step title="Add the marketplace">

113 From within Claude Code, run the `plugin marketplace add` command for the `anthropics/claude-code` marketplace:

114 

115 ```shell theme={null}

116 /plugin marketplace add anthropics/claude-code

117 ```

118 

119 This downloads the marketplace catalog and makes its plugins available to you.

120 </Step>

121 

122 <Step title="Browse available plugins">

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

124 

125 * **Discover**: browse available plugins from all your marketplaces

126 * **Installed**: view and manage your installed plugins

127 * **Marketplaces**: add, remove, or update your added marketplaces

128 * **Errors**: view any plugin loading errors

129 

130 Go to the **Discover** tab to see plugins from the marketplace you just added.

131 </Step>

132 

133 <Step title="Install a plugin">

134 Select a plugin to view its details, then choose an installation scope:

135 

136 * **User scope**: install for yourself across all projects

137 * **Project scope**: install for all collaborators on this repository

138 * **Local scope**: install for yourself in this repository only

139 

140 For example, select **commit-commands** (a plugin that adds git workflow commands) and install it to your user scope.

141 

142 You can also install directly from the command line:

143 

144 ```shell theme={null}

145 /plugin install commit-commands@anthropics-claude-code

146 ```

147 

148 See [Configuration scopes](/en/settings#configuration-scopes) to learn more about scopes.

149 </Step>

150 

151 <Step title="Use your new plugin">

152 After installing, the plugin's commands are immediately available. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`.

153 

154 Try it out by making a change to a file and running:

155 

156 ```shell theme={null}

157 /commit-commands:commit

158 ```

159 

160 This stages your changes, generates a commit message, and creates the commit.

161 

162 Each plugin works differently. Check the plugin's description in the **Discover** tab or its homepage to learn what commands and capabilities it provides.

163 </Step>

164</Steps>

165 

166The rest of this guide covers all the ways you can add marketplaces, install plugins, and manage your configuration.

167 

168## Add marketplaces

169 

170Use the `/plugin marketplace add` command to add marketplaces from different sources.

171 

172<Tip>

173 **Shortcuts**: You can use `/plugin market` instead of `/plugin marketplace`, and `rm` instead of `remove`.

174</Tip>

175 

176* **GitHub repositories**: `owner/repo` format (for example, `anthropics/claude-code`)

177* **Git URLs**: any git repository URL (GitLab, Bitbucket, self-hosted)

178* **Local paths**: directories or direct paths to `marketplace.json` files

179* **Remote URLs**: direct URLs to hosted `marketplace.json` files

180 

181### Add from GitHub

182 

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

184 

185For example, `anthropics/claude-code` refers to the `claude-code` repository owned by `anthropics`:

186 

187```shell theme={null}

188/plugin marketplace add anthropics/claude-code

189```

190 

191### Add from other Git hosts

192 

193Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers:

194 

195Using HTTPS:

196 

197```shell theme={null}

198/plugin marketplace add https://gitlab.com/company/plugins.git

199```

200 

201Using SSH:

202 

203```shell theme={null}

204/plugin marketplace add git@gitlab.com:company/plugins.git

205```

206 

207To add a specific branch or tag, append `#` followed by the ref:

208 

209```shell theme={null}

210/plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0

211```

212 

213### Add from local paths

214 

215Add a local directory that contains a `.claude-plugin/marketplace.json` file:

216 

217```shell theme={null}

218/plugin marketplace add ./my-marketplace

219```

220 

221You can also add a direct path to a `marketplace.json` file:

222 

223```shell theme={null}

224/plugin marketplace add ./path/to/marketplace.json

225```

226 

227### Add from remote URLs

228 

229Add a remote `marketplace.json` file via URL:

230 

231```shell theme={null}

232/plugin marketplace add https://example.com/marketplace.json

233```

234 

235<Note>

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

237</Note>

238 

239## Install plugins

240 

241Once you've added marketplaces, you can install plugins directly (installs to user scope by default):

242 

243```shell theme={null}

244/plugin install plugin-name@marketplace-name

245```

246 

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

248 

249* **User scope** (default): install for yourself across all projects

250* **Project scope**: install for all collaborators on this repository (adds to `.claude/settings.json`)

251* **Local scope**: install for yourself in this repository only (not shared with collaborators)

252 

253You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/en/settings#settings-files) and cannot be modified.

254 

255Run `/plugin` and go to the **Installed** tab to see your plugins grouped by scope.

256 

257<Warning>

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

259</Warning>

260 

261## Manage installed plugins

262 

263Run `/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.

264 

265You can also manage plugins with direct commands.

266 

267Disable a plugin without uninstalling:

268 

269```shell theme={null}

270/plugin disable plugin-name@marketplace-name

271```

272 

273Re-enable a disabled plugin:

274 

275```shell theme={null}

276/plugin enable plugin-name@marketplace-name

277```

278 

279Completely remove a plugin:

280 

281```shell theme={null}

282/plugin uninstall plugin-name@marketplace-name

283```

284 

285The `--scope` option lets you target a specific scope with CLI commands:

286 

287```shell theme={null}

288claude plugin install formatter@your-org --scope project

289claude plugin uninstall formatter@your-org --scope project

290```

291 

292## Manage marketplaces

293 

294You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.

295 

296### Use the interactive interface

297 

298Run `/plugin` and go to the **Marketplaces** tab to:

299 

300* View all your added marketplaces with their sources and status

301* Add new marketplaces

302* Update marketplace listings to fetch the latest plugins

303* Remove marketplaces you no longer need

304 

305### Use CLI commands

306 

307You can also manage marketplaces with direct commands.

308 

309List all configured marketplaces:

310 

311```shell theme={null}

312/plugin marketplace list

313```

314 

315Refresh plugin listings from a marketplace:

316 

317```shell theme={null}

318/plugin marketplace update marketplace-name

319```

320 

321Remove a marketplace:

322 

323```shell theme={null}

324/plugin marketplace remove marketplace-name

325```

326 

327<Warning>

328 Removing a marketplace will uninstall any plugins you installed from it.

329</Warning>

330 

331### Configure auto-updates

332 

333Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you'll see a notification suggesting you restart Claude Code.

334 

335Toggle auto-update for individual marketplaces through the UI:

336 

3371. Run `/plugin` to open the plugin manager

3382. Select **Marketplaces**

3393. Choose a marketplace from the list

3404. Select **Enable auto-update** or **Disable auto-update**

341 

342Official Anthropic marketplaces have auto-update enabled by default. Third-party and local development marketplaces have auto-update disabled by default.

343 

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

345 

346To keep plugin auto-updates enabled while disabling Claude Code auto-updates, set `FORCE_AUTOUPDATE_PLUGINS=true` along with `DISABLE_AUTOUPDATER`:

347 

348```shell theme={null}

349export DISABLE_AUTOUPDATER=true

350export FORCE_AUTOUPDATE_PLUGINS=true

351```

352 

353This is useful when you want to manage Claude Code updates manually but still receive automatic plugin updates.

354 

355## Configure team marketplaces

356 

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

358 

359For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/en/settings#plugin-settings).

360 

361## Troubleshooting

362 

363### /plugin command not recognized

364 

365If you see "unknown command" or the `/plugin` command doesn't appear:

366 

3671. **Check your version**: Run `claude --version`. Plugins require version 1.0.33 or later.

3682. **Update Claude Code**:

369 * **Homebrew**: `brew upgrade claude-code`

370 * **npm**: `npm update -g @anthropic-ai/claude-code`

371 * **Native installer**: Re-run the install command from [Setup](/en/setup)

3723. **Restart Claude Code**: After updating, restart your terminal and run `claude` again.

373 

374### Common issues

375 

376* **Marketplace not loading**: Verify the URL is accessible and that `.claude-plugin/marketplace.json` exists at the path

377* **Plugin installation failures**: Check that plugin source URLs are accessible and repositories are public (or you have access)

378* **Files not found after installation**: Plugins are copied to a cache, so paths referencing files outside the plugin directory won't work

379* **Plugin skills not appearing**: Clear the cache with `rm -rf ~/.claude/plugins/cache`, restart Claude Code, and reinstall the plugin.

380 

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

382 

383### Code intelligence issues

384 

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

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

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

388 

389## Next steps

390 

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

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

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

fast-mode.md +131 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Speed up responses with fast mode

6 

7> Get faster Opus 4.6 responses in Claude Code by toggling fast mode.

8 

9<Note>

10 Fast mode is in [research preview](#research-preview). The feature, pricing, and availability may change based on feedback.

11</Note>

12 

13Fast mode delivers faster Opus 4.6 responses at a higher cost per token. Toggle it on with `/fast` when you need speed for interactive work like rapid iteration or live debugging, and toggle it off when cost matters more than latency.

14 

15Fast mode is not a different model. It uses the same Opus 4.6 with a different API configuration that prioritizes speed over cost efficiency. You get identical quality and capabilities, just faster responses.

16 

17What to know:

18 

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

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

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

22* For Claude Code users on subscription plans (Pro/Max/Team/Enterprise), fast mode is available via extra usage only and not included in the subscription rate limits.

23 

24This page covers how to [toggle fast mode](#toggle-fast-mode), its [cost tradeoff](#understand-the-cost-tradeoff), [when to use it](#decide-when-to-use-fast-mode), [requirements](#requirements), and [rate limit behavior](#handle-rate-limits).

25 

26## Toggle fast mode

27 

28Toggle fast mode in either of these ways:

29 

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

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

32 

33Fast mode persists across sessions. For the best cost efficiency, enable fast mode at the start of a session rather than switching mid-conversation. See [understand the cost tradeoff](#understand-the-cost-tradeoff) for details.

34 

35When you enable fast mode:

36 

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

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

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

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

41 

42When you disable fast mode with `/fast` again, you remain on Opus 4.6. The model does not revert to your previous model. To switch to a different model, use `/model`.

43 

44## Understand the cost tradeoff

45 

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

47 

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

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

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

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

52 

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

54 

55When you switch into fast mode mid-conversation, you pay the full fast mode uncached input token price for the entire conversation context. This costs more than if you had enabled fast mode from the start.

56 

57## Decide when to use fast mode

58 

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

60 

61* Rapid iteration on code changes

62* Live debugging sessions

63* Time-sensitive work with tight deadlines

64 

65Standard mode is better for:

66 

67* Long autonomous tasks where speed matters less

68* Batch processing or CI/CD pipelines

69* Cost-sensitive workloads

70 

71### Fast mode vs effort level

72 

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

74 

75| Setting | Effect |

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

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

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

79 

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

81 

82## Requirements

83 

84Fast mode requires all of the following:

85 

86* **Not available on third-party cloud providers**: fast mode is not available on Amazon Bedrock, Google Vertex AI, or Microsoft Azure Foundry. Fast mode is available through the Anthropic Console API and for Claude subscription plans using extra usage.

87* **Extra usage enabled**: your account must have extra usage enabled, which allows billing beyond your plan's included usage. For individual accounts, enable this in your [Console billing settings](https://platform.claude.com/settings/organization/billing). For Teams and Enterprise, an admin must enable extra usage for the organization.

88 

89<Note>

90 Fast mode usage is billed directly to extra usage, even if you have remaining usage on your plan. This means fast mode tokens do not count against your plan's included usage and are charged at the fast mode rate from the first token.

91</Note>

92 

93* **Admin enablement for Teams and Enterprise**: fast mode is disabled by default for Teams and Enterprise organizations. An admin must explicitly [enable fast mode](#enable-fast-mode-for-your-organization) before users can access it.

94 

95<Note>

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

97</Note>

98 

99### Enable fast mode for your organization

100 

101Admins can enable fast mode in:

102 

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

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

105 

106## Handle rate limits

107 

108Fast mode has separate rate limits from standard Opus 4.6. When you hit the fast mode rate limit or run out of extra usage credits:

109 

1101. Fast mode automatically falls back to standard Opus 4.6

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

1123. You continue working at standard speed and pricing

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

114 

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

116 

117## Research preview

118 

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

120 

121* The feature may change based on feedback

122* Availability and pricing are subject to change

123* The underlying API configuration may evolve

124 

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

126 

127## See also

128 

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

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

131* [Status line configuration](/en/statusline): display model and context information

features-overview.md +278 −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 slash command like `/deploy`, or Claude can load them automatically when relevant. Skills can run in your current conversation or in an isolated context via subagents.

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

85 </Tab>

86 

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

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

89 

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

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

92 

93 | Aspect | Subagent | Agent team |

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

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

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

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

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

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

100 

101 **Use a subagent** when you need a quick, focused worker: research a question, verify a claim, review a file. The subagent does the work and returns a summary. Your main conversation stays clean.

102 

103 **Use an agent team** when teammates need to share findings, challenge each other, and coordinate independently. Agent teams are best for research with competing hypotheses, parallel code review, and new feature development where each teammate owns a separate piece.

104 

105 **Transition point:** If you're running parallel subagents but hitting context limits, or if your subagents need to communicate with each other, agent teams are the natural next step.

106 

107 <Note>

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

109 </Note>

110 </Tab>

111 

112 <Tab title="MCP vs Skill">

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

114 

115 | Aspect | MCP | Skill |

116 | -------------- | ---------------------------------------------------- | ------------------------------------------------------- |

117 | **What it is** | Protocol for connecting to external services | Knowledge, workflows, and reference material |

118 | **Provides** | Tools and data access | Knowledge, workflows, reference material |

119 | **Examples** | Slack integration, database queries, browser control | Code review checklist, deploy workflow, API style guide |

120 

121 These solve different problems and work well together:

122 

123 **MCP** gives Claude the ability to interact with external systems. Without MCP, Claude can't query your database or post to Slack.

124 

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

126 

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

128 </Tab>

129</Tabs>

130 

131### Understand how features layer

132 

133Features can be defined at multiple levels: user-wide, per-project, via plugins, or through managed policies. You can also nest CLAUDE.md files in subdirectories or place skills in specific packages of a monorepo. When the same feature exists at multiple levels, here's how they layer:

134 

135* **CLAUDE.md files** are additive: all levels contribute content to Claude's context simultaneously. Files from your working directory and above load at launch; subdirectories load as you work in them. When instructions conflict, Claude uses judgment to reconcile them, with more specific instructions typically taking precedence. See [how Claude looks up memories](/en/memory#how-claude-looks-up-memories).

136* **Skills and subagents** override by name: when the same name exists at multiple levels, one definition wins based on priority (managed > user > project for skills; managed > CLI flag > project > user > plugin for subagents). Plugin skills are [namespaced](/en/plugins#add-skills-to-your-plugin) to avoid conflicts. See [skill discovery](/en/skills#where-skills-live) and [subagent scope](/en/sub-agents#choose-the-subagent-scope).

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

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

139 

140### Combine features

141 

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

143 

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

145 

146| Pattern | How it works | Example |

147| ---------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |

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

149| **Skill + Subagent** | A skill spawns subagents for parallel work | `/review` skill kicks off security, performance, and style subagents that work in isolated context |

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

151| **Hook + MCP** | A hook triggers external actions through MCP | Post-edit hook sends a Slack notification when Claude modifies critical files |

152 

153## Understand context costs

154 

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

156 

157### Context cost by feature

158 

159Each feature has a different loading strategy and context cost:

160 

161| Feature | When it loads | What loads | Context cost |

162| --------------- | ------------------------- | --------------------------------------------- | -------------------------------------------- |

163| **CLAUDE.md** | Session start | Full content | Every request |

164| **Skills** | Session start + when used | Descriptions at start, full content when used | Low (descriptions every request)\* |

165| **MCP servers** | Session start | All tool definitions and schemas | Every request |

166| **Subagents** | When spawned | Fresh context with specified skills | Isolated from main session |

167| **Hooks** | On trigger | Nothing (runs externally) | Zero, unless hook returns additional context |

168 

169\*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.

170 

171### Understand how features load

172 

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

174 

175<img src="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=bd2e24b8e6a99b31ecfffb63f5b23bf5" alt="Context loading: CLAUDE.md and MCP load at session start and stay in every request. Skills load descriptions at start, full content on invocation. Subagents get isolated context. Hooks run externally." data-og-width="720" width="720" data-og-height="410" height="410" data-path="images/context-loading.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=280&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=aebaadd1f484f285dd9cb4e0ea6d49b9 280w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=560&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=030c9b46126d750de315612560082727 560w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=840&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=6c73f8b0389da4f3190843140c810fe9 840w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=1100&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=9844c55d08d2c386672447f2e8518669 1100w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=1650&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=21a9522d0e4bd10ced146aab850ede76 1650w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/context-loading.svg?w=2500&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=d318525915aee1a1a6a4215cfaa61fb9 2500w" />

176 

177<Tabs>

178 <Tab title="CLAUDE.md">

179 **When:** Session start

180 

181 **What loads:** Full content of all CLAUDE.md files (managed, user, and project levels).

182 

183 **Inheritance:** Claude reads CLAUDE.md files from your working directory up to the root, and discovers nested ones in subdirectories as it accesses those files. See [How Claude looks up memories](/en/memory#how-claude-looks-up-memories) for details.

184 

185 <Tip>Keep CLAUDE.md under \~500 lines. Move reference material to skills, which load on-demand.</Tip>

186 </Tab>

187 

188 <Tab title="Skills">

189 Skills are extra capabilities in Claude's toolkit. They can be reference material (like an API style guide) or invocable workflows you trigger with `/<name>` (like `/deploy`). Some are built-in; you can also create your own. Claude uses skills when appropriate, or you can invoke one directly.

190 

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

192 

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

194 

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

196 

197 **Context cost:** Low until used. User-only skills have zero cost until invoked.

198 

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

200 

201 <Tip>Use `disable-model-invocation: true` for skills with side effects. This saves context and ensures only you trigger them.</Tip>

202 </Tab>

203 

204 <Tab title="MCP servers">

205 **When:** Session start.

206 

207 **What loads:** All tool definitions and JSON schemas from connected servers.

208 

209 **Context cost:** [Tool search](/en/mcp#scale-with-mcp-tool-search) (enabled by default) loads MCP tools up to 10% of context and defers the rest until needed.

210 

211 **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`.

212 

213 <Tip>Run `/mcp` to see token costs per server. Disconnect servers you're not actively using.</Tip>

214 </Tab>

215 

216 <Tab title="Subagents">

217 **When:** On demand, when you or Claude spawns one for a task.

218 

219 **What loads:** Fresh, isolated context containing:

220 

221 * The system prompt (shared with parent for cache efficiency)

222 * Full content of skills listed in the agent's `skills:` field

223 * CLAUDE.md and git status (inherited from parent)

224 * Whatever context the lead agent passes in the prompt

225 

226 **Context cost:** Isolated from main session. Subagents don't inherit your conversation history or invoked skills.

227 

228 <Tip>Use subagents for work that doesn't need your full conversation context. Their isolation prevents bloating your main session.</Tip>

229 </Tab>

230 

231 <Tab title="Hooks">

232 **When:** On trigger. Hooks fire at specific lifecycle events like tool execution, session boundaries, prompt submission, permission requests, and compaction. See [Hooks](/en/hooks) for the full list.

233 

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

235 

236 **Context cost:** Zero, unless the hook returns output that gets added as messages to your conversation.

237 

238 <Tip>Hooks are ideal for side effects (linting, logging) that don't need to affect Claude's context.</Tip>

239 </Tab>

240</Tabs>

241 

242## Learn more

243 

244Each feature has its own guide with setup instructions, examples, and configuration options.

245 

246<CardGroup cols={2}>

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

248 Store project context, conventions, and instructions

249 </Card>

250 

251 <Card title="Skills" icon="brain" href="/en/skills">

252 Give Claude domain expertise and reusable workflows

253 </Card>

254 

255 <Card title="Subagents" icon="users" href="/en/sub-agents">

256 Offload work to isolated context

257 </Card>

258 

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

260 Coordinate multiple sessions working in parallel

261 </Card>

262 

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

264 Connect Claude to external services

265 </Card>

266 

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

268 Automate workflows with hooks

269 </Card>

270 

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

272 Bundle and share feature sets

273 </Card>

274 

275 <Card title="Marketplaces" icon="store" href="/en/plugin-marketplaces">

276 Host and distribute plugin collections

277 </Card>

278</CardGroup>

github-actions.md +23 −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 GitHub Actions5# Claude Code GitHub Actions

2 6 

3> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions7> Learn about integrating Claude Code into your development workflow with Claude Code GitHub Actions


5Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards.9Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project's standards.

6 10 

7<Note>11<Note>

8 Claude Code GitHub Actions is built on top of the [Claude Code12 Claude Code GitHub Actions is built on top of the [Claude

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

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

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

12</Note>16</Note>

13 17 

18<Info>

19 **Claude Opus 4.6 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.6, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-6`.

20</Info>

21 

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

15 23 

16* **Instant PR creation**: Describe what you need, and Claude creates a complete PR with all necessary changes24* **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/`713. **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 72 

65<Tip>73<Tip>

66 After completing either the quickstart or manual setup, test the action by74 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>75</Tip>

69 76 

70## Upgrading from Beta77## Upgrading from Beta


87### Breaking Changes Reference94### Breaking Changes Reference

88 95 

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

90| --------------------- | -------------------------------- |97| --------------------- | ------------------------------------- |

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

92| `direct_prompt` | `prompt` |99| `direct_prompt` | `prompt` |

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

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

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

96| `model` | `claude_args: --model` |103| `model` | `claude_args: --model` |

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


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

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

123 claude_args: |130 claude_args: |

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

125 --max-turns 10132 --max-turns 10

126 --model claude-sonnet-4-5-20250929133 --model claude-sonnet-4-5-20250929

127```134```


153 # Responds to @claude mentions in comments160 # Responds to @claude mentions in comments

154```161```

155 162 

156### Using slash commands163### Using skills

157 164 

158```yaml theme={null}165```yaml theme={null}

159name: Code Review166name: Code Review


186 with:193 with:

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

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

189 claude_args: "--model claude-opus-4-1-20250805"196 claude_args: "--model opus"

190```197```

191 198 

192### Common use cases199### Common use cases


209 216 

210### Security considerations217### Security considerations

211 218 

212<Warning>Never commit API keys directly to your repository!</Warning>219<Warning>Never commit API keys directly to your repository.</Warning>

213 220 

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).221For 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 222 


220* Limit action permissions to only what's necessary227* Limit action permissions to only what's necessary

221* Review Claude's suggestions before merging228* Review Claude's suggestions before merging

222 229 

223Always use GitHub Secrets (e.g., `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.230Always use GitHub Secrets (for example, `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.

224 231 

225### Optimizing performance232### Optimizing performance

226 233 


263Key features:270Key features:

264 271 

265* **Unified prompt interface** - Use `prompt` for all instructions272* **Unified prompt interface** - Use `prompt` for all instructions

266* **Slash commands** - Pre-built prompts like `/review` or `/fix`273* **Commands** - Prebuilt prompts like `/review` or `/fix`

267* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`274* **CLI passthrough** - Any Claude Code CLI argument via `claude_args`

268* **Flexible triggers** - Works with any GitHub event275* **Flexible triggers** - Works with any GitHub event

269 276 


621The Claude Code Action v1 uses a simplified configuration:628The Claude Code Action v1 uses a simplified configuration:

622 629 

623| Parameter | Description | Required |630| Parameter | Description | Required |

624| ------------------- | ----------------------------------------------- | -------- |631| ------------------- | ------------------------------------------------------ | -------- |

625| `prompt` | Instructions for Claude (text or slash command) | No\* |632| `prompt` | Instructions for Claude (text or skill like `/review`) | No\* |

626| `claude_args` | CLI arguments passed to Claude Code | No |633| `claude_args` | CLI arguments passed to Claude Code | No |

627| `anthropic_api_key` | Claude API key | Yes\*\* |634| `anthropic_api_key` | Claude API key | Yes\*\* |

628| `github_token` | GitHub token for API access | No |635| `github_token` | GitHub token for API access | No |


633\*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\640\*Prompt is optional - when omitted for issue/PR comments, Claude responds to trigger phrase\

634\*\*Required for direct Claude API, not for Bedrock/Vertex641\*\*Required for direct Claude API, not for Bedrock/Vertex

635 642 

636#### Using claude\_args643#### Pass CLI arguments

637 644 

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

639 646 


644Common arguments:651Common arguments:

645 652 

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

647* `--model`: Model to use (e.g., `claude-sonnet-4-5-20250929`)654* `--model`: Model to use (for example, `claude-sonnet-4-5-20250929`)

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

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

650* `--debug`: Enable debug output657* `--debug`: Enable debug output

gitlab-ci-cd.md +16 −12

Details

1> ## Documentation Index

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

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

4 

1# Claude Code GitLab CI/CD5# Claude Code GitLab CI/CD

2 6 

3> Learn about integrating Claude Code into your development workflow with GitLab CI/CD7> Learn about integrating Claude Code into your development workflow with GitLab CI/CD


9</Info>13</Info>

10 14 

11<Note>15<Note>

12 This integration is built on top of the [Claude Code CLI and SDK](https://docs.claude.com/en/docs/agent-sdk), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.16 This integration is built on top of the [Claude Code CLI and Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.

13</Note>17</Note>

14 18 

15## Why use Claude Code with GitLab?19## Why use Claude Code with GitLab?


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 


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"


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](https://docs.claude.com/en/docs/about-claude/pricing) for details411 * See [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing) for details

408 412 

409* **Cost optimization tips**:413* **Cost optimization tips**:

410 * Use specific `@claude` commands to reduce unnecessary turns414 * Use specific `@claude` commands to reduce unnecessary turns

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

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 


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

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


82```86```

83 87 

84<Note>88<Note>

85 [Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support.89 [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.

86</Note>90</Note>

87 91 

88<Note>92<Note>


99| Small/fast model | `claude-haiku-4-5@20251001` |103| Small/fast model | `claude-haiku-4-5@20251001` |

100 104 

101<Note>105<Note>

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`).106 For Vertex AI users, Claude Code will not automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `claude-haiku-4-5@20251001`).

103</Note>107</Note>

104 108 

105To customize models:109To customize models:

106 110 

107```bash theme={null}111```bash theme={null}

108export ANTHROPIC_MODEL='claude-opus-4-1@20250805'112export ANTHROPIC_MODEL='claude-opus-4-6'

109export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'113export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'

110```114```

111 115 


127 131 

128## 1M token context window132## 1M token context window

129 133 

130Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) on Vertex AI.134Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) on Vertex AI.

131 135 

132<Note>136<Note>

133 The 1M token context window is currently in beta. To use the extended context window, include the `context-1m-2025-08-07` beta header in your Vertex AI requests.137 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.

headless.md +104 −137

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/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## Examples

47claude --resume 550e8400-e29b-41d4-a716-446655440000 "Update the tests"

48 38 

49# Resume in non-interactive mode39These examples highlight common CLI patterns.

50claude --resume 550e8400-e29b-41d4-a716-446655440000 "Fix all linting issues" --no-interactive40 

51```41### Get structured output

42 

43Use `--output-format` to control how responses are returned:

52 44 

53## Output Formats45* `text` (default): plain text output

46* `json`: structured JSON with result, session ID, and metadata

47* `stream-json`: newline-delimited JSON for real-time streaming

54 48 

55### Text Output (Default)49This example returns a project summary as JSON with session metadata, with the text result in the `result` field:

56 50 

57```bash theme={null}51```bash theme={null}

58claude -p "Explain file src/components/Header.tsx"52claude -p "Summarize this project" --output-format json

59# Output: This is a React component showing...

60```53```

61 54 

62### JSON Output55To 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.

63 56 

64Returns structured data including metadata:57This example extracts function names and returns them as an array of strings:

65 58 

66```bash theme={null}59```bash theme={null}

67claude -p "How does the data layer work?" --output-format json60claude -p "Extract the main function names from auth.py" \

61 --output-format json \

62 --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

68```63```

69 64 

70Response format:65<Tip>

71 66 Use a tool like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields:

72```json theme={null}

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 67 

86### Streaming JSON Output68 ```bash theme={null}

69 # Extract the text result

70 claude -p "Summarize this project" --output-format json | jq -r '.result'

87 71 

88Streams each message as it is received:72 # Extract structured output

73 claude -p "Extract function names from auth.py" \

74 --output-format json \

75 --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \

76 | jq '.structured_output'

77 ```

78</Tip>

89 79 

90```bash theme={null}80### Stream responses

91claude -p "Build an application" --output-format stream-json

92```

93 81 

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.82Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they're generated. Each line is a JSON object representing an event:

95 83 

96## Input Formats84```bash theme={null}

85claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages

86```

97 87 

98### Text Input (Default)88The following example uses [jq](https://jqlang.github.io/jq/) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:

99 89 

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

101# Direct argument91claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \

102claude -p "Explain this code"92 jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

103 

104# From stdin

105echo "Explain this code" | claude -p

106```93```

107 94 

108### Streaming JSON Input95For 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.

109 96 

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.97### Auto-approve tools

111 98 

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`.99Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:

113 100 

114```bash theme={null}101```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 --verbose102claude -p "Run the test suite and fix any failures" \

103 --allowedTools "Bash,Read,Edit"

116```104```

117 105 

118## Agent Integration Examples106### Create a commit

119 107 

120### SRE Incident Response Bot108This example reviews staged changes and creates a commit with an appropriate message:

121 109 

122```bash theme={null}110```bash theme={null}

123#!/bin/bash111claude -p "Look at my staged changes and create an appropriate commit" \

112 --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

113```

124 114 

125# Automated incident response agent115The `--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`.

126investigate_incident() {

127 local incident_description="$1"

128 local severity="${2:-medium}"

129 116 

130 claude -p "Incident: $incident_description (Severity: $severity)" \117<Note>

131 --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \118 User-invoked [skills](/en/skills) like `/commit` and [built-in commands](/en/interactive-mode#built-in-commands) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.

132 --output-format json \119</Note>

133 --allowedTools "Bash,Read,WebSearch,mcp__datadog" \

134 --mcp-config monitoring-tools.json

135}

136 120 

137# Usage121### Customize the system prompt

138investigate_incident "Payment API returning 500 errors" "high"

139```

140 122 

141### Automated Security Review123Use `--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:

142 124 

143```bash theme={null}125```bash theme={null}

144# Security audit agent for pull requests126gh pr diff "$1" | claude -p \

145audit_pr() {127 --append-system-prompt "You are a security engineer. Review for vulnerabilities." \

146 local pr_number="$1"128 --output-format json

129```

147 130 

148 gh pr diff "$pr_number" | claude -p \131See [system prompt flags](/en/cli-reference#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt.

149 --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, insecure patterns, and compliance issues." \

150 --output-format json \

151 --allowedTools "Read,Grep,WebSearch"

152}

153 132 

154# Usage and save to file133### Continue conversations

155audit_pr 123 > security-report.json

156```

157 134 

158### Multi-turn Legal Assistant135Use `--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:

159 136 

160```bash theme={null}137```bash theme={null}

161# Legal document review with session persistence138# First request

162session_id=$(claude -p "Start legal review session" --output-format json | jq -r '.session_id')139claude -p "Review this codebase for performance issues"

163 140 

164# Review contract in multiple steps141# Continue the most recent conversation

165claude -p --resume "$session_id" "Review contract.pdf for liability clauses"142claude -p "Now focus on the database queries" --continue

166claude -p --resume "$session_id" "Check compliance with GDPR requirements"143claude -p "Generate a summary of all issues found" --continue

167claude -p --resume "$session_id" "Generate executive summary of risks"

168```144```

169 145 

170## Best Practices146If you're running multiple conversations, capture the session ID to resume a specific one:

171 

172* **Use JSON output format** for programmatic parsing of responses:

173 

174 ```bash theme={null}

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 

181* **Handle errors gracefully** - check exit codes and stderr:

182 

183 ```bash theme={null}

184 if ! claude -p "$prompt" 2>error.log; then

185 echo "Error occurred:" >&2

186 cat error.log >&2

187 exit 1

188 fi

189 ```

190 147 

191* **Use session management** for maintaining context in multi-turn conversations148```bash theme={null}

149session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')

150claude -p "Continue that review" --resume "$session_id"

151```

192 152 

193* **Consider timeouts** for long-running operations:153## Next steps

194 154 

195 ```bash theme={null}155<CardGroup cols={2}>

196 timeout 300 claude -p "$complex_prompt" || echo "Timed out after 5 minutes"156 <Card title="Agent SDK quickstart" icon="play" href="https://platform.claude.com/docs/en/agent-sdk/quickstart">

197 ```157 Build your first agent with Python or TypeScript

158 </Card>

198 159 

199* **Respect rate limits** when making multiple requests by adding delays between calls160 <Card title="CLI reference" icon="terminal" href="/en/cli-reference">

161 Explore all CLI flags and options

162 </Card>

200 163 

201## Related Resources164 <Card title="GitHub Actions" icon="github" href="/en/github-actions">

165 Use the Agent SDK in GitHub workflows

166 </Card>

202 167 

203* [CLI usage and controls](/en/cli-reference) - Complete CLI documentation168 <Card title="GitLab CI/CD" icon="gitlab" href="/en/gitlab-ci-cd">

204* [Common workflows](/en/common-workflows) - Step-by-step guides for common use cases169 Use the Agent SDK in GitLab pipelines

170 </Card>

171</CardGroup>

hooks.md +1144 −718

Details

1> ## Documentation Index

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

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

4 

1# Hooks reference5# Hooks reference

2 6 

3> This page provides reference documentation for implementing hooks in Claude Code.7> Reference for Claude Code hook events, configuration schema, JSON input/output formats, exit codes, async hooks, prompt hooks, and MCP tool hooks.

4 8 

5<Tip>9<Tip>

6 For a quickstart guide with examples, see [Get started with Claude Code hooks](/en/hooks-guide).10 For a quickstart guide with examples, see [Automate workflows with hooks](/en/hooks-guide).

7</Tip>11</Tip>

8 12 

9## Configuration13Hooks are user-defined shell commands or LLM prompts that execute automatically at specific points in Claude Code's lifecycle. Use this reference to look up event schemas, configuration options, JSON input/output formats, and advanced features like async hooks and MCP tool hooks. If you're setting up hooks for the first time, start with the [guide](/en/hooks-guide) instead.

14 

15## Hook lifecycle

16 

17Hooks fire at specific points during a Claude Code session. When an event fires and a matcher matches, Claude Code passes JSON context about the event to your hook handler. For command hooks, this arrives on stdin. Your handler can then inspect the input, take action, and optionally return a decision. Some events fire once per session, while others fire repeatedly inside the agentic loop:

10 18 

11Claude Code hooks are configured in your [settings files](/en/settings):19<div style={{maxWidth: "500px", margin: "0 auto"}}>

20 <Frame>

21 <img src="https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=7a351ea1cc3d5da7a2176bf51196bc1a" alt="Hook lifecycle diagram showing the sequence of hooks from SessionStart through the agentic loop to SessionEnd" data-og-width="520" width="520" data-og-height="960" height="960" data-path="images/hooks-lifecycle.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?w=280&fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=8f32c67d025f0a318d5ed10a4f8ff2e6 280w, https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?w=560&fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=896fc424e39ff8d590720331a77e3d80 560w, https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?w=840&fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=a1c1c9739cde965e1eade843cee567c5 840w, https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?w=1100&fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=5bb083988de020e7d568e8dd8f1422fc 1100w, https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?w=1650&fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=343e9883c1e3172f08096c352aa46f12 1650w, https://mintcdn.com/claude-code/tpQvD9DKENFo4zX_/images/hooks-lifecycle.svg?w=2500&fit=max&auto=format&n=tpQvD9DKENFo4zX_&q=85&s=4de37b29de0f6df8b0c3e937a76c3bc6 2500w" />

22 </Frame>

23</div>

12 24 

13* `~/.claude/settings.json` - User settings25The 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.

14* `.claude/settings.json` - Project settings

15* `.claude/settings.local.json` - Local project settings (not committed)

16* Enterprise managed policy settings

17 26 

18### Structure27| 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| `PostToolUse` | After a tool call succeeds |

34| `PostToolUseFailure` | After a tool call fails |

35| `Notification` | When Claude Code sends a notification |

36| `SubagentStart` | When a subagent is spawned |

37| `SubagentStop` | When a subagent finishes |

38| `Stop` | When Claude finishes responding |

39| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

40| `TaskCompleted` | When a task is being marked as completed |

41| `PreCompact` | Before context compaction |

42| `SessionEnd` | When a session terminates |

19 43 

20Hooks are organized by matchers, where each matcher can have multiple hooks:44### How a hook resolves

45 

46To see how these pieces fit together, consider this `PreToolUse` hook that blocks destructive shell commands. The hook runs `block-rm.sh` before every Bash tool call:

21 47 

22```json theme={null}48```json theme={null}

23{49{

24 "hooks": {50 "hooks": {

25 "EventName": [51 "PreToolUse": [

26 {52 {

27 "matcher": "ToolPattern",53 "matcher": "Bash",

28 "hooks": [54 "hooks": [

29 {55 {

30 "type": "command",56 "type": "command",

31 "command": "your-command-here"57 "command": ".claude/hooks/block-rm.sh"

32 }58 }

33 ]59 ]

34 }60 }


37}63}

38```64```

39 65 

40* **matcher**: Pattern to match tool names, case-sensitive (only applicable for66The 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 

52For events like `UserPromptSubmit`, `Stop`, and `SubagentStop`

53that don't use matchers, you can omit the matcher field:

54 67 

55```json theme={null}68```bash theme={null}

56{69#!/bin/bash

57 "hooks": {70# .claude/hooks/block-rm.sh

58 "UserPromptSubmit": [71COMMAND=$(jq -r '.tool_input.command')

59 {72 

60 "hooks": [73if echo "$COMMAND" | grep -q 'rm -rf'; then

61 {74 jq -n '{

62 "type": "command",75 hookSpecificOutput: {

63 "command": "/path/to/prompt-validator.py"76 hookEventName: "PreToolUse",

64 }77 permissionDecision: "deny",

65 ]78 permissionDecisionReason: "Destructive command blocked by hook"

66 }

67 ]

68 }79 }

69}80 }'

81else

82 exit 0 # allow the command

83fi

70```84```

71 85 

72### Project-Specific Hook Scripts86Now suppose Claude Code decides to run `Bash "rm -rf /tmp/build"`. Here's what happens:

73 87 

74You can use the environment variable `CLAUDE_PROJECT_DIR` (only available when88<Frame>

75Claude Code spawns the hook command) to reference scripts stored in your project,89 <img src="https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=7c13f51ffcbc37d22a593b27e2f2de72" alt="Hook resolution flow: PreToolUse event fires, matcher checks for Bash match, hook handler runs, result returns to Claude Code" data-og-width="780" width="780" data-og-height="290" height="290" data-path="images/hook-resolution.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=280&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=36a39a07e8bc1995dcb4639e09846905 280w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=560&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=6568d90c596c7605bbac2c325b0a0c86 560w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=840&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=255a6f68b9475a0e41dbde7b88002dad 840w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=1100&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=dcecf8d5edc88cd2bc49deb006d5760d 1100w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=1650&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=04fe51bf69ae375e9fd517f18674e35f 1650w, https://mintcdn.com/claude-code/s7NM0vfd_wres2nf/images/hook-resolution.svg?w=2500&fit=max&auto=format&n=s7NM0vfd_wres2nf&q=85&s=b1b76e0b77fddb5c7fa7bf302dacd80b 2500w" />

76ensuring they work regardless of Claude's current directory:90</Frame>

77 91 

78```json theme={null}92<Steps>

79{93 <Step title="Event fires">

80 "hooks": {94 The `PreToolUse` event fires. Claude Code sends the tool input as JSON on stdin to the hook:

81 "PostToolUse": [95 

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

83 "matcher": "Write|Edit",97 { "tool_name": "Bash", "tool_input": { "command": "rm -rf /tmp/build" }, ... }

84 "hooks": [98 ```

99 </Step>

100 

101 <Step title="Matcher checks">

102 The matcher `"Bash"` matches the tool name, so `block-rm.sh` runs. If you omit the matcher or use `"*"`, the hook runs on every occurrence of the event. Hooks only skip when a matcher is defined and doesn't match.

103 </Step>

104 

105 <Step title="Hook handler runs">

106 The script extracts `"rm -rf /tmp/build"` from the input and finds `rm -rf`, so it prints a decision to stdout:

107 

108 ```json theme={null}

85 {109 {

86 "type": "command",110 "hookSpecificOutput": {

87 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"111 "hookEventName": "PreToolUse",

88 }112 "permissionDecision": "deny",

89 ]113 "permissionDecisionReason": "Destructive command blocked by hook"

90 }114 }

91 ]

92 }115 }

93}116 ```

94```117 

118 If the command had been safe (like `npm test`), the script would hit `exit 0` instead, which tells Claude Code to allow the tool call with no further action.

119 </Step>

120 

121 <Step title="Claude Code acts on the result">

122 Claude Code reads the JSON decision, blocks the tool call, and shows Claude the reason.

123 </Step>

124</Steps>

95 125 

96### Plugin hooks126The [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.

97 127 

98[Plugins](/en/plugins) can provide hooks that integrate seamlessly with your user and project hooks. Plugin hooks are automatically merged with your configuration when plugins are enabled.128## Configuration

129 

130Hooks are defined in JSON settings files. The configuration has three levels of nesting:

131 

1321. Choose a [hook event](#hook-events) to respond to, like `PreToolUse` or `Stop`

1332. Add a [matcher group](#matcher-patterns) to filter when it fires, like "only for the Bash tool"

1343. Define one or more [hook handlers](#hook-handler-fields) to run when matched

135 

136See [How a hook resolves](#how-a-hook-resolves) above for a complete walkthrough with an annotated example.

137 

138<Note>

139 This page uses specific terms for each level: **hook event** for the lifecycle point, **matcher group** for the filter, and **hook handler** for the shell command, prompt, or agent that runs. "Hook" on its own refers to the general feature.

140</Note>

99 141 

100**How plugin hooks work**:142### Hook locations

101 143 

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.144Where you define a hook determines its scope:

103* When a plugin is enabled, its hooks are merged with user and project hooks

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 145 

107**Example plugin hook configuration**:146| Location | Scope | Shareable |

147| :--------------------------------------------------------- | :---------------------------- | :--------------------------------- |

148| `~/.claude/settings.json` | All your projects | No, local to your machine |

149| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

150| `.claude/settings.local.json` | Single project | No, gitignored |

151| Managed policy settings | Organization-wide | Yes, admin-controlled |

152| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

153| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the component is active | Yes, defined in the component file |

154 

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

156 

157### Matcher patterns

158 

159The `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:

160 

161| Event | What the matcher filters | Example matcher values |

162| :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- |

163| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

164| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

165| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

166| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

167| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

168| `PreCompact` | what triggered compaction | `manual`, `auto` |

169| `SubagentStop` | agent type | same values as `SubagentStart` |

170| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted` | no matcher support | always fires on every occurrence |

171 

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

173 

174This example runs a linting script only when Claude writes or edits a file:

108 175 

109```json theme={null}176```json theme={null}

110{177{

111 "description": "Automatic code formatting",

112 "hooks": {178 "hooks": {

113 "PostToolUse": [179 "PostToolUse": [

114 {180 {

115 "matcher": "Write|Edit",181 "matcher": "Edit|Write",

116 "hooks": [182 "hooks": [

117 {183 {

118 "type": "command",184 "type": "command",

119 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",185 "command": "/path/to/lint-check.sh"

120 "timeout": 30

121 }186 }

122 ]187 ]

123 }188 }


126}191}

127```192```

128 193 

129<Note>194`UserPromptSubmit` and `Stop` don't support matchers and always fire on every occurrence. If you add a `matcher` field to these events, it is silently ignored.

130 Plugin hooks use the same format as regular hooks with an optional `description` field to explain the hook's purpose.

131</Note>

132 195 

133<Note>196#### Match MCP tools

134 Plugin hooks run alongside your custom hooks. If multiple hooks match an event, they all execute in parallel.

135</Note>

136 197 

137**Environment variables for plugins**:198[MCP](/en/mcp) server tools appear as regular tools in tool events (`PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`), so you can match them the same way you match any other tool name.

138 199 

139* `${CLAUDE_PLUGIN_ROOT}`: Absolute path to the plugin directory200MCP tools follow the naming pattern `mcp__<server>__<tool>`, for example:

140* `${CLAUDE_PROJECT_DIR}`: Project root directory (same as for project hooks)

141* All standard environment variables are available

142 201 

143See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.202* `mcp__memory__create_entities`: Memory server's create entities tool

203* `mcp__filesystem__read_file`: Filesystem server's read file tool

204* `mcp__github__search_repositories`: GitHub server's search tool

144 205 

145## Prompt-Based Hooks206Use regex patterns to target specific MCP tools or groups of tools:

146 207 

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.208* `mcp__memory__.*` matches all tools from the `memory` server

209* `mcp__.*__write.*` matches any tool containing "write" from any server

148 210 

149### How prompt-based hooks work211This example logs all memory server operations and validates write operations from any MCP server:

150 

151Instead of executing a bash command, prompt-based hooks:

152 

1531. Send the hook input and your prompt to a fast LLM (Haiku)

1542. The LLM responds with structured JSON containing a decision

1553. Claude Code processes the decision automatically

156 

157### Configuration

158 212 

159```json theme={null}213```json theme={null}

160{214{

161 "hooks": {215 "hooks": {

162 "Stop": [216 "PreToolUse": [

163 {217 {

218 "matcher": "mcp__memory__.*",

164 "hooks": [219 "hooks": [

165 {220 {

166 "type": "prompt",221 "type": "command",

167 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."222 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

223 }

224 ]

225 },

226 {

227 "matcher": "mcp__.*__write.*",

228 "hooks": [

229 {

230 "type": "command",

231 "command": "/home/user/scripts/validate-mcp-write.py"

168 }232 }

169 ]233 ]

170 }234 }


173}237}

174```238```

175 239 

176**Fields:**240### Hook handler fields

177 241 

178* `type`: Must be `"prompt"`242Each object in the inner `hooks` array is a hook handler: the shell command, LLM prompt, or agent that runs when the matcher matches. There are three types:

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 243 

184### Response schema244* **[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.

245* **[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).

246* **[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).

185 247 

186The LLM must respond with JSON containing:248#### Common fields

187 249 

188```json theme={null}250These fields apply to all hook types:

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 251 

198**Response fields:**252| Field | Required | Description |

253| :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |

254| `type` | yes | `"command"`, `"prompt"`, or `"agent"` |

255| `timeout` | no | Seconds before canceling. Defaults: 600 for command, 30 for prompt, 60 for agent |

256| `statusMessage` | no | Custom spinner message displayed while the hook runs |

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

199 258 

200* `decision`: `"approve"` allows the action, `"block"` prevents it259#### Command hook fields

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 260 

206### Supported hook events261In addition to the [common fields](#common-fields), command hooks accept these fields:

207 262 

208Prompt-based hooks work with any hook event, but are most useful for:263| Field | Required | Description |

264| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------ |

265| `command` | yes | Shell command to execute |

266| `async` | no | If `true`, runs in the background without blocking. See [Run hooks in the background](#run-hooks-in-the-background) |

209 267 

210* **Stop**: Intelligently decide if Claude should continue working268#### Prompt and agent hook fields

211* **SubagentStop**: Evaluate if a subagent has completed its task

212* **UserPromptSubmit**: Validate user prompts with LLM assistance

213* **PreToolUse**: Make context-aware permission decisions

214 269 

215### Example: Intelligent Stop hook270In addition to the [common fields](#common-fields), prompt and agent hooks accept these fields:

216 271 

217```json theme={null}272| Field | Required | Description |

218{273| :------- | :------- | :------------------------------------------------------------------------------------------ |

274| `prompt` | yes | Prompt text to send to the model. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

275| `model` | no | Model to use for evaluation. Defaults to a fast model |

276 

277All matching hooks run in parallel, and identical handlers are deduplicated automatically. Handlers run in the current directory with Claude Code's environment. The `$CLAUDE_CODE_REMOTE` environment variable is set to `"true"` in remote web environments and not set in the local CLI.

278 

279### Reference scripts by path

280 

281Use environment variables to reference hook scripts relative to the project or plugin root, regardless of the working directory when the hook runs:

282 

283* `$CLAUDE_PROJECT_DIR`: the project root. Wrap in quotes to handle paths with spaces.

284* `${CLAUDE_PLUGIN_ROOT}`: the plugin's root directory, for scripts bundled with a [plugin](/en/plugins).

285 

286<Tabs>

287 <Tab title="Project scripts">

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

289 

290 ```json theme={null}

291 {

219 "hooks": {292 "hooks": {

220 "Stop": [293 "PostToolUse": [

221 {294 {

295 "matcher": "Write|Edit",

222 "hooks": [296 "hooks": [

223 {297 {

224 "type": "prompt",298 "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\"}",299 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh"

226 "timeout": 30

227 }300 }

228 ]301 ]

229 }302 }

230 ]303 ]

231 }304 }

232}305 }

233```306 ```

307 </Tab>

234 308 

235### Example: SubagentStop with custom logic309 <Tab title="Plugin scripts">

310 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 311 

237```json theme={null}312 This example runs a formatting script bundled with the plugin:

238{313 

314 ```json theme={null}

315 {

316 "description": "Automatic code formatting",

239 "hooks": {317 "hooks": {

240 "SubagentStop": [318 "PostToolUse": [

241 {319 {

320 "matcher": "Write|Edit",

242 "hooks": [321 "hooks": [

243 {322 {

244 "type": "prompt",323 "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\"}"324 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",

325 "timeout": 30

246 }326 }

247 ]327 ]

248 }328 }

249 ]329 ]

250 }330 }

251}331 }

332 ```

333 

334 See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.

335 </Tab>

336</Tabs>

337 

338### Hooks in skills and agents

339 

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

341 

342All hook events are supported. For subagents, `Stop` hooks are automatically converted to `SubagentStop` since that is the event that fires when a subagent completes.

343 

344Hooks use the same configuration format as settings-based hooks but are scoped to the component's lifetime and cleaned up when it finishes.

345 

346This skill defines a `PreToolUse` hook that runs a security validation script before each `Bash` command:

347 

348```yaml theme={null}

349---

350name: secure-operations

351description: Perform operations with security checks

352hooks:

353 PreToolUse:

354 - matcher: "Bash"

355 hooks:

356 - type: command

357 command: "./scripts/security-check.sh"

358---

252```359```

253 360 

254### Comparison with bash command hooks361Agents use the same format in their YAML frontmatter.

255 362 

256| Feature | Bash Command Hooks | Prompt-Based Hooks |363### 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 364 

265### Best practices365Type `/hooks` in Claude Code to open the interactive hooks manager, where you can view, add, and delete hooks without editing settings files directly. For a step-by-step walkthrough, see [Set up your first hook](/en/hooks-guide#set-up-your-first-hook) in the guide.

266 366 

267* **Be specific in prompts**: Clearly state what you want the LLM to evaluate367Each hook in the menu is labeled with a bracket prefix indicating its source:

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 368 

273See the [plugin components reference](/en/plugins-reference#hooks) for details on creating plugin hooks.369* `[User]`: from `~/.claude/settings.json`

370* `[Project]`: from `.claude/settings.json`

371* `[Local]`: from `.claude/settings.local.json`

372* `[Plugin]`: from a plugin's `hooks/hooks.json`, read-only

274 373 

275## Hook Events374### Disable or remove hooks

276 375 

277### PreToolUse376To remove a hook, delete its entry from the settings JSON file, or use the `/hooks` menu and select the hook to delete it.

278 377 

279Runs after Claude creates tool parameters and before processing the tool call.378To temporarily disable all hooks without removing them, set `"disableAllHooks": true` in your settings file or use the toggle in the `/hooks` menu. There is no way to disable an individual hook while keeping it in the configuration.

280 379 

281**Common matchers:**380Direct edits to hooks in settings files don't take effect immediately. Claude Code captures a snapshot of hooks at startup and uses it throughout the session. This prevents malicious or accidental hook modifications from taking effect mid-session without your review. If hooks are modified externally, Claude Code warns you and requires review in the `/hooks` menu before changes apply.

282 381 

283* `Task` - Subagent tasks (see [subagents documentation](/en/sub-agents))382## Hook input and output

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 383 

292Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.384Hooks receive JSON data via stdin and communicate results through exit codes, stdout, and stderr. This section covers fields and behavior common to all events. Each event's section under [Hook events](#hook-events) includes its specific input schema and decision control options.

293 385 

294### PermissionRequest386### Common input fields

295 387 

296Runs when the user is shown a permission dialog.388All hook events receive these fields via stdin as JSON, in addition to event-specific fields documented in each [hook event](#hook-events) section:

297Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

298 389 

299Recognizes the same matcher values as PreToolUse.390| Field | Description |

391| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- |

392| `session_id` | Current session identifier |

393| `transcript_path` | Path to conversation JSON |

394| `cwd` | Current working directory when the hook is invoked |

395| `permission_mode` | Current [permission mode](/en/permissions#permission-modes): `"default"`, `"plan"`, `"acceptEdits"`, `"dontAsk"`, or `"bypassPermissions"` |

396| `hook_event_name` | Name of the event that fired |

300 397 

301### PostToolUse398For example, a `PreToolUse` hook for a Bash command receives this on stdin:

302 399 

303Runs immediately after a tool completes successfully.400```json theme={null}

401{

402 "session_id": "abc123",

403 "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",

404 "cwd": "/home/user/my-project",

405 "permission_mode": "default",

406 "hook_event_name": "PreToolUse",

407 "tool_name": "Bash",

408 "tool_input": {

409 "command": "npm test"

410 }

411}

412```

304 413 

305Recognizes the same matcher values as PreToolUse.414The `tool_name` and `tool_input` fields are event-specific. Each [hook event](#hook-events) section documents the additional fields for that event.

306 415 

307### Notification416### Exit code output

417 

418The exit code from your hook command tells Claude Code whether the action should proceed, be blocked, or be ignored.

419 

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

421 

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

423 

424**Any other exit code** is a non-blocking error. stderr is shown in verbose mode (`Ctrl+O`) and execution continues.

425 

426For example, a hook command script that blocks dangerous Bash commands:

427 

428```bash theme={null}

429#!/bin/bash

430# Reads JSON input from stdin, checks the command

431command=$(jq -r '.tool_input.command' < /dev/stdin)

432 

433if [[ "$command" == rm* ]]; then

434 echo "Blocked: rm commands are not allowed" >&2

435 exit 2 # Blocking error: tool call is prevented

436fi

437 

438exit 0 # Success: tool call proceeds

439```

440 

441#### Exit code 2 behavior per event

442 

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

444 

445| Hook event | Can block? | What happens on exit 2 |

446| :------------------- | :--------- | :----------------------------------------------------------------- |

447| `PreToolUse` | Yes | Blocks the tool call |

448| `PermissionRequest` | Yes | Denies the permission |

449| `UserPromptSubmit` | Yes | Blocks prompt processing and erases the prompt |

450| `Stop` | Yes | Prevents Claude from stopping, continues the conversation |

451| `SubagentStop` | Yes | Prevents the subagent from stopping |

452| `TeammateIdle` | Yes | Prevents the teammate from going idle (teammate continues working) |

453| `TaskCompleted` | Yes | Prevents the task from being marked as completed |

454| `PostToolUse` | No | Shows stderr to Claude (tool already ran) |

455| `PostToolUseFailure` | No | Shows stderr to Claude (tool already failed) |

456| `Notification` | No | Shows stderr to user only |

457| `SubagentStart` | No | Shows stderr to user only |

458| `SessionStart` | No | Shows stderr to user only |

459| `SessionEnd` | No | Shows stderr to user only |

460| `PreCompact` | No | Shows stderr to user only |

461 

462### JSON output

308 463 

309Runs when Claude Code sends notifications. Supports matchers to filter by notification type.464Exit 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.

310 465 

311**Common matchers:**466<Note>

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

468</Note>

469 

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

471 

472The JSON object supports three kinds of fields:

312 473 

313* `permission_prompt` - Permission requests from Claude Code474* **Universal fields** like `continue` work across all events. These are listed in the table below.

314* `idle_prompt` - When Claude is waiting for user input (after 60+ seconds of idle time)475* **Top-level `decision` and `reason`** are used by some events to block or provide feedback.

315* `auth_success` - Authentication success notifications476* **`hookSpecificOutput`** is a nested object for events that need richer control. It requires a `hookEventName` field set to the event name.

316* `elicitation_dialog` - When Claude Code needs input for MCP tool elicitation

317 477 

318You can use matchers to run different hooks for different notification types, or omit the matcher to run hooks for all notifications.478| Field | Default | Description |

479| :--------------- | :------ | :------------------------------------------------------------------------------------------------------------------------- |

480| `continue` | `true` | If `false`, Claude stops processing entirely after the hook runs. Takes precedence over any event-specific decision fields |

481| `stopReason` | none | Message shown to the user when `continue` is `false`. Not shown to Claude |

482| `suppressOutput` | `false` | If `true`, hides stdout from verbose mode output |

483| `systemMessage` | none | Warning message shown to the user |

319 484 

320**Example: Different notifications for different types**485To stop Claude entirely regardless of event type:

321 486 

322```json theme={null}487```json theme={null}

323{488{ "continue": false, "stopReason": "Build failed, fix errors before continuing" }

324 "hooks": {489```

325 "Notification": [490 

326 {491#### Decision control

327 "matcher": "permission_prompt",492 

328 "hooks": [493Not 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:

494 

495| Events | Decision pattern | Key fields |

496| :-------------------------------------------------------------------- | :------------------- | :---------------------------------------------------------------- |

497| UserPromptSubmit, PostToolUse, PostToolUseFailure, Stop, SubagentStop | Top-level `decision` | `decision: "block"`, `reason` |

498| TeammateIdle, TaskCompleted | Exit code only | Exit code 2 blocks the action, stderr is fed back as feedback |

499| PreToolUse | `hookSpecificOutput` | `permissionDecision` (allow/deny/ask), `permissionDecisionReason` |

500| PermissionRequest | `hookSpecificOutput` | `decision.behavior` (allow/deny) |

501 

502Here are examples of each pattern in action:

503 

504<Tabs>

505 <Tab title="Top-level decision">

506 Used by `UserPromptSubmit`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SubagentStop`. The only value is `"block"`. To allow the action to proceed, omit `decision` from your JSON, or exit 0 without any JSON at all:

507 

508 ```json theme={null}

329 {509 {

330 "type": "command",510 "decision": "block",

331 "command": "/path/to/permission-alert.sh"511 "reason": "Test suite must pass before proceeding"

332 }512 }

333 ]513 ```

334 },514 </Tab>

515 

516 <Tab title="PreToolUse">

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

518 

519 ```json theme={null}

335 {520 {

336 "matcher": "idle_prompt",521 "hookSpecificOutput": {

337 "hooks": [522 "hookEventName": "PreToolUse",

523 "permissionDecision": "deny",

524 "permissionDecisionReason": "Database writes are not allowed"

525 }

526 }

527 ```

528 </Tab>

529 

530 <Tab title="PermissionRequest">

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

532 

533 ```json theme={null}

338 {534 {

339 "type": "command",535 "hookSpecificOutput": {

340 "command": "/path/to/idle-notification.sh"536 "hookEventName": "PermissionRequest",

537 "decision": {

538 "behavior": "allow",

539 "updatedInput": {

540 "command": "npm run lint"

341 }541 }

342 ]

343 }542 }

344 ]

345 }543 }

346}544 }

347```545 ```

546 </Tab>

547</Tabs>

348 548 

349### UserPromptSubmit549For 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).

350 550 

351Runs when the user submits a prompt, before Claude processes it. This allows you551## Hook events

352to add additional context based on the prompt/conversation, validate prompts, or

353block certain types of prompts.

354 552 

355### Stop553Each 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.

356 554 

357Runs when the main Claude Code agent has finished responding. Does not run if555### SessionStart

358the stoppage occurred due to a user interrupt.

359 556 

360### SubagentStop557Runs 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.

361 558 

362Runs when a Claude Code subagent (Task tool call) has finished responding.559SessionStart runs on every session, so keep these hooks fast.

363 560 

364### PreCompact561The matcher value corresponds to how the session was initiated:

365 562 

366Runs before Claude Code is about to run a compact operation.563| Matcher | When it fires |

564| :-------- | :------------------------------------- |

565| `startup` | New session |

566| `resume` | `--resume`, `--continue`, or `/resume` |

567| `clear` | `/clear` |

568| `compact` | Auto or manual compaction |

367 569 

368**Matchers:**570#### SessionStart input

369 571 

370* `manual` - Invoked from `/compact`572In 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.

371* `auto` - Invoked from auto-compact (due to full context window)

372 573 

373### SessionStart574```json theme={null}

575{

576 "session_id": "abc123",

577 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

578 "cwd": "/Users/...",

579 "permission_mode": "default",

580 "hook_event_name": "SessionStart",

581 "source": "startup",

582 "model": "claude-sonnet-4-5-20250929"

583}

584```

374 585 

375Runs when Claude Code starts a new session or resumes an existing session (which586#### SessionStart decision control

376currently does start a new session under the hood). Useful for loading in

377development context like existing issues or recent changes to your codebase, installing dependencies, or setting up environment variables.

378 587 

379**Matchers:**588Any 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:

380 589 

381* `startup` - Invoked from startup590| Field | Description |

382* `resume` - Invoked from `--resume`, `--continue`, or `/resume`591| :------------------ | :------------------------------------------------------------------------ |

383* `clear` - Invoked from `/clear`592| `additionalContext` | String added to Claude's context. Multiple hooks' values are concatenated |

384* `compact` - Invoked from auto or manual compact.

385 593 

386#### Persisting environment variables594```json theme={null}

595{

596 "hookSpecificOutput": {

597 "hookEventName": "SessionStart",

598 "additionalContext": "My additional context here"

599 }

600}

601```

602 

603#### Persist environment variables

387 604 

388SessionStart 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.605SessionStart 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.

389 606 

390**Example: Setting individual environment variables**607To set individual environment variables, write `export` statements to `CLAUDE_ENV_FILE`. Use append (`>>`) to preserve variables set by other hooks:

391 608 

392```bash theme={null}609```bash theme={null}

393#!/bin/bash610#!/bin/bash

394 611 

395if [ -n "$CLAUDE_ENV_FILE" ]; then612if [ -n "$CLAUDE_ENV_FILE" ]; then

396 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"613 echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"

397 echo 'export API_KEY=your-api-key' >> "$CLAUDE_ENV_FILE"614 echo 'export DEBUG_LOG=true' >> "$CLAUDE_ENV_FILE"

398 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"615 echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"

399fi616fi

400 617 

401exit 0618exit 0

402```619```

403 620 

404**Example: Persisting all environment changes from the hook**621To capture all environment changes from setup commands, compare the exported variables before and after:

405 

406When your setup modifies the environment (e.g., `nvm use`), capture and persist all changes by diffing the environment:

407 622 

408```bash theme={null}623```bash theme={null}

409#!/bin/bash624#!/bin/bash


422exit 0637exit 0

423```638```

424 639 

425Any variables written to this file will be available in all subsequent bash commands that Claude Code executes during the session.640Any variables written to this file will be available in all subsequent Bash commands that Claude Code executes during the session.

426 641 

427<Note>642<Note>

428 `CLAUDE_ENV_FILE` is only available for SessionStart hooks. Other hook types do not have access to this variable.643 `CLAUDE_ENV_FILE` is available for SessionStart hooks. Other hook types do not have access to this variable.

429</Note>644</Note>

430 645 

431### SessionEnd646### UserPromptSubmit

432 647 

433Runs when a Claude Code session ends. Useful for cleanup tasks, logging session648Runs when the user submits a prompt, before Claude processes it. This allows you

434statistics, or saving session state.649to add additional context based on the prompt/conversation, validate prompts, or

650block certain types of prompts.

651 

652#### UserPromptSubmit input

653 

654In addition to the [common input fields](#common-input-fields), UserPromptSubmit hooks receive the `prompt` field containing the text the user submitted.

655 

656```json theme={null}

657{

658 "session_id": "abc123",

659 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

660 "cwd": "/Users/...",

661 "permission_mode": "default",

662 "hook_event_name": "UserPromptSubmit",

663 "prompt": "Write a function to calculate the factorial of a number"

664}

665```

666 

667#### UserPromptSubmit decision control

668 

669`UserPromptSubmit` hooks can control whether a user prompt is processed and add context. All [JSON output fields](#json-output) are available.

670 

671There are two ways to add context to the conversation on exit code 0:

672 

673* **Plain text stdout**: any non-JSON text written to stdout is added as context

674* **JSON with `additionalContext`**: use the JSON format below for more control. The `additionalContext` field is added as context

675 

676Plain stdout is shown as hook output in the transcript. The `additionalContext` field is added more discretely.

677 

678To block a prompt, return a JSON object with `decision` set to `"block"`:

679 

680| Field | Description |

681| :------------------ | :----------------------------------------------------------------------------------------------------------------- |

682| `decision` | `"block"` prevents the prompt from being processed and erases it from context. Omit to allow the prompt to proceed |

683| `reason` | Shown to the user when `decision` is `"block"`. Not added to context |

684| `additionalContext` | String added to Claude's context |

685 

686```json theme={null}

687{

688 "decision": "block",

689 "reason": "Explanation for decision",

690 "hookSpecificOutput": {

691 "hookEventName": "UserPromptSubmit",

692 "additionalContext": "My additional context here"

693 }

694}

695```

696 

697<Note>

698 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

699 block prompts or want more structured control.

700</Note>

701 

702### PreToolUse

703 

704Runs after Claude creates tool parameters and before processing the tool call. Matches on tool name: `Bash`, `Edit`, `Write`, `Read`, `Glob`, `Grep`, `Task`, `WebFetch`, `WebSearch`, and any [MCP tool names](#match-mcp-tools).

705 

706Use [PreToolUse decision control](#pretooluse-decision-control) to allow, deny, or ask for permission to use the tool.

707 

708#### PreToolUse input

709 

710In 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:

711 

712##### Bash

713 

714Executes shell commands.

715 

716| Field | Type | Example | Description |

717| :------------------ | :------ | :----------------- | :-------------------------------------------- |

718| `command` | string | `"npm test"` | The shell command to execute |

719| `description` | string | `"Run test suite"` | Optional description of what the command does |

720| `timeout` | number | `120000` | Optional timeout in milliseconds |

721| `run_in_background` | boolean | `false` | Whether to run the command in background |

722 

723##### Write

724 

725Creates or overwrites a file.

726 

727| Field | Type | Example | Description |

728| :---------- | :----- | :-------------------- | :--------------------------------- |

729| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to write |

730| `content` | string | `"file content"` | Content to write to the file |

731 

732##### Edit

733 

734Replaces a string in an existing file.

735 

736| Field | Type | Example | Description |

737| :------------ | :------ | :-------------------- | :--------------------------------- |

738| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to edit |

739| `old_string` | string | `"original text"` | Text to find and replace |

740| `new_string` | string | `"replacement text"` | Replacement text |

741| `replace_all` | boolean | `false` | Whether to replace all occurrences |

742 

743##### Read

744 

745Reads file contents.

746 

747| Field | Type | Example | Description |

748| :---------- | :----- | :-------------------- | :----------------------------------------- |

749| `file_path` | string | `"/path/to/file.txt"` | Absolute path to the file to read |

750| `offset` | number | `10` | Optional line number to start reading from |

751| `limit` | number | `50` | Optional number of lines to read |

752 

753##### Glob

754 

755Finds files matching a glob pattern.

756 

757| Field | Type | Example | Description |

758| :-------- | :----- | :--------------- | :--------------------------------------------------------------------- |

759| `pattern` | string | `"**/*.ts"` | Glob pattern to match files against |

760| `path` | string | `"/path/to/dir"` | Optional directory to search in. Defaults to current working directory |

761 

762##### Grep

763 

764Searches file contents with regular expressions.

765 

766| Field | Type | Example | Description |

767| :------------ | :------ | :--------------- | :------------------------------------------------------------------------------------ |

768| `pattern` | string | `"TODO.*fix"` | Regular expression pattern to search for |

769| `path` | string | `"/path/to/dir"` | Optional file or directory to search in |

770| `glob` | string | `"*.ts"` | Optional glob pattern to filter files |

771| `output_mode` | string | `"content"` | `"content"`, `"files_with_matches"`, or `"count"`. Defaults to `"files_with_matches"` |

772| `-i` | boolean | `true` | Case insensitive search |

773| `multiline` | boolean | `false` | Enable multiline matching |

774 

775##### WebFetch

776 

777Fetches and processes web content.

778 

779| Field | Type | Example | Description |

780| :------- | :----- | :---------------------------- | :----------------------------------- |

781| `url` | string | `"https://example.com/api"` | URL to fetch content from |

782| `prompt` | string | `"Extract the API endpoints"` | Prompt to run on the fetched content |

783 

784##### WebSearch

785 

786Searches the web.

787 

788| Field | Type | Example | Description |

789| :---------------- | :----- | :----------------------------- | :------------------------------------------------ |

790| `query` | string | `"react hooks best practices"` | Search query |

791| `allowed_domains` | array | `["docs.example.com"]` | Optional: only include results from these domains |

792| `blocked_domains` | array | `["spam.example.com"]` | Optional: exclude results from these domains |

793 

794##### Task

795 

796Spawns a [subagent](/en/sub-agents).

797 

798| Field | Type | Example | Description |

799| :-------------- | :----- | :------------------------- | :------------------------------------------- |

800| `prompt` | string | `"Find all API endpoints"` | The task for the agent to perform |

801| `description` | string | `"Find API endpoints"` | Short description of the task |

802| `subagent_type` | string | `"Explore"` | Type of specialized agent to use |

803| `model` | string | `"sonnet"` | Optional model alias to override the default |

804 

805#### PreToolUse decision control

806 

807`PreToolUse` hooks can control whether a tool call proceeds. Unlike other hooks that use a top-level `decision` field, PreToolUse returns its decision inside a `hookSpecificOutput` object. This gives it richer control: three outcomes (allow, deny, or ask) plus the ability to modify tool input before execution.

808 

809| Field | Description |

810| :------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |

811| `permissionDecision` | `"allow"` bypasses the permission system, `"deny"` prevents the tool call, `"ask"` prompts the user to confirm |

812| `permissionDecisionReason` | For `"allow"` and `"ask"`, shown to the user but not Claude. For `"deny"`, shown to Claude |

813| `updatedInput` | Modifies the tool's input parameters before execution. Combine with `"allow"` to auto-approve, or `"ask"` to show the modified input to the user |

814| `additionalContext` | String added to Claude's context before the tool executes |

815 

816```json theme={null}

817{

818 "hookSpecificOutput": {

819 "hookEventName": "PreToolUse",

820 "permissionDecision": "allow",

821 "permissionDecisionReason": "My reason here",

822 "updatedInput": {

823 "field_to_modify": "new value"

824 },

825 "additionalContext": "Current environment: production. Proceed with caution."

826 }

827}

828```

829 

830<Note>

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

832</Note>

833 

834### PermissionRequest

835 

836Runs when the user is shown a permission dialog.

837Use [PermissionRequest decision control](#permissionrequest-decision-control) to allow or deny on behalf of the user.

838 

839Matches on tool name, same values as PreToolUse.

840 

841#### PermissionRequest input

435 842 

436The `reason` field in the hook input will be one of:843PermissionRequest 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.

437 844 

438* `clear` - Session cleared with /clear command845```json theme={null}

439* `logout` - User logged out846{

440* `prompt_input_exit` - User exited while prompt input was visible847 "session_id": "abc123",

441* `other` - Other exit reasons848 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

849 "cwd": "/Users/...",

850 "permission_mode": "default",

851 "hook_event_name": "PermissionRequest",

852 "tool_name": "Bash",

853 "tool_input": {

854 "command": "rm -rf node_modules",

855 "description": "Remove node_modules directory"

856 },

857 "permission_suggestions": [

858 { "type": "toolAlwaysAllow", "tool": "Bash" }

859 ]

860}

861```

862 

863#### PermissionRequest decision control

442 864 

443## Hook Input865`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:

444 866 

445Hooks receive JSON data via stdin containing session information and867| Field | Description |

446event-specific data:868| :------------------- | :------------------------------------------------------------------------------------------------------------- |

869| `behavior` | `"allow"` grants the permission, `"deny"` denies it |

870| `updatedInput` | For `"allow"` only: modifies the tool's input parameters before execution |

871| `updatedPermissions` | For `"allow"` only: applies permission rule updates, equivalent to the user selecting an "always allow" option |

872| `message` | For `"deny"` only: tells Claude why the permission was denied |

873| `interrupt` | For `"deny"` only: if `true`, stops Claude |

447 874 

448```typescript theme={null}875```json theme={null}

876{

877 "hookSpecificOutput": {

878 "hookEventName": "PermissionRequest",

879 "decision": {

880 "behavior": "allow",

881 "updatedInput": {

882 "command": "npm run lint"

883 }

884 }

885 }

886}

887```

888 

889### PostToolUse

890 

891Runs immediately after a tool completes successfully.

892 

893Matches on tool name, same values as PreToolUse.

894 

895#### PostToolUse input

896 

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

898 

899```json theme={null}

900{

901 "session_id": "abc123",

902 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

903 "cwd": "/Users/...",

904 "permission_mode": "default",

905 "hook_event_name": "PostToolUse",

906 "tool_name": "Write",

907 "tool_input": {

908 "file_path": "/path/to/file.txt",

909 "content": "file content"

910 },

911 "tool_response": {

912 "filePath": "/path/to/file.txt",

913 "success": true

914 },

915 "tool_use_id": "toolu_01ABC123..."

916}

917```

918 

919#### PostToolUse decision control

920 

921`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:

922 

923| Field | Description |

924| :--------------------- | :----------------------------------------------------------------------------------------- |

925| `decision` | `"block"` prompts Claude with the `reason`. Omit to allow the action to proceed |

926| `reason` | Explanation shown to Claude when `decision` is `"block"` |

927| `additionalContext` | Additional context for Claude to consider |

928| `updatedMCPToolOutput` | For [MCP tools](#match-mcp-tools) only: replaces the tool's output with the provided value |

929 

930```json theme={null}

449{931{

450 // Common fields932 "decision": "block",

451 session_id: string933 "reason": "Explanation for decision",

452 transcript_path: string // Path to conversation JSON934 "hookSpecificOutput": {

453 cwd: string // The current working directory when the hook is invoked935 "hookEventName": "PostToolUse",

454 permission_mode: string // Current permission mode: "default", "plan", "acceptEdits", or "bypassPermissions"936 "additionalContext": "Additional information for Claude"

455 937 }

456 // Event-specific fields938}

457 hook_event_name: string939```

458 ...940 

941### PostToolUseFailure

942 

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

944 

945Matches on tool name, same values as PreToolUse.

946 

947#### PostToolUseFailure input

948 

949PostToolUseFailure hooks receive the same `tool_name` and `tool_input` fields as PostToolUse, along with error information as top-level fields:

950 

951```json theme={null}

952{

953 "session_id": "abc123",

954 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

955 "cwd": "/Users/...",

956 "permission_mode": "default",

957 "hook_event_name": "PostToolUseFailure",

958 "tool_name": "Bash",

959 "tool_input": {

960 "command": "npm test",

961 "description": "Run test suite"

962 },

963 "tool_use_id": "toolu_01ABC123...",

964 "error": "Command exited with non-zero status code 1",

965 "is_interrupt": false

966}

967```

968 

969| Field | Description |

970| :------------- | :------------------------------------------------------------------------------ |

971| `error` | String describing what went wrong |

972| `is_interrupt` | Optional boolean indicating whether the failure was caused by user interruption |

973 

974#### PostToolUseFailure decision control

975 

976`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:

977 

978| Field | Description |

979| :------------------ | :------------------------------------------------------------ |

980| `additionalContext` | Additional context for Claude to consider alongside the error |

981 

982```json theme={null}

983{

984 "hookSpecificOutput": {

985 "hookEventName": "PostToolUseFailure",

986 "additionalContext": "Additional information about the failure for Claude"

987 }

988}

989```

990 

991### Notification

992 

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

994 

995Use 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:

996 

997```json theme={null}

998{

999 "hooks": {

1000 "Notification": [

1001 {

1002 "matcher": "permission_prompt",

1003 "hooks": [

1004 {

1005 "type": "command",

1006 "command": "/path/to/permission-alert.sh"

1007 }

1008 ]

1009 },

1010 {

1011 "matcher": "idle_prompt",

1012 "hooks": [

1013 {

1014 "type": "command",

1015 "command": "/path/to/idle-notification.sh"

1016 }

1017 ]

1018 }

1019 ]

1020 }

459}1021}

460```1022```

461 1023 

462### PreToolUse Input1024#### Notification input

463 1025 

464The exact schema for `tool_input` depends on the tool.1026In 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.

465 1027 

466```json theme={null}1028```json theme={null}

467{1029{


469 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1031 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

470 "cwd": "/Users/...",1032 "cwd": "/Users/...",

471 "permission_mode": "default",1033 "permission_mode": "default",

472 "hook_event_name": "PreToolUse",1034 "hook_event_name": "Notification",

473 "tool_name": "Write",1035 "message": "Claude needs your permission to use Bash",

474 "tool_input": {1036 "title": "Permission needed",

475 "file_path": "/path/to/file.txt",1037 "notification_type": "permission_prompt"

476 "content": "file content"

477 },

478 "tool_use_id": "toolu_01ABC123..."

479}1038}

480```1039```

481 1040 

482### PostToolUse Input1041Notification 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:

1042 

1043| Field | Description |

1044| :------------------ | :------------------------------- |

1045| `additionalContext` | String added to Claude's context |

1046 

1047### SubagentStart

483 1048 

484The exact schema for `tool_input` and `tool_response` depends on the tool.1049Runs when a Claude Code subagent is spawned via the Task tool. Supports matchers to filter by agent type name (built-in agents like `Bash`, `Explore`, `Plan`, or custom agent names from `.claude/agents/`).

1050 

1051#### SubagentStart input

1052 

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

485 1054 

486```json theme={null}1055```json theme={null}

487{1056{


489 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1058 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

490 "cwd": "/Users/...",1059 "cwd": "/Users/...",

491 "permission_mode": "default",1060 "permission_mode": "default",

492 "hook_event_name": "PostToolUse",1061 "hook_event_name": "SubagentStart",

493 "tool_name": "Write",1062 "agent_id": "agent-abc123",

494 "tool_input": {1063 "agent_type": "Explore"

495 "file_path": "/path/to/file.txt",

496 "content": "file content"

497 },

498 "tool_response": {

499 "filePath": "/path/to/file.txt",

500 "success": true

501 },

502 "tool_use_id": "toolu_01ABC123..."

503}1064}

504```1065```

505 1066 

506### Notification Input1067SubagentStart 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:

1068 

1069| Field | Description |

1070| :------------------ | :------------------------------------- |

1071| `additionalContext` | String added to the subagent's context |

507 1072 

508```json theme={null}1073```json theme={null}

509{1074{

510 "session_id": "abc123",1075 "hookSpecificOutput": {

511 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1076 "hookEventName": "SubagentStart",

512 "cwd": "/Users/...",1077 "additionalContext": "Follow security guidelines for this task"

513 "permission_mode": "default",1078 }

514 "hook_event_name": "Notification",

515 "message": "Claude needs your permission to use Bash",

516 "notification_type": "permission_prompt"

517}1079}

518```1080```

519 1081 

520### UserPromptSubmit Input1082### SubagentStop

1083 

1084Runs when a Claude Code subagent has finished responding. Matches on agent type, same values as SubagentStart.

1085 

1086#### SubagentStop input

1087 

1088In addition to the [common input fields](#common-input-fields), SubagentStop hooks receive `stop_hook_active`, `agent_id`, `agent_type`, and `agent_transcript_path`. 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.

521 1089 

522```json theme={null}1090```json theme={null}

523{1091{

524 "session_id": "abc123",1092 "session_id": "abc123",

525 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1093 "transcript_path": "~/.claude/projects/.../abc123.jsonl",

526 "cwd": "/Users/...",1094 "cwd": "/Users/...",

527 "permission_mode": "default",1095 "permission_mode": "default",

528 "hook_event_name": "UserPromptSubmit",1096 "hook_event_name": "SubagentStop",

529 "prompt": "Write a function to calculate the factorial of a number"1097 "stop_hook_active": false,

1098 "agent_id": "def456",

1099 "agent_type": "Explore",

1100 "agent_transcript_path": "~/.claude/projects/.../abc123/subagents/agent-def456.jsonl"

530}1101}

531```1102```

532 1103 

533### Stop and SubagentStop Input1104SubagentStop hooks use the same decision control format as [Stop hooks](#stop-decision-control).

1105 

1106### Stop

1107 

1108Runs when the main Claude Code agent has finished responding. Does not run if

1109the stoppage occurred due to a user interrupt.

1110 

1111#### Stop input

534 1112 

535`stop_hook_active` is true when Claude Code is already continuing as a result of1113In addition to the [common input fields](#common-input-fields), Stop hooks receive `stop_hook_active`. This 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.

536a stop hook. Check this value or process the transcript to prevent Claude Code

537from running indefinitely.

538 1114 

539```json theme={null}1115```json theme={null}

540{1116{

541 "session_id": "abc123",1117 "session_id": "abc123",

542 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1118 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

1119 "cwd": "/Users/...",

543 "permission_mode": "default",1120 "permission_mode": "default",

544 "hook_event_name": "Stop",1121 "hook_event_name": "Stop",

545 "stop_hook_active": true1122 "stop_hook_active": true

546}1123}

547```1124```

548 1125 

549### PreCompact Input1126#### Stop decision control

1127 

1128`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:

550 1129 

551For `manual`, `custom_instructions` comes from what the user passes into1130| Field | Description |

552`/compact`. For `auto`, `custom_instructions` is empty.1131| :--------- | :------------------------------------------------------------------------- |

1132| `decision` | `"block"` prevents Claude from stopping. Omit to allow Claude to stop |

1133| `reason` | Required when `decision` is `"block"`. Tells Claude why it should continue |

553 1134 

554```json theme={null}1135```json theme={null}

555{1136{

556 "session_id": "abc123",1137 "decision": "block",

557 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1138 "reason": "Must be provided when Claude is blocked from stopping"

558 "permission_mode": "default",

559 "hook_event_name": "PreCompact",

560 "trigger": "manual",

561 "custom_instructions": ""

562}1139}

563```1140```

564 1141 

565### SessionStart Input1142### TeammateIdle

566 1143 

567```json theme={null}1144Runs 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.

568{1145 

569 "session_id": "abc123",1146When a `TeammateIdle` hook exits with code 2, the teammate receives the stderr message as feedback and continues working instead of going idle. TeammateIdle hooks do not support matchers and fire on every occurrence.

570 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1147 

571 "permission_mode": "default",1148#### TeammateIdle input

572 "hook_event_name": "SessionStart",

573 "source": "startup"

574}

575```

576 1149 

577### SessionEnd Input1150In addition to the [common input fields](#common-input-fields), TeammateIdle hooks receive `teammate_name` and `team_name`.

578 1151 

579```json theme={null}1152```json theme={null}

580{1153{

581 "session_id": "abc123",1154 "session_id": "abc123",

582 "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",1155 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

583 "cwd": "/Users/...",1156 "cwd": "/Users/...",

584 "permission_mode": "default",1157 "permission_mode": "default",

585 "hook_event_name": "SessionEnd",1158 "hook_event_name": "TeammateIdle",

586 "reason": "exit"1159 "teammate_name": "researcher",

1160 "team_name": "my-project"

587}1161}

588```1162```

589 1163 

590## Hook Output1164| Field | Description |

591 1165| :-------------- | :-------------------------------------------- |

592There are two mutually-exclusive ways for hooks to return output back to Claude Code. The output1166| `teammate_name` | Name of the teammate that is about to go idle |

593communicates whether to block and any feedback that should be shown to Claude1167| `team_name` | Name of the team |

594and the user.

595 1168 

596### Simple: Exit Code1169#### TeammateIdle decision control

597 1170 

598Hooks communicate status through exit codes, stdout, and stderr:1171TeammateIdle hooks use exit codes only, not JSON decision control. This example checks that a build artifact exists before allowing a teammate to go idle:

599 1172 

600* **Exit code 0**: Success. `stdout` is shown to the user in verbose mode1173```bash theme={null}

601 (ctrl+o), except for `UserPromptSubmit` and `SessionStart`, where stdout is1174#!/bin/bash

602 added to the context. JSON output in `stdout` is parsed for structured control

603 (see [Advanced: JSON Output](#advanced-json-output)).

604* **Exit code 2**: Blocking error. Only `stderr` is used as the error message

605 and fed back to Claude. The format is `[command]: {stderr}`. JSON in `stdout`

606 is **not** processed for exit code 2. See per-hook-event behavior below.

607* **Other exit codes**: Non-blocking error. `stderr` is shown to the user in verbose mode (ctrl+o) with

608 format `Failed with non-blocking status code: {stderr}`. If `stderr` is empty,

609 it shows `No stderr output`. Execution continues.

610 

611<Warning>

612 Reminder: Claude Code does not see stdout if the exit code is 0, except for

613 the `UserPromptSubmit` hook where stdout is injected as context.

614</Warning>

615 1175 

616#### Exit Code 2 Behavior1176if [ ! -f "./dist/output.js" ]; then

1177 echo "Build artifact missing. Run the build before stopping." >&2

1178 exit 2

1179fi

617 1180 

618| Hook Event | Behavior |1181exit 0

619| ------------------ | ------------------------------------------------------------------ |1182```

620| `PreToolUse` | Blocks the tool call, shows stderr to Claude |

621| `PostToolUse` | Shows stderr to Claude (tool already ran) |

622| `Notification` | N/A, shows stderr to user only |

623| `UserPromptSubmit` | Blocks prompt processing, erases prompt, shows stderr to user only |

624| `Stop` | Blocks stoppage, shows stderr to Claude |

625| `SubagentStop` | Blocks stoppage, shows stderr to Claude subagent |

626| `PreCompact` | N/A, shows stderr to user only |

627| `SessionStart` | N/A, shows stderr to user only |

628| `SessionEnd` | N/A, shows stderr to user only |

629 1183 

630### Advanced: JSON Output1184### TaskCompleted

631 1185 

632Hooks can return structured JSON in `stdout` for more sophisticated control.1186Runs 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.

633 1187 

634<Warning>1188When a `TaskCompleted` hook exits with code 2, the task is not marked as completed and the stderr message is fed back to the model as feedback. TaskCompleted hooks do not support matchers and fire on every occurrence.

635 JSON output is only processed when the hook exits with code 0. If your hook

636 exits with code 2 (blocking error), `stderr` text is used directly—any JSON in `stdout`

637 is ignored. For other non-zero exit codes, only `stderr` is shown to the user in verbose mode (ctrl+o).

638</Warning>

639 1189 

640#### Common JSON Fields1190#### TaskCompleted input

641 1191 

642All hook types can include these optional fields:1192In 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`.

643 1193 

644```json theme={null}1194```json theme={null}

645{1195{

646 "continue": true, // Whether Claude should continue after hook execution (default: true)1196 "session_id": "abc123",

647 "stopReason": "string", // Message shown when continue is false1197 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

648 1198 "cwd": "/Users/...",

649 "suppressOutput": true, // Hide stdout from transcript mode (default: false)1199 "permission_mode": "default",

650 "systemMessage": "string" // Optional warning message shown to the user1200 "hook_event_name": "TaskCompleted",

1201 "task_id": "task-001",

1202 "task_subject": "Implement user authentication",

1203 "task_description": "Add login and signup endpoints",

1204 "teammate_name": "implementer",

1205 "team_name": "my-project"

651}1206}

652```1207```

653 1208 

654If `continue` is false, Claude stops processing after the hooks run.1209| Field | Description |

655 1210| :----------------- | :------------------------------------------------------ |

656* For `PreToolUse`, this is different from `"permissionDecision": "deny"`, which1211| `task_id` | Identifier of the task being completed |

657 only blocks a specific tool call and provides automatic feedback to Claude.1212| `task_subject` | Title of the task |

658* For `PostToolUse`, this is different from `"decision": "block"`, which1213| `task_description` | Detailed description of the task. May be absent |

659 provides automated feedback to Claude.1214| `teammate_name` | Name of the teammate completing the task. May be absent |

660* For `UserPromptSubmit`, this prevents the prompt from being processed.1215| `team_name` | Name of the team. May be absent |

661* For `Stop` and `SubagentStop`, this takes precedence over any

662 `"decision": "block"` output.

663* In all cases, `"continue" = false` takes precedence over any

664 `"decision": "block"` output.

665 1216 

666`stopReason` accompanies `continue` with a reason shown to the user, not shown1217#### TaskCompleted decision control

667to Claude.

668 1218 

669#### `PreToolUse` Decision Control1219TaskCompleted hooks use exit codes only, not JSON decision control. This example runs tests and blocks task completion if they fail:

670 1220 

671`PreToolUse` hooks can control whether a tool call proceeds.1221```bash theme={null}

1222#!/bin/bash

1223INPUT=$(cat)

1224TASK_SUBJECT=$(echo "$INPUT" | jq -r '.task_subject')

672 1225 

673* `"allow"` bypasses the permission system. `permissionDecisionReason` is shown1226# Run the test suite

674 to the user but not to Claude.1227if ! npm test 2>&1; then

675* `"deny"` prevents the tool call from executing. `permissionDecisionReason` is1228 echo "Tests not passing. Fix failing tests before completing: $TASK_SUBJECT" >&2

676 shown to Claude.1229 exit 2

677* `"ask"` asks the user to confirm the tool call in the UI.1230fi

678 `permissionDecisionReason` is shown to the user but not to Claude.

679 1231 

680Additionally, hooks can modify tool inputs before execution using `updatedInput`:1232exit 0

1233```

681 1234 

682* `updatedInput` allows you to modify the tool's input parameters before the tool executes.1235### PreCompact

683* This is most useful with `"permissionDecision": "allow"` to modify and approve tool calls.

684 1236 

685```json theme={null}1237Runs before Claude Code is about to run a compact operation.

686{

687 "hookSpecificOutput": {

688 "hookEventName": "PreToolUse",

689 "permissionDecision": "allow"

690 "permissionDecisionReason": "My reason here",

691 "updatedInput": {

692 "field_to_modify": "new value"

693 }

694 }

695}

696```

697 1238 

698<Note>1239The matcher value indicates whether compaction was triggered manually or automatically:

699 The `decision` and `reason` fields are deprecated for PreToolUse hooks.

700 Use `hookSpecificOutput.permissionDecision` and

701 `hookSpecificOutput.permissionDecisionReason` instead. The deprecated fields

702 `"approve"` and `"block"` map to `"allow"` and `"deny"` respectively.

703</Note>

704 1240 

705#### `PermissionRequest` Decision Control1241| Matcher | When it fires |

1242| :------- | :------------------------------------------- |

1243| `manual` | `/compact` |

1244| `auto` | Auto-compact when the context window is full |

706 1245 

707`PermissionRequest` hooks can allow or deny permission requests shown to the user.1246#### PreCompact input

708 1247 

709* For `"behavior": "allow"` you can also optionally pass in an `"updatedInput"` that modifies the tool's input parameters before the tool executes.1248In 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.

710* For `"behavior": "deny"` you can also optionally pass in a `"message"` string that tells the model why the permission was denied, and a boolean `"interrupt"` which will stop Claude.

711 1249 

712```json theme={null}1250```json theme={null}

713{1251{

714 "hookSpecificOutput": {1252 "session_id": "abc123",

715 "hookEventName": "PermissionRequest",1253 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

716 "decision": {1254 "cwd": "/Users/...",

717 "behavior": "allow",1255 "permission_mode": "default",

718 "updatedInput": {1256 "hook_event_name": "PreCompact",

719 "command": "npm run lint"1257 "trigger": "manual",

720 }1258 "custom_instructions": ""

721 }

722 }

723}1259}

724```1260```

725 1261 

726#### `PostToolUse` Decision Control1262### SessionEnd

1263 

1264Runs when a Claude Code session ends. Useful for cleanup tasks, logging session

1265statistics, or saving session state. Supports matchers to filter by exit reason.

1266 

1267The `reason` field in the hook input indicates why the session ended:

727 1268 

728`PostToolUse` hooks can provide feedback to Claude after tool execution.1269| Reason | Description |

1270| :---------------------------- | :----------------------------------------- |

1271| `clear` | Session cleared with `/clear` command |

1272| `logout` | User logged out |

1273| `prompt_input_exit` | User exited while prompt input was visible |

1274| `bypass_permissions_disabled` | Bypass permissions mode was disabled |

1275| `other` | Other exit reasons |

729 1276 

730* `"block"` automatically prompts Claude with `reason`.1277#### SessionEnd input

731* `undefined` does nothing. `reason` is ignored.1278 

732* `"hookSpecificOutput.additionalContext"` adds context for Claude to consider.1279In 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.

733 1280 

734```json theme={null}1281```json theme={null}

735{1282{

736 "decision": "block" | undefined,1283 "session_id": "abc123",

737 "reason": "Explanation for decision",1284 "transcript_path": "/Users/.../.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl",

738 "hookSpecificOutput": {1285 "cwd": "/Users/...",

739 "hookEventName": "PostToolUse",1286 "permission_mode": "default",

740 "additionalContext": "Additional information for Claude"1287 "hook_event_name": "SessionEnd",

741 }1288 "reason": "other"

742}1289}

743```1290```

744 1291 

745#### `UserPromptSubmit` Decision Control1292SessionEnd hooks have no decision control. They cannot block session termination but can perform cleanup tasks.

1293 

1294## Prompt-based hooks

746 1295 

747`UserPromptSubmit` hooks can control whether a user prompt is processed and add context.1296In addition to Bash command hooks (`type: "command"`), Claude Code supports prompt-based hooks (`type: "prompt"`) that use an LLM to evaluate whether to allow or block an action. Prompt-based hooks work with the following events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `UserPromptSubmit`, `Stop`, `SubagentStop`, and `TaskCompleted`. `TeammateIdle` does not support prompt-based or agent-based hooks.

748 1297 

749**Adding context (exit code 0):**1298### How prompt-based hooks work

750There are two ways to add context to the conversation:

751 1299 

7521. **Plain text stdout** (simpler): Any non-JSON text written to stdout is added1300Instead of executing a Bash command, prompt-based hooks:

753 as context. This is the easiest way to inject information.

754 1301 

7552. **JSON with `additionalContext`** (structured): Use the JSON format below for13021. Send the hook input and your prompt to a Claude model, Haiku by default

756 more control. The `additionalContext` field is added as context.13032. The LLM responds with structured JSON containing a decision

13043. Claude Code processes the decision automatically

757 1305 

758Both methods work with exit code 0. Plain stdout is shown as hook output in1306### Prompt hook configuration

759the transcript; `additionalContext` is added more discretely.

760 1307 

761**Blocking prompts:**1308Set `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.

762 1309 

763* `"decision": "block"` prevents the prompt from being processed. The submitted1310This `Stop` hook asks the LLM to evaluate whether all tasks are complete before allowing Claude to finish:

764 prompt is erased from context. `"reason"` is shown to the user but not added

765 to context.

766* `"decision": undefined` (or omitted) allows the prompt to proceed normally.

767 1311 

768```json theme={null}1312```json theme={null}

769{1313{

770 "decision": "block" | undefined,1314 "hooks": {

771 "reason": "Explanation for decision",1315 "Stop": [

772 "hookSpecificOutput": {1316 {

773 "hookEventName": "UserPromptSubmit",1317 "hooks": [

774 "additionalContext": "My additional context here"1318 {

1319 "type": "prompt",

1320 "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete."

1321 }

1322 ]

1323 }

1324 ]

775 }1325 }

776}1326}

777```1327```

778 1328 

779<Note>1329| Field | Required | Description |

780 The JSON format is not required for simple use cases. To add context, you can1330| :-------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

781 just print plain text to stdout with exit code 0. Use JSON when you need to1331| `type` | yes | Must be `"prompt"` |

782 block prompts or want more structured control.1332| `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 |

783</Note>1333| `model` | no | Model to use for evaluation. Defaults to a fast model |

784 1334| `timeout` | no | Timeout in seconds. Default: 30 |

785#### `Stop`/`SubagentStop` Decision Control

786 1335 

787`Stop` and `SubagentStop` hooks can control whether Claude must continue.1336### Response schema

788 1337 

789* `"block"` prevents Claude from stopping. You must populate `reason` for Claude1338The LLM must respond with JSON containing:

790 to know how to proceed.

791* `undefined` allows Claude to stop. `reason` is ignored.

792 1339 

793```json theme={null}1340```json theme={null}

794{1341{

795 "decision": "block" | undefined,1342 "ok": true | false,

796 "reason": "Must be provided when Claude is blocked from stopping"1343 "reason": "Explanation for the decision"

797}1344}

798```1345```

799 1346 

800#### `SessionStart` Decision Control1347| Field | Description |

1348| :------- | :--------------------------------------------------------- |

1349| `ok` | `true` allows the action, `false` prevents it |

1350| `reason` | Required when `ok` is `false`. Explanation shown to Claude |

801 1351 

802`SessionStart` hooks allow you to load in context at the start of a session.1352### Example: Multi-criteria Stop hook

803 1353 

804* `"hookSpecificOutput.additionalContext"` adds the string to the context.1354This `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:

805* Multiple hooks' `additionalContext` values are concatenated.

806 1355 

807```json theme={null}1356```json theme={null}

808{1357{

809 "hookSpecificOutput": {1358 "hooks": {

810 "hookEventName": "SessionStart",1359 "Stop": [

811 "additionalContext": "My additional context here"1360 {

1361 "hooks": [

1362 {

1363 "type": "prompt",

1364 "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.",

1365 "timeout": 30

1366 }

1367 ]

1368 }

1369 ]

812 }1370 }

813}1371}

814```1372```

815 1373 

816#### `SessionEnd` Decision Control1374## Agent-based hooks

817 

818`SessionEnd` hooks run when a session ends. They cannot block session termination

819but can perform cleanup tasks.

820 

821#### Exit Code Example: Bash Command Validation

822 

823```python theme={null}

824#!/usr/bin/env python3

825import json

826import re

827import sys

828 

829# Define validation rules as a list of (regex pattern, message) tuples

830VALIDATION_RULES = [

831 (

832 r"\bgrep\b(?!.*\|)",

833 "Use 'rg' (ripgrep) instead of 'grep' for better performance and features",

834 ),

835 (

836 r"\bfind\s+\S+\s+-name\b",

837 "Use 'rg --files | rg pattern' or 'rg --files -g pattern' instead of 'find -name' for better performance",

838 ),

839]

840 

841 

842def validate_command(command: str) -> list[str]:

843 issues = []

844 for pattern, message in VALIDATION_RULES:

845 if re.search(pattern, command):

846 issues.append(message)

847 return issues

848 

849 

850try:

851 input_data = json.load(sys.stdin)

852except json.JSONDecodeError as e:

853 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

854 sys.exit(1)

855 

856tool_name = input_data.get("tool_name", "")

857tool_input = input_data.get("tool_input", {})

858command = tool_input.get("command", "")

859 

860if tool_name != "Bash" or not command:

861 sys.exit(1)

862 

863# Validate the command

864issues = validate_command(command)

865 

866if issues:

867 for message in issues:

868 print(f"• {message}", file=sys.stderr)

869 # Exit code 2 blocks tool call and shows stderr to Claude

870 sys.exit(2)

871```

872 

873#### JSON Output Example: UserPromptSubmit to Add Context and Validation

874 1375 

875<Note>1376Agent-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.

876 For `UserPromptSubmit` hooks, you can inject context using either method:

877 1377 

878 * **Plain text stdout** with exit code 0: Simplest approach—just print text1378### How agent hooks work

879 * **JSON output** with exit code 0: Use `"decision": "block"` to reject prompts,

880 or `additionalContext` for structured context injection

881 1379 

882 Remember: Exit code 2 only uses `stderr` for the error message. To block using1380When an agent hook fires:

883 JSON (with a custom reason), use `"decision": "block"` with exit code 0.

884</Note>

885 1381 

886```python theme={null}13821. Claude Code spawns a subagent with your prompt and the hook's JSON input

887#!/usr/bin/env python313832. The subagent can use tools like Read, Grep, and Glob to investigate

888import json13843. After up to 50 turns, the subagent returns a structured `{ "ok": true/false }` decision

889import sys13854. Claude Code processes the decision the same way as a prompt hook

890import re

891import datetime

892 

893# Load input from stdin

894try:

895 input_data = json.load(sys.stdin)

896except json.JSONDecodeError as e:

897 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

898 sys.exit(1)

899 

900prompt = input_data.get("prompt", "")

901 

902# Check for sensitive patterns

903sensitive_patterns = [

904 (r"(?i)\b(password|secret|key|token)\s*[:=]", "Prompt contains potential secrets"),

905]

906 

907for pattern, message in sensitive_patterns:

908 if re.search(pattern, prompt):

909 # Use JSON output to block with a specific reason

910 output = {

911 "decision": "block",

912 "reason": f"Security policy violation: {message}. Please rephrase your request without sensitive information."

913 }

914 print(json.dumps(output))

915 sys.exit(0)

916 1386 

917# Add current time to context1387Agent hooks are useful when verification requires inspecting actual files or test output, not just evaluating the hook input data alone.

918context = f"Current time: {datetime.datetime.now()}"

919print(context)

920 1388 

921"""1389### Agent hook configuration

922The following is also equivalent:

923print(json.dumps({

924 "hookSpecificOutput": {

925 "hookEventName": "UserPromptSubmit",

926 "additionalContext": context,

927 },

928}))

929"""

930 1390 

931# Allow the prompt to proceed with the additional context1391Set `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:

932sys.exit(0)

933```

934 1392 

935#### JSON Output Example: PreToolUse with Approval1393| Field | Required | Description |

936 1394| :-------- | :------- | :------------------------------------------------------------------------------------------ |

937```python theme={null}1395| `type` | yes | Must be `"agent"` |

938#!/usr/bin/env python31396| `prompt` | yes | Prompt describing what to verify. Use `$ARGUMENTS` as a placeholder for the hook input JSON |

939import json1397| `model` | no | Model to use. Defaults to a fast model |

940import sys1398| `timeout` | no | Timeout in seconds. Default: 60 |

941 

942# Load input from stdin

943try:

944 input_data = json.load(sys.stdin)

945except json.JSONDecodeError as e:

946 print(f"Error: Invalid JSON input: {e}", file=sys.stderr)

947 sys.exit(1)

948 

949tool_name = input_data.get("tool_name", "")

950tool_input = input_data.get("tool_input", {})

951 

952# Example: Auto-approve file reads for documentation files

953if tool_name == "Read":

954 file_path = tool_input.get("file_path", "")

955 if file_path.endswith((".md", ".mdx", ".txt", ".json")):

956 # Use JSON output to auto-approve the tool call

957 output = {

958 "decision": "approve",

959 "reason": "Documentation file auto-approved",

960 "suppressOutput": True # Don't show in verbose mode

961 }

962 print(json.dumps(output))

963 sys.exit(0)

964 1399 

965# For other cases, let the normal permission flow proceed1400The response schema is the same as prompt hooks: `{ "ok": true }` to allow or `{ "ok": false, "reason": "..." }` to block.

966sys.exit(0)

967```

968 1401 

969## Working with MCP Tools1402This `Stop` hook verifies that all unit tests pass before allowing Claude to finish:

970 1403 

971Claude Code hooks work seamlessly with1404```json theme={null}

972[Model Context Protocol (MCP) tools](/en/mcp). When MCP servers1405{

973provide tools, they appear with a special naming pattern that you can match in1406 "hooks": {

974your hooks.1407 "Stop": [

1408 {

1409 "hooks": [

1410 {

1411 "type": "agent",

1412 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

1413 "timeout": 120

1414 }

1415 ]

1416 }

1417 ]

1418 }

1419}

1420```

975 1421 

976### MCP Tool Naming1422## Run hooks in the background

977 1423 

978MCP tools follow the pattern `mcp__<server>__<tool>`, for example:1424By 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.

979 1425 

980* `mcp__memory__create_entities` - Memory server's create entities tool1426### Configure an async hook

981* `mcp__filesystem__read_file` - Filesystem server's read file tool

982* `mcp__github__search_repositories` - GitHub server's search tool

983 1427 

984### Configuring Hooks for MCP Tools1428Add `"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.

985 1429 

986You can target specific MCP tools or entire MCP servers:1430This 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:

987 1431 

988```json theme={null}1432```json theme={null}

989{1433{

990 "hooks": {1434 "hooks": {

991 "PreToolUse": [1435 "PostToolUse": [

992 {

993 "matcher": "mcp__memory__.*",

994 "hooks": [

995 {

996 "type": "command",

997 "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log"

998 }

999 ]

1000 },

1001 {1436 {

1002 "matcher": "mcp__.*__write.*",1437 "matcher": "Write",

1003 "hooks": [1438 "hooks": [

1004 {1439 {

1005 "type": "command",1440 "type": "command",

1006 "command": "/home/user/scripts/validate-mcp-write.py"1441 "command": "/path/to/run-tests.sh",

1442 "async": true,

1443 "timeout": 120

1007 }1444 }

1008 ]1445 ]

1009 }1446 }


1012}1449}

1013```1450```

1014 1451 

1015## Examples1452The `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.

1016 

1017<Tip>

1018 For practical examples including code formatting, notifications, and file protection, see [More Examples](/en/hooks-guide#more-examples) in the get started guide.

1019</Tip>

1020 

1021## Security Considerations

1022 1453 

1023### Disclaimer1454### How async hooks execute

1024 1455 

1025**USE AT YOUR OWN RISK**: Claude Code hooks execute arbitrary shell commands on1456When 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.

1026your system automatically. By using hooks, you acknowledge that:

1027 1457 

1028* You are solely responsible for the commands you configure1458After 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.

1029* Hooks can modify, delete, or access any files your user account can access

1030* Malicious or poorly written hooks can cause data loss or system damage

1031* Anthropic provides no warranty and assumes no liability for any damages

1032 resulting from hook usage

1033* You should thoroughly test hooks in a safe environment before production use

1034 1459 

1035Always review and understand any hook commands before adding them to your1460### Example: run tests after file changes

1036configuration.

1037 1461 

1038### Security Best Practices1462This 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`:

1039 1463 

1040Here are some key practices for writing more secure hooks:1464```bash theme={null}

1465#!/bin/bash

1466# run-tests-async.sh

1041 1467 

10421. **Validate and sanitize inputs** - Never trust input data blindly1468# Read hook input from stdin

10432. **Always quote shell variables** - Use `"$VAR"` not `$VAR`1469INPUT=$(cat)

10443. **Block path traversal** - Check for `..` in file paths1470FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

10454. **Use absolute paths** - Specify full paths for scripts (use

1046 "\$CLAUDE\_PROJECT\_DIR" for the project path)

10475. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc.

1048 1471 

1049### Configuration Safety1472# Only run tests for source files

1473if [[ "$FILE_PATH" != *.ts && "$FILE_PATH" != *.js ]]; then

1474 exit 0

1475fi

1050 1476 

1051Direct edits to hooks in settings files don't take effect immediately. Claude1477# Run tests and report results via systemMessage

1052Code:1478RESULT=$(npm test 2>&1)

1479EXIT_CODE=$?

1053 1480 

10541. Captures a snapshot of hooks at startup1481if [ $EXIT_CODE -eq 0 ]; then

10552. Uses this snapshot throughout the session1482 echo "{\"systemMessage\": \"Tests passed after editing $FILE_PATH\"}"

10563. Warns if hooks are modified externally1483else

10574. Requires review in `/hooks` menu for changes to apply1484 echo "{\"systemMessage\": \"Tests failed after editing $FILE_PATH: $RESULT\"}"

1485fi

1486```

1058 1487 

1059This prevents malicious hook modifications from affecting your current session.1488Then add this configuration to `.claude/settings.json` in your project root. The `async: true` flag lets Claude keep working while tests run:

1060 1489 

1061## Hook Execution Details1490```json theme={null}

1491{

1492 "hooks": {

1493 "PostToolUse": [

1494 {

1495 "matcher": "Write|Edit",

1496 "hooks": [

1497 {

1498 "type": "command",

1499 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/run-tests-async.sh",

1500 "async": true,

1501 "timeout": 300

1502 }

1503 ]

1504 }

1505 ]

1506 }

1507}

1508```

1062 1509 

1063* **Timeout**: 60-second execution limit by default, configurable per command.1510### Limitations

1064 * A timeout for an individual command does not affect the other commands.

1065* **Parallelization**: All matching hooks run in parallel

1066* **Deduplication**: Multiple identical hook commands are deduplicated automatically

1067* **Environment**: Runs in current directory with Claude Code's environment

1068 * The `CLAUDE_PROJECT_DIR` environment variable is available and contains the

1069 absolute path to the project root directory (where Claude Code was started)

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

1071* **Input**: JSON via stdin

1072* **Output**:

1073 * PreToolUse/PostToolUse/Stop/SubagentStop: Progress shown in verbose mode (ctrl+o)

1074 * Notification/SessionEnd: Logged to debug only (`--debug`)

1075 * UserPromptSubmit/SessionStart: stdout added as context for Claude

1076 1511 

1077## Debugging1512Async hooks have several constraints compared to synchronous hooks:

1078 1513 

1079### Basic Troubleshooting1514* Only `type: "command"` hooks support `async`. Prompt-based hooks cannot run asynchronously.

1515* Async hooks cannot block tool calls or return decisions. By the time the hook completes, the triggering action has already proceeded.

1516* Hook output is delivered on the next conversation turn. If the session is idle, the response waits until the next user interaction.

1517* Each execution creates a separate background process. There is no deduplication across multiple firings of the same async hook.

1080 1518 

1081If your hooks aren't working:1519## Security considerations

1082 1520 

10831. **Check configuration** - Run `/hooks` to see if your hook is registered1521### Disclaimer

10842. **Verify syntax** - Ensure your JSON settings are valid

10853. **Test commands** - Run hook commands manually first

10864. **Check permissions** - Make sure scripts are executable

10875. **Review logs** - Use `claude --debug` to see hook execution details

1088 1522 

1089Common issues:1523Hooks run with your system user's full permissions.

1090 1524 

1091* **Quotes not escaped** - Use `\"` inside JSON strings1525<Warning>

1092* **Wrong matcher** - Check tool names match exactly (case-sensitive)1526 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.

1093* **Command not found** - Use full paths for scripts1527</Warning>

1094 1528 

1095### Advanced Debugging1529### Security best practices

1096 1530 

1097For complex hook issues:1531Keep these practices in mind when writing hooks:

1098 1532 

10991. **Inspect hook execution** - Use `claude --debug` to see detailed hook1533* **Validate and sanitize inputs**: never trust input data blindly

1100 execution1534* **Always quote shell variables**: use `"$VAR"` not `$VAR`

11012. **Validate JSON schemas** - Test hook input/output with external tools1535* **Block path traversal**: check for `..` in file paths

11023. **Check environment variables** - Verify Claude Code's environment is correct1536* **Use absolute paths**: specify full paths for scripts, using `"$CLAUDE_PROJECT_DIR"` for the project root

11034. **Test edge cases** - Try hooks with unusual file paths or inputs1537* **Skip sensitive files**: avoid `.env`, `.git/`, keys, etc.

11045. **Monitor system resources** - Check for resource exhaustion during hook

1105 execution

11066. **Use structured logging** - Implement logging in your hook scripts

1107 1538 

1108### Debug Output Example1539## Debug hooks

1109 1540 

1110Use `claude --debug` to see hook execution details:1541Run `claude --debug` to see hook execution details, including which hooks matched, their exit codes, and output. Toggle verbose mode with `Ctrl+O` to see hook progress in the transcript.

1111 1542 

1112```1543```

1113[DEBUG] Executing hooks for PostToolUse:Write1544[DEBUG] Executing hooks for PostToolUse:Write


1115[DEBUG] Found 1 hook matchers in settings1546[DEBUG] Found 1 hook matchers in settings

1116[DEBUG] Matched 1 hooks for query "Write"1547[DEBUG] Matched 1 hooks for query "Write"

1117[DEBUG] Found 1 hook commands to execute1548[DEBUG] Found 1 hook commands to execute

1118[DEBUG] Executing hook command: <Your command> with timeout 60000ms1549[DEBUG] Executing hook command: <Your command> with timeout 600000ms

1119[DEBUG] Hook command completed with status 0: <Your stdout>1550[DEBUG] Hook command completed with status 0: <Your stdout>

1120```1551```

1121 1552 

1122Progress messages appear in verbose mode (ctrl+o) showing:1553For 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.

1123 

1124* Which hook is running

1125* Command being executed

1126* Success/failure status

1127* Output or error messages

hooks-guide.md +504 −203

Details

1# Get started with Claude Code hooks1> ## Documentation Index

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

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

2 4 

3> Learn how to customize and extend Claude Code's behavior by registering shell commands5# Automate workflows with hooks

4 6 

5Claude Code hooks are user-defined shell commands that execute at various points7> Run shell commands automatically when Claude Code edits files, finishes tasks, or needs input. Format code, send notifications, validate commands, and enforce project rules.

6in Claude Code's lifecycle. Hooks provide deterministic control over Claude8 

7Code's behavior, ensuring certain actions always happen rather than relying on9Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide deterministic control over Claude Code's behavior, ensuring certain actions always happen rather than relying on the LLM to choose to run them. Use hooks to enforce project rules, automate repetitive tasks, and integrate Claude Code with your existing tools.

8the LLM to choose to run them.10 

11For decisions that require judgment rather than deterministic rules, you can also use [prompt-based hooks](#prompt-based-hooks) or [agent-based hooks](#agent-based-hooks) that use a Claude model to evaluate conditions.

12 

13For other ways to extend Claude Code, see [skills](/en/skills) for giving Claude additional instructions and executable commands, [subagents](/en/sub-agents) for running tasks in isolated contexts, and [plugins](/en/plugins) for packaging extensions to share across projects.

9 14 

10<Tip>15<Tip>

11 For reference documentation on hooks, see [Hooks reference](/en/hooks).16 This guide covers common use cases and how to get started. For full event schemas, JSON input/output formats, and advanced features like async hooks and MCP tool hooks, see the [Hooks reference](/en/hooks).

12</Tip>17</Tip>

13 18 

14Example use cases for hooks include:19## Set up your first hook

15 20 

16* **Notifications**: Customize how you get notified when Claude Code is awaiting21The fastest way to create a hook is through the `/hooks` interactive menu in Claude Code. This walkthrough creates a desktop notification hook, so you get alerted whenever Claude is waiting for your input instead of watching the terminal.

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="Open the hooks menu">

25 Type `/hooks` in the Claude Code CLI. You'll see a list of all available hook events, plus an option to disable all hooks. Each event corresponds to a point in Claude's lifecycle where you can run custom code. Select `Notification` to create a hook that fires when Claude needs your attention.

26 </Step>

29 27 

30<Warning>28 <Step title="Configure the matcher">

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.29 The menu shows a list of matchers, which filter when the hook fires. Set the matcher to `*` to fire on all notification types. You can narrow it later by changing the matcher to a specific value like `permission_prompt` or `idle_prompt`.

32 For example, malicious hooks code can exfiltrate your data. Always review your hooks implementation before registering them.30 </Step>

33 31 

34 For full security best practices, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.32 <Step title="Add your command">

35</Warning>33 Select `+ Add new hook…`. The menu prompts you for a shell command to run when the event fires. Hooks run any shell command you provide, so you can use your platform's built-in notification tool. Copy the command for your OS:

36 34 

37## Hook Events Overview35 <Tabs>

36 <Tab title="macOS">

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

38 38 

39Claude Code provides several hook events that run at different points in the39 ```

40workflow:40 osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'

41 ```

42 </Tab>

41 43 

42* **PreToolUse**: Runs before tool calls (can block them)44 <Tab title="Linux">

43* **PostToolUse**: Runs after tool calls complete45 Uses `notify-send`, which is pre-installed on most Linux desktops with a notification daemon:

44* **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it

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 46 

52Each event receives different data and can control Claude's behavior in47 ```

53different ways.48 notify-send 'Claude Code' 'Claude Code needs your attention'

49 ```

50 </Tab>

54 51 

55## Quickstart52 <Tab title="Windows (PowerShell)">

53 Uses PowerShell to show a native message box through .NET's Windows Forms:

56 54 

57In this quickstart, you'll add a hook that logs the shell commands that Claude55 ```

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

57 ```

58 </Tab>

59 </Tabs>

60 </Step>

59 61 

60### Prerequisites62 <Step title="Choose a storage location">

63 The menu asks where to save the hook configuration. Select `User settings` to store it in `~/.claude/settings.json`, which applies the hook to all your projects. You could also choose `Project settings` to scope it to the current project. See [Configure hook location](#configure-hook-location) for all available scopes.

64 </Step>

61 65 

62Install `jq` for JSON processing in the command line.66 <Step title="Test the hook">

67 Press `Esc` to return to the CLI. Ask Claude to do something that requires permission, then switch away from the terminal. You should receive a desktop notification.

68 </Step>

69</Steps>

63 70 

64### Step 1: Open hooks configuration71## What you can automate

65 72 

66Run the `/hooks` [slash command](/en/slash-commands) and select73Hooks 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).

67the `PreToolUse` hook event.

68 74 

69`PreToolUse` hooks run before tool calls and can block them while providing75Each example includes a ready-to-use configuration block that you add to a [settings file](#configure-hook-location). The most common patterns:

70Claude feedback on what to do differently.

71 76 

72### Step 2: Add a matcher77* [Get notified when Claude needs input](#get-notified-when-claude-needs-input)

78* [Auto-format code after edits](#auto-format-code-after-edits)

79* [Block edits to protected files](#block-edits-to-protected-files)

80* [Re-inject context after compaction](#re-inject-context-after-compaction)

73 81 

74Select `+ Add new matcher…` to run your hook only on Bash tool calls.82### Get notified when Claude needs input

75 83 

76Type `Bash` for the matcher.84Get a desktop notification whenever Claude finishes working and needs your input, so you can switch to other tasks without checking the terminal.

77 85 

78<Note>You can use `*` to match all tools.</Note>86This hook uses the `Notification` event, which fires when Claude is waiting for input or permission. Each tab below uses the platform's native notification command. Add this to `~/.claude/settings.json`, or use the [interactive walkthrough](#set-up-your-first-hook) above to configure it with `/hooks`:

79 87 

80### Step 3: Add the hook88<Tabs>

89 <Tab title="macOS">

90 ```json theme={null}

91 {

92 "hooks": {

93 "Notification": [

94 {

95 "matcher": "",

96 "hooks": [

97 {

98 "type": "command",

99 "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"

100 }

101 ]

102 }

103 ]

104 }

105 }

106 ```

107 </Tab>

81 108 

82Select `+ Add new hook…` and enter this command:109 <Tab title="Linux">

110 ```json theme={null}

111 {

112 "hooks": {

113 "Notification": [

114 {

115 "matcher": "",

116 "hooks": [

117 {

118 "type": "command",

119 "command": "notify-send 'Claude Code' 'Claude Code needs your attention'"

120 }

121 ]

122 }

123 ]

124 }

125 }

126 ```

127 </Tab>

83 128 

84```bash theme={null}129 <Tab title="Windows (PowerShell)">

85jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt130 ```json theme={null}

131 {

132 "hooks": {

133 "Notification": [

134 {

135 "matcher": "",

136 "hooks": [

137 {

138 "type": "command",

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

140 }

141 ]

142 }

143 ]

144 }

145 }

146 ```

147 </Tab>

148</Tabs>

149 

150### Auto-format code after edits

151 

152Automatically run [Prettier](https://prettier.io/) on every file Claude edits, so formatting stays consistent without manual intervention.

153 

154This 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:

155 

156```json theme={null}

157{

158 "hooks": {

159 "PostToolUse": [

160 {

161 "matcher": "Edit|Write",

162 "hooks": [

163 {

164 "type": "command",

165 "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"

166 }

167 ]

168 }

169 ]

170 }

171}

86```172```

87 173 

88### Step 4: Save your configuration174<Note>

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

176</Note>

177 

178### Block edits to protected files

179 

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

89 181 

90For storage location, select `User settings` since you're logging to your home182This 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.

91directory. This hook will then apply to all projects, not just your current

92project.

93 183 

94Then press Esc until you return to the REPL. Your hook is now registered!184<Steps>

185 <Step title="Create the hook script">

186 Save this to `.claude/hooks/protect-files.sh`:

95 187 

96### Step 5: Verify your hook188 ```bash theme={null}

189 #!/bin/bash

190 # protect-files.sh

97 191 

98Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:192 INPUT=$(cat)

193 FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

194 

195 PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

196 

197 for pattern in "${PROTECTED_PATTERNS[@]}"; do

198 if [[ "$FILE_PATH" == *"$pattern"* ]]; then

199 echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2

200 exit 2

201 fi

202 done

203 

204 exit 0

205 ```

206 </Step>

207 

208 <Step title="Make the script executable (macOS/Linux)">

209 Hook scripts must be executable for Claude Code to run them:

210 

211 ```bash theme={null}

212 chmod +x .claude/hooks/protect-files.sh

213 ```

214 </Step>

215 

216 <Step title="Register the hook">

217 Add a `PreToolUse` hook to `.claude/settings.json` that runs the script before any `Edit` or `Write` tool call:

218 

219 ```json theme={null}

220 {

221 "hooks": {

222 "PreToolUse": [

223 {

224 "matcher": "Edit|Write",

225 "hooks": [

226 {

227 "type": "command",

228 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"

229 }

230 ]

231 }

232 ]

233 }

234 }

235 ```

236 </Step>

237</Steps>

238 

239### Re-inject context after compaction

240 

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

242 

243Any 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 244 

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

101{246{

102 "hooks": {247 "hooks": {

103 "PreToolUse": [248 "SessionStart": [

104 {249 {

105 "matcher": "Bash",250 "matcher": "compact",

106 "hooks": [251 "hooks": [

107 {252 {

108 "type": "command",253 "type": "command",

109 "command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"254 "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"

110 }255 }

111 ]256 ]

112 }257 }


115}260}

116```261```

117 262 

118### Step 6: Test your hook263You 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 264 

120Ask Claude to run a simple command like `ls` and check your log file:265## How hooks work

121 266 

122```bash theme={null}267Hook 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:

123cat ~/.claude/bash-command-log.txt

124```

125 268 

126You should see entries like:269| Event | When it fires |

270| :------------------- | :----------------------------------------------------------------- |

271| `SessionStart` | When a session begins or resumes |

272| `UserPromptSubmit` | When you submit a prompt, before Claude processes it |

273| `PreToolUse` | Before a tool call executes. Can block it |

274| `PermissionRequest` | When a permission dialog appears |

275| `PostToolUse` | After a tool call succeeds |

276| `PostToolUseFailure` | After a tool call fails |

277| `Notification` | When Claude Code sends a notification |

278| `SubagentStart` | When a subagent is spawned |

279| `SubagentStop` | When a subagent finishes |

280| `Stop` | When Claude finishes responding |

281| `TeammateIdle` | When an [agent team](/en/agent-teams) teammate is about to go idle |

282| `TaskCompleted` | When a task is being marked as completed |

283| `PreCompact` | Before context compaction |

284| `SessionEnd` | When a session terminates |

127 285 

286Each hook has a `type` that determines how it runs. Most hooks use `"type": "command"`, which runs a shell command. Two other options use a Claude model to make decisions: `"type": "prompt"` for single-turn evaluation and `"type": "agent"` for multi-turn verification with tool access. See [Prompt-based hooks](#prompt-based-hooks) and [Agent-based hooks](#agent-based-hooks) for details.

287 

288### Read input and return output

289 

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

291 

292#### Hook input

293 

294Every 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:

295 

296```json theme={null}

297{

298 "session_id": "abc123", // unique ID for this session

299 "cwd": "/Users/sarah/myproject", // working directory when the event fired

300 "hook_event_name": "PreToolUse", // which event triggered this hook

301 "tool_name": "Bash", // the tool Claude is about to use

302 "tool_input": { // the arguments Claude passed to the tool

303 "command": "npm test" // for Bash, this is the shell command

304 }

305}

128```306```

129ls - Lists files and directories307 

308Your script can parse that JSON and act on any of those fields. `UserPromptSubmit` hooks get the `prompt` text instead, `SessionStart` hooks get the `source` (startup, resume, compact), and so on. See [Common input fields](/en/hooks#common-input-fields) in the reference for shared fields, and each event's section for event-specific schemas.

309 

310#### Hook output

311 

312Your 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:

313 

314```bash theme={null}

315#!/bin/bash

316INPUT=$(cat)

317COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')

318 

319if echo "$COMMAND" | grep -q "drop table"; then

320 echo "Blocked: dropping tables is not allowed" >&2 # stderr becomes Claude's feedback

321 exit 2 # exit 2 = block the action

322fi

323 

324exit 0 # exit 0 = let it proceed

130```325```

131 326 

132## More Examples327The exit code determines what happens next:

328 

329* **Exit 0**: the action proceeds. For `UserPromptSubmit` and `SessionStart` hooks, anything you write to stdout is added to Claude's context.

330* **Exit 2**: the action is blocked. Write a reason to stderr, and Claude receives it as feedback so it can adjust.

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

332 

333#### Structured JSON output

334 

335Exit codes give you two options: allow or block. For more control, exit 0 and print a JSON object to stdout instead.

133 336 

134<Note>337<Note>

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

136</Note>339</Note>

137 340 

138### Code Formatting Hook341For example, a `PreToolUse` hook can deny a tool call and tell Claude why, or escalate it to the user for approval:

342 

343```json theme={null}

344{

345 "hookSpecificOutput": {

346 "hookEventName": "PreToolUse",

347 "permissionDecision": "deny",

348 "permissionDecisionReason": "Use rg instead of grep for better performance"

349 }

350}

351```

352 

353Claude Code reads `permissionDecision` and cancels the tool call, then feeds `permissionDecisionReason` back to Claude as feedback. These three options are specific to `PreToolUse`:

354 

355* `"allow"`: proceed without showing a permission prompt

356* `"deny"`: cancel the tool call and send the reason to Claude

357* `"ask"`: show the permission prompt to the user as normal

139 358 

140Automatically format TypeScript files after editing:359Other 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.

360 

361For `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).

362 

363### Filter hooks with matchers

364 

365Without 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:

141 366 

142```json theme={null}367```json theme={null}

143{368{


146 {371 {

147 "matcher": "Edit|Write",372 "matcher": "Edit|Write",

148 "hooks": [373 "hooks": [

149 {374 { "type": "command", "command": "prettier --write ..." }

150 "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; }"

152 }

153 ]375 ]

154 }376 }

155 ]377 ]


157}379}

158```380```

159 381 

160### Markdown Formatting Hook382The `"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.

161 383 

162Automatically fix missing language tags and formatting issues in markdown files:384Each event type matches on a specific field. Matchers support exact strings and regex patterns:

163 385 

164```json theme={null}386| Event | What the matcher filters | Example matcher values |

165{387| :--------------------------------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------- |

388| `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest` | tool name | `Bash`, `Edit\|Write`, `mcp__.*` |

389| `SessionStart` | how the session started | `startup`, `resume`, `clear`, `compact` |

390| `SessionEnd` | why the session ended | `clear`, `logout`, `prompt_input_exit`, `bypass_permissions_disabled`, `other` |

391| `Notification` | notification type | `permission_prompt`, `idle_prompt`, `auth_success`, `elicitation_dialog` |

392| `SubagentStart` | agent type | `Bash`, `Explore`, `Plan`, or custom agent names |

393| `PreCompact` | what triggered compaction | `manual`, `auto` |

394| `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted` | no matcher support | always fires on every occurrence |

395| `SubagentStop` | agent type | same values as `SubagentStart` |

396 

397A few more examples showing matchers on different event types:

398 

399<Tabs>

400 <Tab title="Log every Bash command">

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

402 

403 ```json theme={null}

404 {

166 "hooks": {405 "hooks": {

167 "PostToolUse": [406 "PostToolUse": [

168 {407 {

169 "matcher": "Edit|Write",408 "matcher": "Bash",

170 "hooks": [409 "hooks": [

171 {410 {

172 "type": "command",411 "type": "command",

173 "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"412 "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"

174 }413 }

175 ]414 ]

176 }415 }

177 ]416 ]

178 }417 }

179}418 }

180```419 ```

420 </Tab>

181 421 

182Create `.claude/hooks/markdown_formatter.py` with this content:422 <Tab title="Match MCP tools">

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

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 424 

272```bash theme={null}425 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`):

273chmod +x .claude/hooks/markdown_formatter.py426 

274```427 ```json theme={null}

428 {

429 "hooks": {

430 "PreToolUse": [

431 {

432 "matcher": "mcp__github__.*",

433 "hooks": [

434 {

435 "type": "command",

436 "command": "echo \"GitHub tool called: $(jq -r '.tool_name')\" >&2"

437 }

438 ]

439 }

440 ]

441 }

442 }

443 ```

444 </Tab>

445 

446 <Tab title="Clean up on session end">

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

448 

449 ```json theme={null}

450 {

451 "hooks": {

452 "SessionEnd": [

453 {

454 "matcher": "clear",

455 "hooks": [

456 {

457 "type": "command",

458 "command": "rm -f /tmp/claude-scratch-*.txt"

459 }

460 ]

461 }

462 ]

463 }

464 }

465 ```

466 </Tab>

467</Tabs>

468 

469For full matcher syntax, see the [Hooks reference](/en/hooks#configuration).

275 470 

276This hook automatically:471### Configure hook location

277 472 

278* Detects programming languages in unlabeled code blocks473Where you add a hook determines its scope:

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 474 

283### Custom Notification Hook475| Location | Scope | Shareable |

476| :--------------------------------------------------------- | :--------------------------------- | :--------------------------------- |

477| `~/.claude/settings.json` | All your projects | No, local to your machine |

478| `.claude/settings.json` | Single project | Yes, can be committed to the repo |

479| `.claude/settings.local.json` | Single project | No, gitignored |

480| Managed policy settings | Organization-wide | Yes, admin-controlled |

481| [Plugin](/en/plugins) `hooks/hooks.json` | When plugin is enabled | Yes, bundled with the plugin |

482| [Skill](/en/skills) or [agent](/en/sub-agents) frontmatter | While the skill or agent is active | Yes, defined in the component file |

284 483 

285Get desktop notifications when Claude needs input:484You can also use the [`/hooks` menu](/en/hooks#the-hooks-menu) in Claude Code to add, delete, and view hooks interactively. To disable all hooks at once, use the toggle at the bottom of the `/hooks` menu or set `"disableAllHooks": true` in your settings file.

485 

486Hooks added through the `/hooks` menu take effect immediately. If you edit settings files directly while Claude Code is running, the changes won't take effect until you review them in the `/hooks` menu or restart your session.

487 

488## Prompt-based hooks

489 

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

491 

492The model's only job is to return a yes/no decision as JSON:

493 

494* `"ok": true`: the action proceeds

495* `"ok": false`: the action is blocked. The model's `"reason"` is fed back to Claude so it can adjust.

496 

497This 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:

286 498 

287```json theme={null}499```json theme={null}

288{500{

289 "hooks": {501 "hooks": {

290 "Notification": [502 "Stop": [

291 {503 {

292 "matcher": "",

293 "hooks": [504 "hooks": [

294 {505 {

295 "type": "command",506 "type": "prompt",

296 "command": "notify-send 'Claude Code' 'Awaiting your input'"507 "prompt": "Check if all tasks are complete. If not, respond with {\"ok\": false, \"reason\": \"what remains to be done\"}."

297 }508 }

298 ]509 ]

299 }510 }


302}513}

303```514```

304 515 

305### File Protection Hook516For full configuration options, see [Prompt-based hooks](/en/hooks#prompt-based-hooks) in the reference.

517 

518## Agent-based hooks

519 

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

306 521 

307Block edits to sensitive files:522Agent 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.

523 

524This example verifies that tests pass before allowing Claude to stop:

308 525 

309```json theme={null}526```json theme={null}

310{527{

311 "hooks": {528 "hooks": {

312 "PreToolUse": [529 "Stop": [

313 {530 {

314 "matcher": "Edit|Write",

315 "hooks": [531 "hooks": [

316 {532 {

317 "type": "command",533 "type": "agent",

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)\""534 "prompt": "Verify that all unit tests pass. Run the test suite and check the results. $ARGUMENTS",

535 "timeout": 120

319 }536 }

320 ]537 ]

321 }538 }


324}541}

325```542```

326 543 

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

545 

546For full configuration options, see [Agent-based hooks](/en/hooks#agent-based-hooks) in the reference.

547 

548## Limitations and troubleshooting

549 

550### Limitations

551 

552* Hooks communicate through stdout, stderr, and exit codes only. They cannot trigger slash commands or tool calls directly.

553* Hook timeout is 10 minutes by default, configurable per hook with the `timeout` field (in seconds).

554* `PostToolUse` hooks cannot undo actions since the tool has already executed.

555* `PermissionRequest` hooks do not fire in [non-interactive mode](/en/headless) (`-p`). Use `PreToolUse` hooks for automated permission decisions.

556* `Stop` hooks fire whenever Claude finishes responding, not only at task completion. They do not fire on user interrupts.

557 

558### Hook not firing

559 

560The hook is configured but never executes.

561 

562* Run `/hooks` and confirm the hook appears under the correct event

563* Check that the matcher pattern matches the tool name exactly (matchers are case-sensitive)

564* Verify you're triggering the right event type (e.g., `PreToolUse` fires before tool execution, `PostToolUse` fires after)

565* If using `PermissionRequest` hooks in non-interactive mode (`-p`), switch to `PreToolUse` instead

566 

567### Hook error in output

568 

569You see a message like "PreToolUse hook error: ..." in the transcript.

570 

571* Your script exited with a non-zero code unexpectedly. Test it manually by piping sample JSON:

572 ```bash theme={null}

573 echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh

574 echo $? # Check the exit code

575 ```

576* If you see "command not found", use absolute paths or `$CLAUDE_PROJECT_DIR` to reference scripts

577* If you see "jq: command not found", install `jq` or use Python/Node.js for JSON parsing

578* If the script isn't running at all, make it executable: `chmod +x ./my-hook.sh`

579 

580### `/hooks` shows no hooks configured

581 

582You edited a settings file but the hooks don't appear in the menu.

583 

584* Restart your session or open `/hooks` to reload. Hooks added through the `/hooks` menu take effect immediately, but manual file edits require a reload.

585* Verify your JSON is valid (trailing commas and comments are not allowed)

586* Confirm the settings file is in the correct location: `.claude/settings.json` for project hooks, `~/.claude/settings.json` for global hooks

587 

588### Stop hook runs forever

589 

590Claude keeps working in an infinite loop instead of stopping.

591 

592Your 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`:

593 

594```bash theme={null}

595#!/bin/bash

596INPUT=$(cat)

597if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then

598 exit 0 # Allow Claude to stop

599fi

600# ... rest of your hook logic

601```

602 

603### JSON validation failed

604 

605Claude Code shows a JSON parsing error even though your hook script outputs valid JSON.

606 

607When 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:

608 

609```

610Shell ready on arm64

611{"decision": "block", "reason": "Not allowed"}

612```

613 

614Claude 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:

615 

616```bash theme={null}

617# In ~/.zshrc or ~/.bashrc

618if [[ $- == *i* ]]; then

619 echo "Shell ready"

620fi

621```

622 

623The `$-` variable contains shell flags, and `i` means interactive. Hooks run in non-interactive shells, so the echo is skipped.

624 

625### Debug techniques

626 

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

628 

327## Learn more629## Learn more

328 630 

329* For reference documentation on hooks, see [Hooks reference](/en/hooks).631* [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/hooks#security-considerations) in the hooks reference documentation.632* [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/hooks#debugging) in the hooks reference633* [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 +240 −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/ELkJZG54dIaeldDC/images/agentic-loop.svg?fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=e30acfc80d6ff01ec877dd19c7af58b2" alt="The agentic loop: Your prompt leads to Claude gathering context, taking action, verifying results, and repeating until task complete. You can interrupt at any point." data-og-width="720" width="720" data-og-height="280" height="280" data-path="images/agentic-loop.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=280&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=8620f6ebce761a1e8bbf7f0a0255cc15 280w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=560&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=7b46b5ff4454aa4a03725eee625b39a0 560w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=840&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=7fa0397bc37d147e3bf3bb6296c6477f 840w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=1100&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=73b2a7040c4c93821c4d5bbee9f4a2d4 1100w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=1650&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=17703cbeb6f59b40a00ab24f56d5f8f9 1650w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/agentic-loop.svg?w=2500&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=20dedb60b95d45a1bd60a0cccaf3e1ff 2500w" />

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 four 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/settings#tools-available-to-claude) 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, JetBrains IDEs, and other environments](/en/ide-integrations).

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* **Extensions you configure.** [MCP servers](/en/mcp) for external services, [skills](/en/skills) for workflows, [subagents](/en/sub-agents) for delegated work, and [Claude in Chrome](/en/chrome) for browser interaction.

73 

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

75 

76## Work with sessions

77 

78Claude Code saves your conversation locally as you work. Each message, tool use, and result is stored, which enables [rewinding](#undo-changes-with-checkpoints), [resuming, and forking](#resume-or-fork-sessions) sessions. Before Claude makes code changes, it also snapshots the affected files so you can revert if needed.

79 

80**Sessions are independent.** Each new session starts with a fresh context window, without the conversation history from previous sessions. Claude can persist learnings across sessions using [auto memory](/en/memory#auto-memory), and you can add your own persistent instructions in [CLAUDE.md](/en/memory).

81 

82### Work across branches

83 

84Each Claude Code conversation is a session tied to your current directory. When you resume, you only see sessions from that directory.

85 

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

87 

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

89 

90### Resume or fork sessions

91 

92When you resume a session with `claude --continue` or `claude --resume`, you pick up where you left off using the same session ID. New messages append to the existing conversation. Your full conversation history is restored, but session-scoped permissions are not. You'll need to re-approve those.

93 

94<img src="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=f671b603cc856119c95475b9084ebfef" alt="Session continuity: resume continues the same session, fork creates a new branch with a new ID." data-og-width="560" width="560" data-og-height="280" height="280" data-path="images/session-continuity.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=280&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=bddf1f33d419a27d7427acdf06058804 280w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=560&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=417478eb9b86003b8eebaac058a8618a 560w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=840&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=1d89d26e2c0487f067d187c3fa5f7170 840w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=1100&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=8ea739a1f7860e4edbbcf74d444e37b2 1100w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=1650&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=9cb5095d6a8920f04c3b78d31a69c809 1650w, https://mintcdn.com/claude-code/ELkJZG54dIaeldDC/images/session-continuity.svg?w=2500&fit=max&auto=format&n=ELkJZG54dIaeldDC&q=85&s=d67e1744e4878813d20c6c3f39d9459d 2500w" />

95 

96To branch off and try a different approach without affecting the original session, use the `--fork-session` flag:

97 

98```bash theme={null}

99claude --continue --fork-session

100```

101 

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

103 

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

105 

106### The context window

107 

108Claude's context window holds your conversation history, file contents, command outputs, [CLAUDE.md](/en/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.

109 

110#### When context fills up

111 

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

113 

114To 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`).

115 

116Run `/context` to see what's using space. MCP servers add tool definitions to every request, so a few servers can consume significant context before you start working. Run `/mcp` to check per-server costs.

117 

118#### Manage context with skills and subagents

119 

120Beyond compaction, you can use other features to control what loads into context.

121 

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

123 

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

125 

126See [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.

127 

128## Stay safe with checkpoints and permissions

129 

130Claude has two safety mechanisms: checkpoints let you undo file changes, and permissions control what Claude can do without asking.

131 

132### Undo changes with checkpoints

133 

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

135 

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

137 

138### Control what Claude can do

139 

140Press `Shift+Tab` to cycle through permission modes:

141 

142* **Default**: Claude asks before file edits and shell commands

143* **Auto-accept edits**: Claude edits files without asking, still asks for commands

144* **Plan mode**: Claude uses read-only tools only, creating a plan you can approve before execution

145* **Delegate mode**: Claude coordinates work through [agent teammates](/en/agent-teams) only, with no direct implementation. Only available when an agent team is active.

146 

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

148 

149***

150 

151## Work effectively with Claude Code

152 

153These tips help you get better results from Claude Code.

154 

155### Ask Claude Code for help

156 

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

158 

159Built-in commands also guide you through setup:

160 

161* `/init` walks you through creating a CLAUDE.md for your project

162* `/agents` helps you configure custom subagents

163* `/doctor` diagnoses common issues with your installation

164 

165### It's a conversation

166 

167Claude Code is conversational. You don't need perfect prompts. Start with what you want, then refine:

168 

169```

170> Fix the login bug

171 

172[Claude investigates, tries something]

173 

174> That's not quite right. The issue is in the session handling.

175 

176[Claude adjusts approach]

177```

178 

179When the first attempt isn't right, you don't start over. You iterate.

180 

181#### Interrupt and steer

182 

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

184 

185### Be specific upfront

186 

187The more precise your initial prompt, the fewer corrections you'll need. Reference specific files, mention constraints, and point to example patterns.

188 

189```

190> The checkout flow is broken for users with expired cards.

191> Check src/payments/ for the issue, especially token refresh.

192> Write a failing test first, then fix it.

193```

194 

195Vague prompts like "fix the login bug" work, but you'll spend more time steering. Specific prompts like the above often succeed on the first attempt.

196 

197### Give Claude something to verify against

198 

199Claude performs better when it can check its own work. Include test cases, paste screenshots of expected UI, or define the output you want.

200 

201```

202> Implement validateEmail. Test cases: 'user@example.com' → true,

203> 'invalid' → false, 'user@.com' → false. Run the tests after.

204```

205 

206For visual work, paste a screenshot of the design and ask Claude to compare its implementation against it.

207 

208### Explore before implementing

209 

210For complex problems, separate research from coding. Use plan mode (`Shift+Tab` twice) to analyze the codebase first:

211 

212```

213> Read src/auth/ and understand how we handle sessions.

214> Then create a plan for adding OAuth support.

215```

216 

217Review the plan, refine it through conversation, then let Claude implement. This two-phase approach produces better results than jumping straight to code.

218 

219### Delegate, don't dictate

220 

221Think of delegating to a capable colleague. Give context and direction, then trust Claude to figure out the details:

222 

223```

224> The checkout flow is broken for users with expired cards.

225> The relevant code is in src/payments/. Can you investigate and fix it?

226```

227 

228You don't need to specify which files to read or what commands to run. Claude figures that out.

229 

230## What's next

231 

232<CardGroup cols={2}>

233 <Card title="Extend with features" icon="puzzle-piece" href="/en/features-overview">

234 Add Skills, MCP connections, and custom commands

235 </Card>

236 

237 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">

238 Step-by-step guides for typical tasks

239 </Card>

240</CardGroup>

iam.md +0 −201 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 four ways:

8 

9* Claude API via the Claude Console

10* Amazon Bedrock

11* Azure AI Foundry

12* Google Vertex AI

13 

14### Claude API authentication

15 

16**To set up Claude Code access for your team via Claude API:**

17 

181. Use your existing Claude Console account or create a new Claude Console account

192. You can add users through either method below:

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

21 * [Set up SSO](https://support.claude.com/en/articles/10280258-setting-up-single-sign-on-on-the-api-console)

223. When inviting users, they need one of the following roles:

23 * "Claude Code" role means users can only create Claude Code API keys

24 * "Developer" role means users can create any kind of API key

254. Each invited user needs to complete these steps:

26 * Accept the Console invite

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

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

29 * Login with Console account credentials

30 

31### Cloud provider authentication

32 

33**To set up Claude Code access for your team via Bedrock, Vertex, or Azure:**

34 

351. Follow the [Bedrock docs](/en/amazon-bedrock), [Vertex docs](/en/google-vertex-ai), or [Azure AI Foundry docs](/en/azure-ai-foundry)

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

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

38 

39## Access control and permissions

40 

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

42 

43### Permission system

44 

45Claude Code uses a tiered permission system to balance power and safety:

46 

47| Tool Type | Example | Approval Required | "Yes, don't ask again" Behavior |

48| :---------------- | :------------------- | :---------------- | :-------------------------------------------- |

49| Read-only | File reads, LS, Grep | No | N/A |

50| Bash Commands | Shell execution | Yes | Permanently per project directory and command |

51| File Modification | Edit/write files | Yes | Until session end |

52 

53### Configuring permissions

54 

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

56 

57* **Allow** rules will allow Claude Code to use the specified tool without further manual approval.

58* **Ask** rules will ask the user for confirmation whenever Claude Code tries to use the specified tool. Ask rules take precedence over allow rules.

59* **Deny** rules will prevent Claude Code from using the specified tool. Deny rules take precedence over allow and ask rules.

60* **Additional directories** extend Claude's file access to directories beyond the initial working directory.

61* **Default mode** controls Claude's permission behavior when encountering new requests.

62 

63Permission rules use the format: `Tool` or `Tool(optional-specifier)`

64 

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

66 

67#### Permission modes

68 

69Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/en/settings#settings-files):

70 

71| Mode | Description |

72| :------------------ | :--------------------------------------------------------------------------- |

73| `default` | Standard behavior - prompts for permission on first use of each tool |

74| `acceptEdits` | Automatically accepts file edit permissions for the session |

75| `plan` | Plan Mode - Claude can analyze but not modify files or execute commands |

76| `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) |

77 

78#### Working directories

79 

80By default, Claude has access to files in the directory where it was launched. You can extend this access:

81 

82* **During startup**: Use `--add-dir <path>` CLI argument

83* **During session**: Use `/add-dir` slash command

84* **Persistent configuration**: Add to `additionalDirectories` in [settings files](/en/settings#settings-files)

85 

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

87 

88#### Tool-specific permission rules

89 

90Some tools support more fine-grained permission controls:

91 

92**Bash**

93 

94* `Bash(npm run build)` Matches the exact Bash command `npm run build`

95* `Bash(npm run test:*)` Matches Bash commands starting with `npm run test`

96* `Bash(curl http://site.com/:*)` Matches curl commands that start with exactly `curl http://site.com/`

97 

98<Tip>

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

100</Tip>

101 

102<Warning>

103 Important limitations of Bash permission patterns:

104 

105 1. This tool uses **prefix matches**, not regex or glob patterns

106 2. The wildcard `:*` only works at the end of a pattern to match any continuation

107 3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in many ways:

108 * Options before URL: `curl -X GET http://github.com/...` won't match

109 * Different protocol: `curl https://github.com/...` won't match

110 * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)

111 * Variables: `URL=http://github.com && curl $URL` won't match

112 * Extra spaces: `curl http://github.com` won't match

113 

114 For more reliable URL filtering, consider:

115 

116 * Using the WebFetch tool with `WebFetch(domain:github.com)` permission

117 * Instructing Claude Code about your allowed curl patterns via CLAUDE.md

118 * Using hooks for custom permission validation

119</Warning>

120 

121**Read & Edit**

122 

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

124 

125Read & Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

126 

127| Pattern | Meaning | Example | Matches |

128| ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- |

129| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

130| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

131| `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `<settings file path>/src/**/*.ts` |

132| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

133 

134<Warning>

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

136</Warning>

137 

138* `Edit(/docs/**)` - Edits in `<project>/docs/` (NOT `/docs/`!)

139* `Read(~/.zshrc)` - Reads your home directory's `.zshrc`

140* `Edit(//tmp/scratch.txt)` - Edits the absolute path `/tmp/scratch.txt`

141* `Read(src/**)` - Reads from `<current-directory>/src/`

142 

143**WebFetch**

144 

145* `WebFetch(domain:example.com)` Matches fetch requests to example.com

146 

147**MCP**

148 

149* `mcp__puppeteer` Matches any tool provided by the `puppeteer` server (name configured in Claude Code)

150* `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server

151 

152<Warning>

153 Unlike other permission types, MCP permissions do NOT support wildcards (`*`).

154 

155 To approve all tools from an MCP server:

156 

157 * ✅ Use: `mcp__github` (approves ALL GitHub tools)

158 * ❌ Don't use: `mcp__github__*` (wildcards are not supported)

159 

160 To approve specific tools only, list each one:

161 

162 * ✅ Use: `mcp__github__get_issue`

163 * ✅ Use: `mcp__github__list_issues`

164</Warning>

165 

166### Additional permission control with hooks

167 

168[Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system runs, and the hook output can determine whether to approve or deny the tool call in place of the permission system.

169 

170### Enterprise managed policy settings

171 

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

173 

174System administrators can deploy policies to:

175 

176* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`

177* Linux and WSL: `/etc/claude-code/managed-settings.json`

178* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`

179 

180These policy files follow the same format as regular [settings files](/en/settings#settings-files) but cannot be overridden by user or project settings. This ensures consistent security policies across your organization.

181 

182### Settings precedence

183 

184When multiple settings sources exist, they are applied in the following order (highest to lowest precedence):

185 

1861. Enterprise policies

1872. Command line arguments

1883. Local project settings (`.claude/settings.local.json`)

1894. Shared project settings (`.claude/settings.json`)

1905. User settings (`~/.claude/settings.json`)

191 

192This hierarchy ensures that organizational policies are always enforced while still allowing flexibility at the project and user levels where appropriate.

193 

194## Credential management

195 

196Claude Code securely manages your authentication credentials:

197 

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

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

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

201* **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 +171 −14

Details

1> ## Documentation Index

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

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

4 

1# 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`) 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**: Settings → Profiles → Keys → Set Left/Right Option key to "Esc+"

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 |

16| `Ctrl+D` | Exit Claude Code session | EOF signal |28| `Ctrl+D` | Exit Claude Code session | EOF signal |

29| `Ctrl+G` | Open in default text editor | Edit your prompt or custom response in your default text editor |

17| `Ctrl+L` | Clear terminal screen | Keeps conversation history |30| `Ctrl+L` | Clear terminal screen | Keeps conversation history |

18| `Ctrl+O` | Toggle verbose output | Shows detailed tool usage and execution |31| `Ctrl+O` | Toggle verbose output | Shows detailed tool usage and execution |

19| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |32| `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 |33| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file |

34| `Ctrl+B` | Background running tasks | Backgrounds bash commands and agents. Tmux users press twice |

35| `Ctrl+T` | Toggle task list | Show or hide the [task list](#task-list) in the terminal status area |

36| `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 |37| `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 |38| `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](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) | Switch between Thinking on and Thinking off |39| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode. When an [agent team](/en/agent-teams) is active, the cycle also includes Delegate Mode. |

24| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode |40| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |

41| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Run `/terminal-setup` first to enable this shortcut |

42 

43### Text editing

44 

45| Shortcut | Description | Context |

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

47| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |

48| `Ctrl+U` | Delete entire line | Stores deleted text for pasting |

49| `Ctrl+Y` | Paste deleted text | Paste text deleted with `Ctrl+K` or `Ctrl+U` |

50| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

51| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

52| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |

53 

54### Theme and display

55 

56| Shortcut | Description | Context |

57| :------- | :----------------------------------------- | :----------------------------------------------------------------------------------------------------------- |

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

59 

60<Note>

61 Syntax highlighting is only available in the native build of Claude Code.

62</Note>

25 63 

26### Multiline input64### Multiline input

27 65 

28| Method | Shortcut | Context |66| Method | Shortcut | Context |

29| :--------------- | :------------- | :-------------------------------- |67| :--------------- | :------------- | :------------------------------------------------------ |

30| Quick escape | `\` + `Enter` | Works in all terminals |68| Quick escape | `\` + `Enter` | Works in all terminals |

31| macOS default | `Option+Enter` | Default on macOS |69| macOS default | `Option+Enter` | Default on macOS |

32| Terminal setup | `Shift+Enter` | After `/terminal-setup` |70| Shift+Enter | `Shift+Enter` | Works out of the box in iTerm2, WezTerm, Ghostty, Kitty |

33| Control sequence | `Ctrl+J` | Line feed character for multiline |71| Control sequence | `Ctrl+J` | Line feed character for multiline |

34| Paste mode | Paste directly | For code blocks, logs |72| Paste mode | Paste directly | For code blocks, logs |

35 73 

36<Tip>74<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.75 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>76</Tip>

39 77 

40### Quick commands78### Quick commands

41 79 

42| Shortcut | Description | Notes |80| Shortcut | Description | Notes |

43| :----------- | :--------------------------------- | :------------------------------------------------------------ |81| :----------- | :---------------- | :------------------------------------------------------------------- |

44| `#` at start | Memory shortcut - add to CLAUDE.md | Prompts for file selection |82| `/` 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/slash-commands) |

46| `!` at start | Bash mode | Run commands directly and add execution output to the session |83| `!` at start | Bash mode | Run commands directly and add execution output to the session |

47| `@` | File path mention | Trigger file path autocomplete |84| `@` | File path mention | Trigger file path autocomplete |

48 85 

86## Built-in commands

87 

88Built-in commands are shortcuts for common actions. The table below covers commonly used commands but not all available options. Type `/` in Claude Code to see the full list, or type `/` followed by any letters to filter.

89 

90To create your own commands you can invoke with `/`, see [skills](/en/skills).

91 

92| Command | Purpose |

93| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

94| `/clear` | Clear conversation history |

95| `/compact [instructions]` | Compact conversation with optional focus instructions |

96| `/config` | Open the Settings interface (Config tab) |

97| `/context` | Visualize current context usage as a colored grid |

98| `/cost` | Show token usage statistics. See [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details. |

99| `/debug [description]` | Troubleshoot the current session by reading the session debug log. Optionally describe the issue |

100| `/doctor` | Checks the health of your Claude Code installation |

101| `/exit` | Exit the REPL |

102| `/export [filename]` | Export the current conversation to a file or clipboard |

103| `/help` | Get usage help |

104| `/init` | Initialize project with `CLAUDE.md` guide |

105| `/mcp` | Manage MCP server connections and OAuth authentication |

106| `/memory` | Edit `CLAUDE.md` memory files |

107| `/model` | Select or change the AI model. With Opus 4.6, use left/right arrows to [adjust effort level](/en/model-config#adjust-effort-level). The change takes effect immediately without waiting for the current response to finish |

108| `/permissions` | View or update [permissions](/en/permissions#manage-permissions) |

109| `/plan` | Enter plan mode directly from the prompt |

110| `/rename <name>` | Rename the current session for easier identification |

111| `/resume [session]` | Resume a conversation by ID or name, or open the session picker |

112| `/rewind` | Rewind the conversation and/or code, or summarize from a selected message |

113| `/stats` | Visualize daily usage, session history, streaks, and model preferences |

114| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |

115| `/statusline` | Set up Claude Code's status line UI |

116| `/copy` | Copy the last assistant response to clipboard |

117| `/tasks` | List and manage background tasks |

118| `/teleport` | Resume a remote session from claude.ai (subscribers only) |

119| `/theme` | Change the color theme |

120| `/todos` | List current TODO items |

121| `/usage` | For subscription plans only: show plan usage limits and rate limit status |

122 

123### MCP prompts

124 

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

126 

49## Vim editor mode127## Vim editor mode

50 128 

51Enable vim-style editing with `/vim` command or configure permanently via `/config`.129Enable vim-style editing with `/vim` command or configure permanently via `/config`.


65### Navigation (NORMAL mode)143### Navigation (NORMAL mode)

66 144 

67| Command | Action |145| Command | Action |

68| :-------------- | :------------------------ |146| :-------------- | :-------------------------------------------------- |

69| `h`/`j`/`k`/`l` | Move left/down/up/right |147| `h`/`j`/`k`/`l` | Move left/down/up/right |

70| `w` | Next word |148| `w` | Next word |

71| `e` | End of word |149| `e` | End of word |


75| `^` | First non-blank character |153| `^` | First non-blank character |

76| `gg` | Beginning of input |154| `gg` | Beginning of input |

77| `G` | End of input |155| `G` | End of input |

156| `f{char}` | Jump to next occurrence of character |

157| `F{char}` | Jump to previous occurrence of character |

158| `t{char}` | Jump to just before next occurrence of character |

159| `T{char}` | Jump to just after previous occurrence of character |

160| `;` | Repeat last f/F/t/T motion |

161| `,` | Repeat last f/F/t/T motion in reverse |

162 

163<Note>

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

165</Note>

78 166 

79### Editing (NORMAL mode)167### Editing (NORMAL mode)

80 168 


87| `cc` | Change line |175| `cc` | Change line |

88| `C` | Change to end of line |176| `C` | Change to end of line |

89| `cw`/`ce`/`cb` | Change word/to end/back |177| `cw`/`ce`/`cb` | Change word/to end/back |

178| `yy`/`Y` | Yank (copy) line |

179| `yw`/`ye`/`yb` | Yank word/to end/back |

180| `p` | Paste after cursor |

181| `P` | Paste before cursor |

182| `>>` | Indent line |

183| `<<` | Dedent line |

184| `J` | Join lines |

90| `.` | Repeat last change |185| `.` | Repeat last change |

91 186 

187### Text objects (NORMAL mode)

188 

189Text objects work with operators like `d`, `c`, and `y`:

190 

191| Command | Action |

192| :-------- | :--------------------------------------- |

193| `iw`/`aw` | Inner/around word |

194| `iW`/`aW` | Inner/around WORD (whitespace-delimited) |

195| `i"`/`a"` | Inner/around double quotes |

196| `i'`/`a'` | Inner/around single quotes |

197| `i(`/`a(` | Inner/around parentheses |

198| `i[`/`a[` | Inner/around brackets |

199| `i{`/`a{` | Inner/around braces |

200 

92## Command history201## Command history

93 202 

94Claude Code maintains command history for the current session:203Claude Code maintains command history for the current session:


129 238 

130**Key features:**239**Key features:**

131 240 

132* Output is buffered and Claude can retrieve it using the BashOutput tool241* Output is buffered and Claude can retrieve it using the TaskOutput tool

133* Background tasks have unique IDs for tracking and output retrieval242* Background tasks have unique IDs for tracking and output retrieval

134* Background tasks are automatically cleaned up when Claude Code exits243* Background tasks are automatically cleaned up when Claude Code exits

135 244 

245To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables) for details.

246 

136**Common backgrounded commands:**247**Common backgrounded commands:**

137 248 

138* Build tools (webpack, vite, make)249* Build tools (webpack, vite, make)


157* Shows real-time progress and output268* Shows real-time progress and output

158* Supports the same `Ctrl+B` backgrounding for long-running commands269* Supports the same `Ctrl+B` backgrounding for long-running commands

159* Does not require Claude to interpret or approve the command270* Does not require Claude to interpret or approve the command

271* Supports history-based autocomplete: type a partial command and press **Tab** to complete from previous `!` commands in the current project

160 272 

161This is useful for quick shell operations while maintaining conversation context.273This is useful for quick shell operations while maintaining conversation context.

162 274 

275## Prompt suggestions

276 

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

278 

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

280 

281* Press **Tab** to accept the suggestion, or press **Enter** to accept and submit

282* Start typing to dismiss it

283 

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

285 

286Suggestions are automatically skipped after the first turn of a conversation, in non-interactive mode, and in plan mode.

287 

288To disable prompt suggestions entirely, set the environment variable or toggle the setting in `/config`:

289 

290```bash theme={null}

291export CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false

292```

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* To revert to the previous TODO list, set `CLAUDE_CODE_ENABLE_TASKS=false`.

303 

304## PR review status

305 

306When 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:

307 

308* Green: approved

309* Yellow: pending review

310* Red: changes requested

311* Gray: draft

312* Purple: merged

313 

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

315 

316<Note>

317 PR status requires the `gh` CLI to be installed and authenticated (`gh auth login`).

318</Note>

319 

163## See also320## See also

164 321 

165* [Slash commands](/en/slash-commands) - Interactive session commands322* [Skills](/en/skills) - Custom prompts and workflows

166* [Checkpointing](/en/checkpointing) - Rewind Claude's edits and restore previous states323* [Checkpointing](/en/checkpointing) - Rewind Claude's edits and restore previous states

167* [CLI reference](/en/cli-reference) - Command-line flags and options324* [CLI reference](/en/cli-reference) - Command-line flags and options

168* [Settings](/en/settings) - Configuration options325* [Settings](/en/settings) - Configuration options

jetbrains.md +8 −6

Details

1> ## Documentation Index

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

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

4 

1# 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


70 72 

71#### General Settings73#### General Settings

72 74 

73* **Claude command**: Specify a custom command to run Claude (e.g., `claude`, `/usr/local/bin/claude`, or `npx @anthropic/claude`)75* **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 command76* **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)77* **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)78* **Enable automatic updates**: Automatically check for and install plugin updates (applied on restart)

keybindings.md +381 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Customize keyboard shortcuts

6 

7> Customize keyboard shortcuts in Claude Code with a keybindings configuration file.

8 

9Claude Code supports customizable keyboard shortcuts. Run `/keybindings` to create or open your configuration file at `~/.claude/keybindings.json`.

10 

11## Configuration file

12 

13The keybindings configuration file is an object with a `bindings` array. Each block specifies a context and a map of keystrokes to actions.

14 

15<Note>Changes to the keybindings file are automatically detected and applied without restarting Claude Code.</Note>

16 

17| Field | Description |

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

19| `$schema` | Optional JSON Schema URL for editor autocompletion |

20| `$docs` | Optional documentation URL |

21| `bindings` | Array of binding blocks by context |

22 

23This example binds `Ctrl+E` to open an external editor in the chat context, and unbinds `Ctrl+U`:

24 

25```json theme={null}

26{

27 "$schema": "https://www.schemastore.org/claude-code-keybindings.json",

28 "$docs": "https://code.claude.com/docs/en/keybindings",

29 "bindings": [

30 {

31 "context": "Chat",

32 "bindings": {

33 "ctrl+e": "chat:externalEditor",

34 "ctrl+u": null

35 }

36 }

37 ]

38}

39```

40 

41## Contexts

42 

43Each binding block specifies a **context** where the bindings apply:

44 

45| Context | Description |

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

47| `Global` | Applies everywhere in the app |

48| `Chat` | Main chat input area |

49| `Autocomplete` | Autocomplete menu is open |

50| `Settings` | Settings menu (escape-only dismiss) |

51| `Confirmation` | Permission and confirmation dialogs |

52| `Tabs` | Tab navigation components |

53| `Help` | Help menu is visible |

54| `Transcript` | Transcript viewer |

55| `HistorySearch` | History search mode (Ctrl+R) |

56| `Task` | Background task is running |

57| `ThemePicker` | Theme picker dialog |

58| `Attachments` | Image/attachment bar navigation |

59| `Footer` | Footer indicator navigation (tasks, teams, diff) |

60| `MessageSelector` | Rewind and summarize dialog message selection |

61| `DiffDialog` | Diff viewer navigation |

62| `ModelPicker` | Model picker effort level |

63| `Select` | Generic select/list components |

64| `Plugin` | Plugin dialog (browse, discover, manage) |

65 

66## Available actions

67 

68Actions follow a `namespace:action` format, such as `chat:submit` to send a message or `app:toggleTodos` to show the task list. Each context has specific actions available.

69 

70### App actions

71 

72Actions available in the `Global` context:

73 

74| Action | Default | Description |

75| :--------------------- | :------ | :-------------------------- |

76| `app:interrupt` | Ctrl+C | Cancel current operation |

77| `app:exit` | Ctrl+D | Exit Claude Code |

78| `app:toggleTodos` | Ctrl+T | Toggle task list visibility |

79| `app:toggleTranscript` | Ctrl+O | Toggle verbose transcript |

80 

81### History actions

82 

83Actions for navigating command history:

84 

85| Action | Default | Description |

86| :----------------- | :------ | :-------------------- |

87| `history:search` | Ctrl+R | Open history search |

88| `history:previous` | Up | Previous history item |

89| `history:next` | Down | Next history item |

90 

91### Chat actions

92 

93Actions available in the `Chat` context:

94 

95| Action | Default | Description |

96| :-------------------- | :------------------------ | :----------------------- |

97| `chat:cancel` | Escape | Cancel current input |

98| `chat:cycleMode` | Shift+Tab\* | Cycle permission modes |

99| `chat:modelPicker` | Cmd+P / Meta+P | Open model picker |

100| `chat:thinkingToggle` | Cmd+T / Meta+T | Toggle extended thinking |

101| `chat:submit` | Enter | Submit message |

102| `chat:undo` | Ctrl+\_ | Undo last action |

103| `chat:externalEditor` | Ctrl+G | Open in external editor |

104| `chat:stash` | Ctrl+S | Stash current prompt |

105| `chat:imagePaste` | Ctrl+V (Alt+V on Windows) | Paste image |

106 

107\*On Windows without VT mode (Node \<24.2.0/\<22.17.0, Bun \<1.2.23), defaults to Meta+M.

108 

109### Autocomplete actions

110 

111Actions available in the `Autocomplete` context:

112 

113| Action | Default | Description |

114| :---------------------- | :------ | :------------------ |

115| `autocomplete:accept` | Tab | Accept suggestion |

116| `autocomplete:dismiss` | Escape | Dismiss menu |

117| `autocomplete:previous` | Up | Previous suggestion |

118| `autocomplete:next` | Down | Next suggestion |

119 

120### Confirmation actions

121 

122Actions available in the `Confirmation` context:

123 

124| Action | Default | Description |

125| :-------------------------- | :-------- | :---------------------------- |

126| `confirm:yes` | Y, Enter | Confirm action |

127| `confirm:no` | N, Escape | Decline action |

128| `confirm:previous` | Up | Previous option |

129| `confirm:next` | Down | Next option |

130| `confirm:nextField` | Tab | Next field |

131| `confirm:previousField` | (unbound) | Previous field |

132| `confirm:cycleMode` | Shift+Tab | Cycle permission modes |

133| `confirm:toggleExplanation` | Ctrl+E | Toggle permission explanation |

134 

135### Permission actions

136 

137Actions available in the `Confirmation` context for permission dialogs:

138 

139| Action | Default | Description |

140| :----------------------- | :------ | :--------------------------- |

141| `permission:toggleDebug` | Ctrl+D | Toggle permission debug info |

142 

143### Transcript actions

144 

145Actions available in the `Transcript` context:

146 

147| Action | Default | Description |

148| :------------------------- | :------------- | :---------------------- |

149| `transcript:toggleShowAll` | Ctrl+E | Toggle show all content |

150| `transcript:exit` | Ctrl+C, Escape | Exit transcript view |

151 

152### History search actions

153 

154Actions available in the `HistorySearch` context:

155 

156| Action | Default | Description |

157| :---------------------- | :---------- | :----------------------- |

158| `historySearch:next` | Ctrl+R | Next match |

159| `historySearch:accept` | Escape, Tab | Accept selection |

160| `historySearch:cancel` | Ctrl+C | Cancel search |

161| `historySearch:execute` | Enter | Execute selected command |

162 

163### Task actions

164 

165Actions available in the `Task` context:

166 

167| Action | Default | Description |

168| :---------------- | :------ | :---------------------- |

169| `task:background` | Ctrl+B | Background current task |

170 

171### Theme actions

172 

173Actions available in the `ThemePicker` context:

174 

175| Action | Default | Description |

176| :------------------------------- | :------ | :------------------------- |

177| `theme:toggleSyntaxHighlighting` | Ctrl+T | Toggle syntax highlighting |

178 

179### Help actions

180 

181Actions available in the `Help` context:

182 

183| Action | Default | Description |

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

185| `help:dismiss` | Escape | Close help menu |

186 

187### Tabs actions

188 

189Actions available in the `Tabs` context:

190 

191| Action | Default | Description |

192| :-------------- | :-------------- | :----------- |

193| `tabs:next` | Tab, Right | Next tab |

194| `tabs:previous` | Shift+Tab, Left | Previous tab |

195 

196### Attachments actions

197 

198Actions available in the `Attachments` context:

199 

200| Action | Default | Description |

201| :--------------------- | :---------------- | :------------------------- |

202| `attachments:next` | Right | Next attachment |

203| `attachments:previous` | Left | Previous attachment |

204| `attachments:remove` | Backspace, Delete | Remove selected attachment |

205| `attachments:exit` | Down, Escape | Exit attachment bar |

206 

207### Footer actions

208 

209Actions available in the `Footer` context:

210 

211| Action | Default | Description |

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

213| `footer:next` | Right | Next footer item |

214| `footer:previous` | Left | Previous footer item |

215| `footer:openSelected` | Enter | Open selected footer item |

216| `footer:clearSelection` | Escape | Clear footer selection |

217 

218### Message selector actions

219 

220Actions available in the `MessageSelector` context:

221 

222| Action | Default | Description |

223| :----------------------- | :---------------------------------------- | :---------------- |

224| `messageSelector:up` | Up, K | Move up in list |

225| `messageSelector:down` | Down, J | Move down in list |

226| `messageSelector:top` | Ctrl+Up, Shift+Up, Meta+Up, Shift+K | Jump to top |

227| `messageSelector:bottom` | Ctrl+Down, Shift+Down, Meta+Down, Shift+J | Jump to bottom |

228| `messageSelector:select` | Enter | Select message |

229 

230### Diff actions

231 

232Actions available in the `DiffDialog` context:

233 

234| Action | Default | Description |

235| :-------------------- | :----------------- | :--------------------- |

236| `diff:dismiss` | Escape | Close diff viewer |

237| `diff:previousSource` | Left | Previous diff source |

238| `diff:nextSource` | Right | Next diff source |

239| `diff:previousFile` | Up | Previous file in diff |

240| `diff:nextFile` | Down | Next file in diff |

241| `diff:viewDetails` | Enter | View diff details |

242| `diff:back` | (context-specific) | Go back in diff viewer |

243 

244### Model picker actions

245 

246Actions available in the `ModelPicker` context:

247 

248| Action | Default | Description |

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

250| `modelPicker:decreaseEffort` | Left | Decrease effort level |

251| `modelPicker:increaseEffort` | Right | Increase effort level |

252 

253### Select actions

254 

255Actions available in the `Select` context:

256 

257| Action | Default | Description |

258| :---------------- | :-------------- | :--------------- |

259| `select:next` | Down, J, Ctrl+N | Next option |

260| `select:previous` | Up, K, Ctrl+P | Previous option |

261| `select:accept` | Enter | Accept selection |

262| `select:cancel` | Escape | Cancel selection |

263 

264### Plugin actions

265 

266Actions available in the `Plugin` context:

267 

268| Action | Default | Description |

269| :--------------- | :------ | :----------------------- |

270| `plugin:toggle` | Space | Toggle plugin selection |

271| `plugin:install` | I | Install selected plugins |

272 

273### Settings actions

274 

275Actions available in the `Settings` context:

276 

277| Action | Default | Description |

278| :---------------- | :------ | :---------------------------------- |

279| `settings:search` | / | Enter search mode |

280| `settings:retry` | R | Retry loading usage data (on error) |

281 

282## Keystroke syntax

283 

284### Modifiers

285 

286Use modifier keys with the `+` separator:

287 

288* `ctrl` or `control` - Control key

289* `alt`, `opt`, or `option` - Alt/Option key

290* `shift` - Shift key

291* `meta`, `cmd`, or `command` - Meta/Command key

292 

293For example:

294 

295```

296ctrl+k Single key with modifier

297shift+tab Shift + Tab

298meta+p Command/Meta + P

299ctrl+shift+c Multiple modifiers

300```

301 

302### Uppercase letters

303 

304A standalone uppercase letter implies Shift. For example, `K` is equivalent to `shift+k`. This is useful for vim-style bindings where uppercase and lowercase keys have different meanings.

305 

306Uppercase letters with modifiers (e.g., `ctrl+K`) are treated as stylistic and do **not** imply Shift — `ctrl+K` is the same as `ctrl+k`.

307 

308### Chords

309 

310Chords are sequences of keystrokes separated by spaces:

311 

312```

313ctrl+k ctrl+s Press Ctrl+K, release, then Ctrl+S

314```

315 

316### Special keys

317 

318* `escape` or `esc` - Escape key

319* `enter` or `return` - Enter key

320* `tab` - Tab key

321* `space` - Space bar

322* `up`, `down`, `left`, `right` - Arrow keys

323* `backspace`, `delete` - Delete keys

324 

325## Unbind default shortcuts

326 

327Set an action to `null` to unbind a default shortcut:

328 

329```json theme={null}

330{

331 "bindings": [

332 {

333 "context": "Chat",

334 "bindings": {

335 "ctrl+s": null

336 }

337 }

338 ]

339}

340```

341 

342## Reserved shortcuts

343 

344These shortcuts cannot be rebound:

345 

346| Shortcut | Reason |

347| :------- | :------------------------- |

348| Ctrl+C | Hardcoded interrupt/cancel |

349| Ctrl+D | Hardcoded exit |

350 

351## Terminal conflicts

352 

353Some shortcuts may conflict with terminal multiplexers:

354 

355| Shortcut | Conflict |

356| :------- | :-------------------------------- |

357| Ctrl+B | tmux prefix (press twice to send) |

358| Ctrl+A | GNU screen prefix |

359| Ctrl+Z | Unix process suspend (SIGTSTP) |

360 

361## Vim mode interaction

362 

363When vim mode is enabled (`/vim`), keybindings and vim mode operate independently:

364 

365* **Vim mode** handles input at the text input level (cursor movement, modes, motions)

366* **Keybindings** handle actions at the component level (toggle todos, submit, etc.)

367* The Escape key in vim mode switches INSERT to NORMAL mode; it does not trigger `chat:cancel`

368* Most Ctrl+key shortcuts pass through vim mode to the keybinding system

369* In vim NORMAL mode, `?` shows the help menu (vim behavior)

370 

371## Validation

372 

373Claude Code validates your keybindings and shows warnings for:

374 

375* Parse errors (invalid JSON or structure)

376* Invalid context names

377* Reserved shortcut conflicts

378* Terminal multiplexer conflicts

379* Duplicate bindings in the same context

380 

381Run `/doctor` to see any keybinding warnings.

llm-gateway.md +4 −0

Details

1> ## Documentation Index

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

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

4 

1# LLM gateway configuration5# LLM gateway configuration

2 6 

3> Learn how to configure Claude Code to work with LLM gateway solutions. Covers gateway requirements, authentication configuration, model selection, and provider-specific endpoint setup.7> Learn how to configure Claude Code to work with LLM gateway solutions. Covers gateway requirements, authentication configuration, model selection, and provider-specific endpoint setup.

mcp.md +326 −40

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

17 21 


77 81 

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

79# Basic syntax83# Basic syntax

80claude mcp add --transport stdio <name> <command> [args...]84claude mcp add [options] <name> -- <command> [args...]

81 85 

82# Real example: Add Airtable server86# Real example: Add Airtable server

83claude mcp add --transport stdio airtable --env AIRTABLE_API_KEY=YOUR_KEY \87claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \

84 -- npx -y airtable-mcp-server88 -- npx -y airtable-mcp-server

85```89```

86 90 

87<Note>91<Note>

88 **Understanding the "--" parameter:**92 **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.93 

94 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 95 

91 For example:96 For example:

92 97 

93 * `claude mcp add --transport stdio myserver -- npx server` → runs `npx server`98 * `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 environment99 * `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 100 

96 This prevents conflicts between Claude's flags and the server's flags.101 This prevents conflicts between Claude's flags and the server's flags.

97</Note>102</Note>


114/mcp119/mcp

115```120```

116 121 

122### Dynamic tool updates

123 

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

125 

117<Tip>126<Tip>

118 Tips:127 Tips:

119 128 


121 * `local` (default): Available only to you in the current project (was called `project` in older versions)130 * `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` file131 * `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)132 * `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`)133 * 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)134 * 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`)135 * 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 authentication136 * Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication

128</Tip>137</Tip>

129 138 


209 218 

210### Local scope219### Local scope

211 220 

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.221Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project's path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn't be shared.

222 

223<Note>

224 The term "local scope" for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](/en/settings#settings-files) for details on settings file locations.

225</Note>

213 226 

214```bash theme={null}227```bash theme={null}

215# Add a local-scoped server (default)228# Add a local-scoped server (default)


246 259 

247### User scope260### User scope

248 261 

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.262User-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 263 

251```bash theme={null}264```bash theme={null}

252# Add a user server265# Add a user server


259 272 

260* **Local scope**: Personal servers, experimental configurations, or sensitive credentials specific to one project273* **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 collaboration274* **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 services275* **User scope**: Personal utilities needed across multiple projects, development tools, or frequently used services

276 

277<Note>

278 **Where are MCP servers stored?**

279 

280 * **User and local scope**: `~/.claude.json` (in the `mcpServers` field or under project paths)

281 * **Project scope**: `.mcp.json` in your project root (checked into source control)

282 * **Managed**: `managed-mcp.json` in system directories (see [Managed MCP configuration](#managed-mcp-configuration))

283</Note>

263 284 

264### Scope hierarchy and precedence285### Scope hierarchy and precedence

265 286 


392 * OAuth authentication works with HTTP servers413 * OAuth authentication works with HTTP servers

393</Tip>414</Tip>

394 415 

416### Use pre-configured OAuth credentials

417 

418Some MCP servers don't support automatic OAuth setup. If you see an error like "Incompatible auth server: does not support dynamic client registration," the server requires pre-configured credentials. Register an OAuth app through the server's developer portal first, then provide the credentials when adding the server.

419 

420<Steps>

421 <Step title="Register an OAuth app with the server">

422 Create an app through the server's developer portal and note your client ID and client secret.

423 

424 Many servers also require a redirect URI. If so, choose a port and register a redirect URI in the format `http://localhost:PORT/callback`. Use that same port with `--callback-port` in the next step.

425 </Step>

426 

427 <Step title="Add the server with your credentials">

428 Choose one of the following methods. The port used for `--callback-port` can be any available port. It just needs to match the redirect URI you registered in the previous step.

429 

430 <Tabs>

431 <Tab title="claude mcp add">

432 Use `--client-id` to pass your app's client ID. The `--client-secret` flag prompts for the secret with masked input:

433 

434 ```bash theme={null}

435 claude mcp add --transport http \

436 --client-id your-client-id --client-secret --callback-port 8080 \

437 my-server https://mcp.example.com/mcp

438 ```

439 </Tab>

440 

441 <Tab title="claude mcp add-json">

442 Include the `oauth` object in the JSON config and pass `--client-secret` as a separate flag:

443 

444 ```bash theme={null}

445 claude mcp add-json my-server \

446 '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \

447 --client-secret

448 ```

449 </Tab>

450 

451 <Tab title="CI / env var">

452 Set the secret via environment variable to skip the interactive prompt:

453 

454 ```bash theme={null}

455 MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \

456 --client-id your-client-id --client-secret --callback-port 8080 \

457 my-server https://mcp.example.com/mcp

458 ```

459 </Tab>

460 </Tabs>

461 </Step>

462 

463 <Step title="Authenticate in Claude Code">

464 Run `/mcp` in Claude Code and follow the browser login flow.

465 </Step>

466</Steps>

467 

468<Tip>

469 Tips:

470 

471 * The client secret is stored securely in your system keychain (macOS) or a credentials file, not in your config

472 * If the server uses a public OAuth client with no secret, use only `--client-id` without `--client-secret`

473 * These flags only apply to HTTP and SSE transports. They have no effect on stdio servers

474 * Use `claude mcp get <name>` to verify that OAuth credentials are configured for a server

475</Tip>

476 

395## Add MCP servers from JSON configuration477## Add MCP servers from JSON configuration

396 478 

397If you have a JSON configuration for an MCP server, you can add it directly:479If you have a JSON configuration for an MCP server, you can add it directly:


407 489 

408 # Example: Adding a stdio server with JSON configuration490 # 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"}}'491 claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'

492 

493 # Example: Adding an HTTP server with pre-configured OAuth credentials

494 claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret

410 ```495 ```

411 </Step>496 </Step>

412 497 


455 * It reads the Claude Desktop configuration file from its standard location on those platforms540 * 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 configuration541 * Use the `--scope user` flag to add servers to your user configuration

457 * Imported servers will have the same names as in Claude Desktop542 * 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`)543 * If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)

459</Tip>544</Tip>

460 545 

461## Use Claude Code as an MCP server546## Use Claude Code as an MCP server


514 599 

515 * The server provides access to Claude's tools like View, Edit, LS, etc.600 * The server provides access to Claude's tools like View, Edit, LS, etc.

516 * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more.601 * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more.

517 * 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.602 * 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.

518</Tip>603</Tip>

519 604 

520## MCP output limits and warnings605## MCP output limits and warnings


584 * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.)669 * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.)

585</Tip>670</Tip>

586 671 

587## Use MCP prompts as slash commands672## Scale with MCP Tool Search

673 

674When you have many MCP servers configured, tool definitions can consume a significant portion of your context window. MCP Tool Search solves this by dynamically loading tools on-demand instead of preloading all of them.

675 

676### How it works

677 

678Claude Code automatically enables Tool Search when your MCP tool descriptions would consume more than 10% of the context window. You can [adjust this threshold](#configure-tool-search) or disable tool search entirely. When triggered:

679 

6801. MCP tools are deferred rather than loaded into context upfront

6812. Claude uses a search tool to discover relevant MCP tools when needed

6823. Only the tools Claude actually needs are loaded into context

6834. MCP tools continue to work exactly as before from your perspective

684 

685### For MCP server authors

686 

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

688 

689Add clear, descriptive server instructions that explain:

690 

691* What category of tasks your tools handle

692* When Claude should search for your tools

693* Key capabilities your server provides

694 

695### Configure tool search

696 

697Tool search runs in auto mode by default, meaning it activates only when your MCP tool definitions exceed the context threshold. If you have few tools, they load normally without tool search. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.

698 

699Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:

588 700 

589MCP servers can expose prompts that become available as slash commands in Claude Code.701| Value | Behavior |

702| :--------- | :--------------------------------------------------------------------------------- |

703| `auto` | Activates when MCP tools exceed 10% of context (default) |

704| `auto:<N>` | Activates at custom threshold, where `<N>` is a percentage (e.g., `auto:5` for 5%) |

705| `true` | Always enabled |

706| `false` | Disabled, all MCP tools loaded upfront |

707 

708```bash theme={null}

709# Use a custom 5% threshold

710ENABLE_TOOL_SEARCH=auto:5 claude

711 

712# Disable tool search entirely

713ENABLE_TOOL_SEARCH=false claude

714```

715 

716Or set the value in your [settings.json `env` field](/en/settings#available-settings).

717 

718You can also disable the MCPSearch tool specifically using the `disallowedTools` setting:

719 

720```json theme={null}

721{

722 "permissions": {

723 "deny": ["MCPSearch"]

724 }

725}

726```

727 

728## Use MCP prompts as commands

729 

730MCP servers can expose prompts that become available as commands in Claude Code.

590 731 

591### Execute MCP prompts732### Execute MCP prompts

592 733 


623 * Server and prompt names are normalized (spaces become underscores)764 * Server and prompt names are normalized (spaces become underscores)

624</Tip>765</Tip>

625 766 

626## Enterprise MCP configuration767## Managed MCP configuration

768 

769For organizations that need centralized control over MCP servers, Claude Code supports two configuration options:

770 

7711. **Exclusive control with `managed-mcp.json`**: Deploy a fixed set of MCP servers that users cannot modify or extend

7722. **Policy-based control with allowlists/denylists**: Allow users to add their own servers, but restrict which ones are permitted

627 773 

628For organizations that need centralized control over MCP servers, Claude Code supports enterprise-managed MCP configurations. This allows IT administrators to:774These options allow IT administrators to:

629 775 

630* **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization776* **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization

631* **Prevent unauthorized MCP servers**: Optionally restrict users from adding their own MCP servers777* **Prevent unauthorized MCP servers**: Restrict users from adding unapproved MCP servers

632* **Disable MCP entirely**: Remove MCP functionality completely if needed778* **Disable MCP entirely**: Remove MCP functionality completely if needed

633 779 

634### Setting up enterprise MCP configuration780### Option 1: Exclusive control with managed-mcp.json

635 781 

636System administrators can deploy an enterprise MCP configuration file alongside the managed settings file:782When 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.

637 783 

638* **macOS**: `/Library/Application Support/ClaudeCode/managed-mcp.json`784System administrators deploy the configuration file to a system-wide directory:

639* **Windows**: `C:\ProgramData\ClaudeCode\managed-mcp.json`785 

640* **Linux**: `/etc/claude-code/managed-mcp.json`786* macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`

787* Linux and WSL: `/etc/claude-code/managed-mcp.json`

788* Windows: `C:\Program Files\ClaudeCode\managed-mcp.json`

789 

790<Note>

791 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.

792</Note>

641 793 

642The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file:794The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file:

643 795 


664}816}

665```817```

666 818 

667### Restricting MCP servers with allowlists and denylists819### Option 2: Policy-based control with allowlists and denylists

820 

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

822 

823<Note>

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

825</Note>

826 

827#### Restriction options

668 828 

669In 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:829Each entry in the allowlist or denylist can restrict servers in three ways:

670 830 

671* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`8311. **By server name** (`serverName`): Matches the configured name of the server

672* **Windows**: `C:\ProgramData\ClaudeCode\managed-settings.json`8322. **By command** (`serverCommand`): Matches the exact command and arguments used to start stdio servers

673* **Linux**: `/etc/claude-code/managed-settings.json`8333. **By URL pattern** (`serverUrl`): Matches remote server URLs with wildcard support

834 

835**Important**: Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`.

836 

837#### Example configuration

674 838 

675```json theme={null}839```json theme={null}

676{840{

677 "allowedMcpServers": [841 "allowedMcpServers": [

842 // Allow by server name

678 { "serverName": "github" },843 { "serverName": "github" },

679 { "serverName": "sentry" },844 { "serverName": "sentry" },

680 { "serverName": "company-internal" }845 

846 // Allow by exact command (for stdio servers)

847 { "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },

848 { "serverCommand": ["python", "/usr/local/bin/approved-server.py"] },

849 

850 // Allow by URL pattern (for remote servers)

851 { "serverUrl": "https://mcp.company.com/*" },

852 { "serverUrl": "https://*.internal.corp/*" }

681 ],853 ],

682 "deniedMcpServers": [854 "deniedMcpServers": [

683 { "serverName": "filesystem" }855 // Block by server name

856 { "serverName": "dangerous-server" },

857 

858 // Block by exact command (for stdio servers)

859 { "serverCommand": ["npx", "-y", "unapproved-package"] },

860 

861 // Block by URL pattern (for remote servers)

862 { "serverUrl": "https://*.untrusted.com/*" }

684 ]863 ]

685}864}

686```865```

687 866 

688**Allowlist behavior (`allowedMcpServers`)**:867#### How command-based restrictions work

868 

869**Exact matching**:

870 

871* Command arrays must match **exactly** - both the command and all arguments in the correct order

872* Example: `["npx", "-y", "server"]` will NOT match `["npx", "server"]` or `["npx", "-y", "server", "--flag"]`

873 

874**Stdio server behavior**:

875 

876* When the allowlist contains **any** `serverCommand` entries, stdio servers **must** match one of those commands

877* Stdio servers cannot pass by name alone when command restrictions are present

878* This ensures administrators can enforce which commands are allowed to run

879 

880**Non-stdio server behavior**:

881 

882* Remote servers (HTTP, SSE, WebSocket) use URL-based matching when `serverUrl` entries exist in the allowlist

883* If no URL entries exist, remote servers fall back to name-based matching

884* Command restrictions do not apply to remote servers

885 

886#### How URL-based restrictions work

887 

888URL patterns support wildcards using `*` to match any sequence of characters. This is useful for allowing entire domains or subdomains.

889 

890**Wildcard examples**:

891 

892* `https://mcp.company.com/*` - Allow all paths on a specific domain

893* `https://*.example.com/*` - Allow any subdomain of example.com

894* `http://localhost:*/*` - Allow any port on localhost

895 

896**Remote server behavior**:

897 

898* When the allowlist contains **any** `serverUrl` entries, remote servers **must** match one of those URL patterns

899* Remote servers cannot pass by name alone when URL restrictions are present

900* This ensures administrators can enforce which remote endpoints are allowed

901 

902<Accordion title="Example: URL-only allowlist">

903 ```json theme={null}

904 {

905 "allowedMcpServers": [

906 { "serverUrl": "https://mcp.company.com/*" },

907 { "serverUrl": "https://*.internal.corp/*" }

908 ]

909 }

910 ```

911 

912 **Result**:

913 

914 * HTTP server at `https://mcp.company.com/api`: ✅ Allowed (matches URL pattern)

915 * HTTP server at `https://api.internal.corp/mcp`: ✅ Allowed (matches wildcard subdomain)

916 * HTTP server at `https://external.com/mcp`: ❌ Blocked (doesn't match any URL pattern)

917 * Stdio server with any command: ❌ Blocked (no name or command entries to match)

918</Accordion>

919 

920<Accordion title="Example: Command-only allowlist">

921 ```json theme={null}

922 {

923 "allowedMcpServers": [

924 { "serverCommand": ["npx", "-y", "approved-package"] }

925 ]

926 }

927 ```

928 

929 **Result**:

930 

931 * Stdio server with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command)

932 * Stdio server with `["node", "server.js"]`: ❌ Blocked (doesn't match command)

933 * HTTP server named "my-api": ❌ Blocked (no name entries to match)

934</Accordion>

935 

936<Accordion title="Example: Mixed name and command allowlist">

937 ```json theme={null}

938 {

939 "allowedMcpServers": [

940 { "serverName": "github" },

941 { "serverCommand": ["npx", "-y", "approved-package"] }

942 ]

943 }

944 ```

945 

946 **Result**:

947 

948 * Stdio server named "local-tool" with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command)

949 * Stdio server named "local-tool" with `["node", "server.js"]`: ❌ Blocked (command entries exist but doesn't match)

950 * Stdio server named "github" with `["node", "server.js"]`: ❌ Blocked (stdio servers must match commands when command entries exist)

951 * HTTP server named "github": ✅ Allowed (matches name)

952 * HTTP server named "other-api": ❌ Blocked (name doesn't match)

953</Accordion>

954 

955<Accordion title="Example: Name-only allowlist">

956 ```json theme={null}

957 {

958 "allowedMcpServers": [

959 { "serverName": "github" },

960 { "serverName": "internal-tool" }

961 ]

962 }

963 ```

964 

965 **Result**:

966 

967 * Stdio server named "github" with any command: ✅ Allowed (no command restrictions)

968 * Stdio server named "internal-tool" with any command: ✅ Allowed (no command restrictions)

969 * HTTP server named "github": ✅ Allowed (matches name)

970 * Any server named "other": ❌ Blocked (name doesn't match)

971</Accordion>

972 

973#### Allowlist behavior (`allowedMcpServers`)

689 974 

690* `undefined` (default): No restrictions - users can configure any MCP server975* `undefined` (default): No restrictions - users can configure any MCP server

691* Empty array `[]`: Complete lockdown - users cannot configure any MCP servers976* Empty array `[]`: Complete lockdown - users cannot configure any MCP servers

692* List of server names: Users can only configure the specified servers977* List of entries: Users can only configure servers that match by name, command, or URL pattern

693 978 

694**Denylist behavior (`deniedMcpServers`)**:979#### Denylist behavior (`deniedMcpServers`)

695 980 

696* `undefined` (default): No servers are blocked981* `undefined` (default): No servers are blocked

697* Empty array `[]`: No servers are blocked982* Empty array `[]`: No servers are blocked

698* List of server names: Specified servers are explicitly blocked across all scopes983* List of entries: Specified servers are explicitly blocked across all scopes

699 984 

700**Important notes**:985#### Important notes

701 986 

702* These restrictions apply to all scopes: user, project, local, and even enterprise servers from `managed-mcp.json`987* **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.

703* **Denylist takes absolute precedence**: If a server appears in both lists, it will be blocked988* **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

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

704 990 

705<Note>991<Note>

706 **Enterprise configuration precedence**: The enterprise MCP configuration has the highest precedence and cannot be overridden by user, local, or project configurations.992 **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.

707</Note>993</Note>

memory.md +216 −20

Details

1> ## Documentation Index

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

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

4 

1# Manage Claude's memory5# Manage Claude's memory

2 6 

3> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.7> Learn how to manage Claude Code's memory across sessions with different memory locations and best practices.

4 8 

5Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow.9Claude Code has two kinds of memory that persist across sessions:

10 

11* **Auto memory**: Claude automatically saves useful context like project patterns, key commands, and your preferences. This persists across sessions.

12* **CLAUDE.md files**: Markdown files you write and maintain with instructions, rules, and preferences for Claude to follow.

13 

14Both are loaded into Claude's context at the start of every session, though auto memory loads only the first 200 lines of its main file.

6 15 

7## Determine memory type16## Determine memory type

8 17 

9Claude Code offers four memory locations in a hierarchical structure, each serving a different purpose:18Claude Code offers several memory locations in a hierarchical structure, each serving a different purpose:

10 19 

11| Memory Type | Location | Purpose | Use Case Examples | Shared With |20| Memory Type | Location | Purpose | Use Case Examples | Shared With |

12| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |21| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------- |

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 |22| **Managed policy** | macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`<br />Linux: `/etc/claude-code/CLAUDE.md`<br />Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |

14| **Project memory** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |23| **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 |

24| **Project rules** | `./.claude/rules/*.md` | Modular, topic-specific project instructions | Language-specific guidelines, testing conventions, API standards | 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) |25| **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) |26| **Project memory (local)** | `./CLAUDE.local.md` | Personal project-specific preferences | Your sandbox URLs, preferred test data | Just you (current project) |

27| **Auto memory** | `~/.claude/projects/<project>/memory/` | Claude's automatic notes and learnings | Project patterns, debugging insights, architecture notes | Just you (per project) |

28 

29CLAUDE.md files in the directory hierarchy above the working directory are loaded in full at launch. CLAUDE.md files in child directories load on demand when Claude reads files in those directories. Auto memory loads only the first 200 lines of `MEMORY.md`. More specific instructions take precedence over broader ones.

30 

31<Note>

32 CLAUDE.local.md files are automatically added to .gitignore, making them ideal for private project-specific preferences that shouldn't be checked into version control.

33</Note>

34 

35## Auto memory

36 

37Auto memory is a persistent directory where Claude records learnings, patterns, and insights as it works. Unlike CLAUDE.md files that contain instructions you write for Claude, auto memory contains notes Claude writes for itself based on what it discovers during sessions.

38 

39<Note>

40 Auto memory is being rolled out gradually. If you aren't seeing auto memory, you can opt in by setting `CLAUDE_CODE_DISABLE_AUTO_MEMORY=0` in your environment.

41</Note>

42 

43### What Claude remembers

44 

45As Claude works, it may save things like:

46 

47* Project patterns: build commands, test conventions, code style preferences

48* Debugging insights: solutions to tricky problems, common error causes

49* Architecture notes: key files, module relationships, important abstractions

50* Your preferences: communication style, workflow habits, tool choices

51 

52### Where auto memory is stored

53 

54Each project gets its own memory directory at `~/.claude/projects/<project>/memory/`. The `<project>` path is derived from the git repository root, so all subdirectories within the same repo share one auto memory directory. Git worktrees get separate memory directories. Outside a git repo, the working directory is used instead.

55 

56The directory contains a `MEMORY.md` entrypoint and optional topic files:

57 

58```text theme={null}

59~/.claude/projects/<project>/memory/

60├── MEMORY.md # Concise index, loaded into every session

61├── debugging.md # Detailed notes on debugging patterns

62├── api-conventions.md # API design decisions

63└── ... # Any other topic files Claude creates

64```

65 

66`MEMORY.md` acts as an index of the memory directory. Claude reads and writes files in this directory throughout your session, using `MEMORY.md` to keep track of what's stored where.

67 

68### How it works

69 

70* The first 200 lines of `MEMORY.md` are loaded into Claude's system prompt at the start of every session. Content beyond 200 lines is not loaded automatically, and Claude is instructed to keep it concise by moving detailed notes into separate topic files.

71* Topic files like `debugging.md` or `patterns.md` are not loaded at startup. Claude reads them on demand using its standard file tools when it needs the information.

72* Claude reads and writes memory files during your session, so you'll see memory updates happen as you work.

73 

74### Manage auto memory

17 75 

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.76Auto memory files are markdown files you can edit at any time. Use `/memory` to open the file selector, which includes your auto memory entrypoint alongside your CLAUDE.md files.

77 

78To ask Claude to save something specific, tell it directly: "remember that we use pnpm, not npm" or "save to memory that the API tests require a local Redis instance".

79 

80When neither variable is set, auto memory follows the gradual rollout. The variable name uses double-negative logic: `DISABLE=0` means "don't disable" and forces auto memory on.

81 

82```bash theme={null}

83export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 # Force off

84export CLAUDE_CODE_DISABLE_AUTO_MEMORY=0 # Force on

85```

19 86 

20## CLAUDE.md imports87## CLAUDE.md imports

21 88 


28- git workflow @docs/git-instructions.md95- git workflow @docs/git-instructions.md

29```96```

30 97 

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.98Both relative and absolute paths are allowed. Relative paths resolve relative to the file containing the import, not the working directory. For private per-project preferences that shouldn't be checked into version control, prefer `CLAUDE.local.md`: it is automatically loaded and added to `.gitignore`.

99 

100If you work across multiple git worktrees, `CLAUDE.local.md` only exists in one. Use a home-directory import instead so all worktrees share the same personal instructions:

32 101 

33```102```

34# Individual Preferences103# Individual Preferences

35- @~/.claude/my-project-instructions.md104- @~/.claude/my-project-instructions.md

36```105```

37 106 

107<Warning>

108 The first time Claude Code encounters external imports in a project, it shows an approval dialog listing the specific files. Approve to load them; decline to skip them. This is a one-time decision per project: once declined, the dialog does not resurface and the imports remain disabled.

109</Warning>

110 

38To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.111To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.

39 112 

40```113```


49 122 

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.123Claude will also discover CLAUDE.md nested in subtrees under your current working directory. Instead of loading them at launch, they are only included when Claude reads files in those subtrees.

51 124 

52## Quickly add memories with the `#` shortcut125### Load memory from additional directories

53 126 

54The fastest way to add a memory is to start your input with the `#` character:127The `--add-dir` flag gives Claude access to additional directories outside your main working directory. By default, CLAUDE.md files from these directories are not loaded.

55 128 

56```129To also load memory files (CLAUDE.md, .claude/CLAUDE.md, and .claude/rules/\*.md) from additional directories, set the `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable:

57# Always use descriptive variable names

58```

59 130 

60You'll be prompted to select which memory file to store this in.131```bash theme={null}

132CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config

133```

61 134 

62## Directly edit memories with `/memory`135## Directly edit memories with `/memory`

63 136 

64Use the `/memory` slash command during a session to open any memory file in your system editor for more extensive additions or organization.137Use the `/memory` command during a session to open any memory file in your system editor for more extensive additions or organization.

65 138 

66## Set up project memory139## Set up project memory

67 140 


82 * CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences.155 * CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences.

83</Tip>156</Tip>

84 157 

158## Modular rules with `.claude/rules/`

159 

160For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This allows teams to maintain focused, well-organized rule files instead of one large CLAUDE.md.

161 

162### Basic structure

163 

164Place markdown files in your project's `.claude/rules/` directory:

165 

166```

167your-project/

168├── .claude/

169│ ├── CLAUDE.md # Main project instructions

170│ └── rules/

171│ ├── code-style.md # Code style guidelines

172│ ├── testing.md # Testing conventions

173│ └── security.md # Security requirements

174```

175 

176All `.md` files in `.claude/rules/` are automatically loaded as project memory, with the same priority as `.claude/CLAUDE.md`.

177 

178### Path-specific rules

179 

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

181 

182```markdown theme={null}

183---

184paths:

185 - "src/api/**/*.ts"

186---

187 

188# API Development Rules

189 

190- All API endpoints must include input validation

191- Use the standard error response format

192- Include OpenAPI documentation comments

193```

194 

195Rules without a `paths` field are loaded unconditionally and apply to all files.

196 

197### Glob patterns

198 

199The `paths` field supports standard glob patterns:

200 

201| Pattern | Matches |

202| ---------------------- | ---------------------------------------- |

203| `**/*.ts` | All TypeScript files in any directory |

204| `src/**/*` | All files under `src/` directory |

205| `*.md` | Markdown files in the project root |

206| `src/components/*.tsx` | React components in a specific directory |

207 

208You can specify multiple patterns:

209 

210```markdown theme={null}

211---

212paths:

213 - "src/**/*.ts"

214 - "lib/**/*.ts"

215 - "tests/**/*.test.ts"

216---

217```

218 

219Brace expansion is supported for matching multiple extensions or directories:

220 

221```markdown theme={null}

222---

223paths:

224 - "src/**/*.{ts,tsx}"

225 - "{src,lib}/**/*.ts"

226---

227 

228# TypeScript/React Rules

229```

230 

231This expands `src/**/*.{ts,tsx}` to match both `.ts` and `.tsx` files.

232 

233### Subdirectories

234 

235Rules can be organized into subdirectories for better structure:

236 

237```

238.claude/rules/

239├── frontend/

240│ ├── react.md

241│ └── styles.md

242├── backend/

243│ ├── api.md

244│ └── database.md

245└── general.md

246```

247 

248All `.md` files are discovered recursively.

249 

250### Symlinks

251 

252The `.claude/rules/` directory supports symlinks, allowing you to share common rules across multiple projects:

253 

254```bash theme={null}

255# Symlink a shared rules directory

256ln -s ~/shared-claude-rules .claude/rules/shared

257 

258# Symlink individual rule files

259ln -s ~/company-standards/security.md .claude/rules/security.md

260```

261 

262Symlinks are resolved and their contents are loaded normally. Circular symlinks are detected and handled gracefully.

263 

264### User-level rules

265 

266You can create personal rules that apply to all your projects in `~/.claude/rules/`:

267 

268```

269~/.claude/rules/

270├── preferences.md # Your personal coding preferences

271└── workflows.md # Your preferred workflows

272```

273 

274User-level rules are loaded before project rules, giving project rules higher priority.

275 

276<Tip>

277 Best practices for `.claude/rules/`:

278 

279 * **Keep rules focused**: Each file should cover one topic (e.g., `testing.md`, `api-design.md`)

280 * **Use descriptive filenames**: The filename should indicate what the rules cover

281 * **Use conditional rules sparingly**: Only add `paths` frontmatter when rules truly apply to specific file types

282 * **Organize with subdirectories**: Group related rules (e.g., `frontend/`, `backend/`)

283</Tip>

284 

85## Organization-level memory management285## Organization-level memory management

86 286 

87Enterprise organizations can deploy centrally managed CLAUDE.md files that apply to all users.287Organizations can deploy centrally managed CLAUDE.md files that apply to all users.

88 288 

89To set up organization-level memory management:289To set up organization-level memory management:

90 290 

911. Create the enterprise memory file in the appropriate location for your operating system:2911. Create the managed memory file at the **Managed policy** location shown in the [memory types table above](#determine-memory-type).

92 

93* macOS: `/Library/Application Support/ClaudeCode/CLAUDE.md`

94* Linux/WSL: `/etc/claude-code/CLAUDE.md`

95* Windows: `C:\ProgramData\ClaudeCode\CLAUDE.md`

96 292 

972. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines.2932. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines.

98 294 

microsoft-foundry.md +23 −19 renamed

Details

Previously: azure-ai-foundry.md

1# Claude Code on Azure AI Foundry1> ## 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 configuring Claude Code through Azure AI Foundry, including setup, configuration, and troubleshooting.5# Claude Code on Microsoft Foundry

6 

7> Learn about configuring Claude Code through Microsoft Foundry, including setup, configuration, and troubleshooting.

4 8 

5## Prerequisites9## Prerequisites

6 10 

7Before configuring Claude Code with Azure AI Foundry, ensure you have:11Before configuring Claude Code with Microsoft Foundry, ensure you have:

8 12 

9* An Azure subscription with access to Azure AI Foundry13* An Azure subscription with access to Microsoft Foundry

10* RBAC permissions to create Azure AI Foundry resources and deployments14* RBAC permissions to create Microsoft Foundry resources and deployments

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

12 16 

13## Setup17## Setup

14 18 

15### 1. Provision Azure AI Foundry resource19### 1. Provision Microsoft Foundry resource

16 20 

17First, create a Claude resource in Azure:21First, create a Claude resource in Azure:

18 22 

191. Navigate to the [Azure AI Foundry portal](https://ai.azure.com/)231. Navigate to the [Microsoft Foundry portal](https://ai.azure.com/)

202. Create a new resource, noting your resource name242. Create a new resource, noting your resource name

213. Create deployments for the Claude models:253. Create deployments for the Claude models:

22 * Claude Opus26 * Claude Opus


25 29 

26### 2. Configure Azure credentials30### 2. Configure Azure credentials

27 31 

28Claude Code supports two authentication methods for Azure AI Foundry. Choose the method that best fits your security requirements.32Claude Code supports two authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements.

29 33 

30**Option A: API key authentication**34**Option A: API key authentication**

31 35 

321. Navigate to your resource in the Azure AI Foundry portal361. Navigate to your resource in the Microsoft Foundry portal

332. Go to the **Endpoints and keys** section372. Go to the **Endpoints and keys** section

343. Copy **API Key**383. Copy **API Key**

354. Set the environment variable:394. Set the environment variable:


50```54```

51 55 

52<Note>56<Note>

53 When using AI Foundry, the `/login` and `/logout` commands are disabled since authentication is handled through Azure credentials.57 When using Microsoft Foundry, the `/login` and `/logout` commands are disabled since authentication is handled through Azure credentials.

54</Note>58</Note>

55 59 

56### 3. Configure Claude Code60### 3. Configure Claude Code

57 61 

58Set the following environment variables to enable Azure AI Foundry. Note that your deployments' names are set as the model identifiers in Claude Code (may be optional if using suggested deployment names).62Set the following environment variables to enable Microsoft Foundry. Note that your deployments' names are set as the model identifiers in Claude Code (may be optional if using suggested deployment names).

59 63 

60```bash theme={null}64```bash theme={null}

61# Enable Azure AI Foundry integration65# Enable Microsoft Foundry integration

62export CLAUDE_CODE_USE_FOUNDRY=166export CLAUDE_CODE_USE_FOUNDRY=1

63 67 

64# Azure resource name (replace {resource} with your resource name)68# Azure resource name (replace {resource} with your resource name)

65export ANTHROPIC_FOUNDRY_RESOURCE={resource}69export ANTHROPIC_FOUNDRY_RESOURCE={resource}

66# Or provide the full base URL:70# Or provide the full base URL:

67# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com71# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com/anthropic

68 72 

69# Set models to your resource's deployment names73# Set models to your resource's deployment names

70export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-5'74export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-5'

71export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'75export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'

72export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-1'76export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-6'

73```77```

74 78 

75For more details on model configuration options, see [Model configuration](/en/model-config).79For more details on model configuration options, see [Model configuration](/en/model-config).


92}96}

93```97```

94 98 

95For details, see [Azure AI Foundry RBAC documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry).99For details, see [Microsoft Foundry RBAC documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry).

96 100 

97## Troubleshooting101## Troubleshooting

98 102 


102 106 

103## Additional resources107## Additional resources

104 108 

105* [AI Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)109* [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)

106* [AI Foundry models](https://ai.azure.com/explore/models)110* [Microsoft Foundry models](https://ai.azure.com/explore/models)

107* [AI Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)111* [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)

model-config.md +46 −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# Model configuration5# Model configuration

2 6 

3> Learn about the Claude Code model configuration, including model aliases like `opusplan`7> Learn about the Claude Code model configuration, including model aliases like `opusplan`


8 12 

9* A **model alias**13* A **model alias**

10* A **model name**14* A **model name**

11 * Anthropic API: A full **[model name](https://docs.claude.com/en/docs/about-claude/models/overview#model-names)**15 * Anthropic API: A full **[model name](https://platform.claude.com/docs/en/about-claude/models/overview)**

12 * Bedrock: an inference profile ARN16 * Bedrock: an inference profile ARN

13 * Foundry: a deployment name17 * Foundry: a deployment name

14 * Vertex: a version name18 * Vertex: a version name


19remembering exact version numbers:23remembering exact version numbers:

20 24 

21| Model alias | Behavior |25| Model alias | Behavior |

22| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |26| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

23| **`default`** | Recommended model setting, depending on your account type |27| **`default`** | Recommended model setting, depending on your account type |

24| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.5) for daily coding tasks |28| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.5) for daily coding tasks |

25| **`opus`** | Uses Opus model (currently Opus 4.1) for specialized complex reasoning tasks |29| **`opus`** | Uses the latest Opus model (currently Opus 4.6) for complex reasoning tasks |

26| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |30| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |

27| **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) window for long sessions |31| **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions |

28| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |32| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |

29 33 

34Aliases always point to the latest version. To pin to a specific version, use the full model name (for example, `claude-opus-4-6`) or set the corresponding environment variable like `ANTHROPIC_DEFAULT_OPUS_MODEL`.

35 

30### Setting your model36### Setting your model

31 37 

32You can configure your model in several ways, listed in order of priority:38You can configure your model in several ways, listed in order of priority:


62 68 

63### `default` model setting69### `default` model setting

64 70 

65The behavior of `default` depends on your account type.71The behavior of `default` depends on your account type:

72 

73* **Max and Teams**: defaults to Opus 4.6

74* **Pro**: defaults to Opus 4.6 in Claude Code

75* **Enterprise**: Opus 4.6 is available but not the default

66 76 

67For certain Max users, Claude Code will automatically fall back to Sonnet if you77Claude Code may automatically fall back to Sonnet if you hit a usage threshold with Opus.

68hit a usage threshold with Opus.

69 78 

70### `opusplan` model setting79### `opusplan` model setting

71 80 


79This gives you the best of both worlds: Opus's superior reasoning for planning,88This gives you the best of both worlds: Opus's superior reasoning for planning,

80and Sonnet's efficiency for execution.89and Sonnet's efficiency for execution.

81 90 

91### Adjust effort level

92 

93[Effort levels](https://platform.claude.com/docs/en/build-with-claude/effort) control Opus 4.6's adaptive reasoning, which dynamically allocates thinking based on task complexity. Lower effort is faster and cheaper for straightforward tasks, while higher effort provides deeper reasoning for complex problems.

94 

95Three levels are available: **low**, **medium**, and **high** (default).

96 

97**Setting effort:**

98 

99* **In `/model`**: use left/right arrow keys to adjust the effort slider when selecting a model

100* **Environment variable**: set `CLAUDE_CODE_EFFORT_LEVEL=low|medium|high`

101* **Settings**: set `effortLevel` in your settings file

102 

103Effort is currently supported on Opus 4.6. The effort slider appears in `/model` when a supported model is selected.

104 

82### Extended context with \[1m]105### Extended context with \[1m]

83 106 

84For Console/API users, the `[1m]` suffix can be added to full model names to107The `[1m]` suffix enables a [1 million token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows#1m-token-context-window) for long sessions.

85enable a108 

86[1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window).109<Note>

110 For Opus 4.6, the 1M context window is available for API and Claude Code pay-as-you-go users. Pro, Max, Teams, and Enterprise subscription users do not have access to Opus 4.6 1M context at launch.

111</Note>

112 

113You can use the `[1m]` suffix with model aliases or full model names:

87 114 

88```bash theme={null}115```bash theme={null}

89# Example of using a full model name with the [1m] suffix116# Use the sonnet[1m] alias

90/model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]117/model sonnet[1m]

118 

119# Or append [1m] to a full model name

120/model claude-sonnet-4-5-20250929[1m]

91```121```

92 122 

93Note: Extended context models have123Note: Extended context models have

94[different pricing](https://docs.claude.com/en/docs/about-claude/pricing#long-context-pricing).124[different pricing](https://platform.claude.com/docs/en/about-claude/pricing#long-context-pricing).

95 125 

96## Checking your current model126## Checking your current model

97 127 


105You can use the following environment variables, which must be full **model135You can use the following environment variables, which must be full **model

106names** (or equivalent for your API provider), to control the model names that the aliases map to.136names** (or equivalent for your API provider), to control the model names that the aliases map to.

107 137 

108| Env var | Description |138| Environment variable | Description |

109| -------------------------------- | --------------------------------------------------------------------------------------------- |139| -------------------------------- | --------------------------------------------------------------------------------------------- |

110| `ANTHROPIC_DEFAULT_OPUS_MODEL` | The model to use for `opus`, or for `opusplan` when Plan Mode is active. |140| `ANTHROPIC_DEFAULT_OPUS_MODEL` | The model to use for `opus`, or for `opusplan` when Plan Mode is active. |

111| `ANTHROPIC_DEFAULT_SONNET_MODEL` | The model to use for `sonnet`, or for `opusplan` when Plan Mode is not active. |141| `ANTHROPIC_DEFAULT_SONNET_MODEL` | The model to use for `sonnet`, or for `opusplan` when Plan Mode is not active. |


117 147 

118### Prompt caching configuration148### Prompt caching configuration

119 149 

120Claude Code automatically uses [prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:150Claude Code automatically uses [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:

121 151 

122| Env var | Description |152| Environment variable | Description |

123| ------------------------------- | ---------------------------------------------------------------------------------------------- |153| ------------------------------- | ---------------------------------------------------------------------------------------------- |

124| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |154| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |

125| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only |155| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only |

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.


6 10 

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.11All 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 12 

9## Quick Start13## Quick start

10 14 

11Configure OpenTelemetry using environment variables:15Configure OpenTelemetry using environment variables:

12 16 


39 43 

40For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).44For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).

41 45 

42## Administrator Configuration46## Administrator configuration

43 

44Administrators 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/settings#settings-precedence) for more information about how settings are applied.

45 47 

46The managed settings file is located at:48Administrators 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.

47 

48* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`

49* Linux and WSL: `/etc/claude-code/managed-settings.json`

50* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`

51 49 

52Example managed settings configuration:50Example managed settings configuration:

53 51 


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

69</Note>67</Note>

70 68 

71## Configuration Details69## Configuration details

72 70 

73### Common Configuration Variables71### Common configuration variables

74 72 

75| Environment Variable | Description | Example Values |73| Environment Variable | Description | Example Values |

76| ----------------------------------------------- | --------------------------------------------------------- | ------------------------------------ |74| ----------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------ |

77| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |75| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |

78| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |76| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |

79| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |77| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |


89| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |87| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |

90| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |88| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |

91| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |89| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |

90| `OTEL_LOG_TOOL_DETAILS` | Enable logging of MCP server/tool names and skill names in tool events (default: disabled) | `1` to enable |

91| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |

92 92 

93### Metrics Cardinality Control93### Metrics cardinality control

94 94 

95The 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:

96 96 


102 102 

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

104 104 

105### Dynamic Headers105### Dynamic headers

106 106 

107For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:107For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:

108 108 

109#### Settings Configuration109#### Settings configuration

110 110 

111Add to your `.claude/settings.json`:111Add to your `.claude/settings.json`:

112 112 


116}116}

117```117```

118 118 

119#### Script Requirements119#### Script requirements

120 120 

121The script must output valid JSON with string key-value pairs representing HTTP headers:121The script must output valid JSON with string key-value pairs representing HTTP headers:

122 122 


126echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"126echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"

127```127```

128 128 

129#### Important Limitations129#### Refresh behavior

130 

131**Headers are fetched only at startup, not during runtime.** This is due to OpenTelemetry exporter architecture limitations.

132 130 

133For scenarios requiring frequent token refresh, use an OpenTelemetry Collector as a proxy that can refresh its own headers.131The 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.

134 132 

135### Multi-Team Organization Support133### Multi-team organization support

136 134 

137Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:135Organizations with multiple teams or departments can add custom attributes to distinguish between different groups using the `OTEL_RESOURCE_ATTRIBUTES` environment variable:

138 136 


172 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"170 export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"

173 ```171 ```

174 172 

175 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.173 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`.

176</Warning>174</Warning>

177 175 

178### Example Configurations176### Example configurations

179 177 

180```bash theme={null}178```bash theme={null}

181# Console debugging (1-second intervals)179# Console debugging (1-second intervals)


220export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317218export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

221```219```

222 220 

223## Available Metrics and Events221## Available metrics and events

224 222 

225### Standard Attributes223### Standard attributes

226 224 

227All metrics and events share these standard attributes:225All metrics and events share these standard attributes:

228 226 

229| Attribute | Description | Controlled By |227| Attribute | Description | Controlled By |

230| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |228| ------------------- | -------------------------------------------------------------------- | --------------------------------------------------- |

231| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |229| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |

232| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |230| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |

233| `organization.id` | Organization UUID (when authenticated) | Always included when available |231| `organization.id` | Organization UUID (when authenticated) | Always included when available |

234| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |232| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |

235| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |233| `terminal.type` | Terminal type (for example, `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |

236 234 

237### Metrics235### Metrics

238 236 


249| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |247| `claude_code.code_edit_tool.decision` | Count of code editing tool permission decisions | count |

250| `claude_code.active_time.total` | Total active time in seconds | s |248| `claude_code.active_time.total` | Total active time in seconds | s |

251 249 

252### Metric Details250### Metric details

253 251 

254#### Session Counter252#### Session counter

255 253 

256Incremented at the start of each session.254Incremented at the start of each session.

257 255 


259 257 

260* All [standard attributes](#standard-attributes)258* All [standard attributes](#standard-attributes)

261 259 

262#### Lines of Code Counter260#### Lines of code counter

263 261 

264Incremented when code is added or removed.262Incremented when code is added or removed.

265 263 


268* All [standard attributes](#standard-attributes)266* All [standard attributes](#standard-attributes)

269* `type`: (`"added"`, `"removed"`)267* `type`: (`"added"`, `"removed"`)

270 268 

271#### Pull Request Counter269#### Pull request counter

272 270 

273Incremented when creating pull requests via Claude Code.271Incremented when creating pull requests via Claude Code.

274 272 


276 274 

277* All [standard attributes](#standard-attributes)275* All [standard attributes](#standard-attributes)

278 276 

279#### Commit Counter277#### Commit counter

280 278 

281Incremented when creating git commits via Claude Code.279Incremented when creating git commits via Claude Code.

282 280 


284 282 

285* All [standard attributes](#standard-attributes)283* All [standard attributes](#standard-attributes)

286 284 

287#### Cost Counter285#### Cost counter

288 286 

289Incremented after each API request.287Incremented after each API request.

290 288 

291**Attributes**:289**Attributes**:

292 290 

293* All [standard attributes](#standard-attributes)291* All [standard attributes](#standard-attributes)

294* `model`: Model identifier (e.g., "claude-sonnet-4-5-20250929")292* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929")

295 293 

296#### Token Counter294#### Token counter

297 295 

298Incremented after each API request.296Incremented after each API request.

299 297 


301 299 

302* All [standard attributes](#standard-attributes)300* All [standard attributes](#standard-attributes)

303* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)301* `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)

304* `model`: Model identifier (e.g., "claude-sonnet-4-5-20250929")302* `model`: Model identifier (for example, "claude-sonnet-4-5-20250929")

305 303 

306#### Code Edit Tool Decision Counter304#### Code edit tool decision counter

307 305 

308Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.306Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.

309 307 


312* All [standard attributes](#standard-attributes)310* All [standard attributes](#standard-attributes)

313* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)311* `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)

314* `decision`: User decision (`"accept"`, `"reject"`)312* `decision`: User decision (`"accept"`, `"reject"`)

315* `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.313* `language`: Programming language of the edited file (for example, `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.

316 314 

317#### Active Time Counter315#### Active time counter

318 316 

319Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.317Tracks actual time spent actively using Claude Code (not idle time). This metric is incremented during user interactions such as typing prompts or receiving responses.

320 318 


326 324 

327Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):325Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):

328 326 

329#### User Prompt Event327#### User prompt event

330 328 

331Logged when a user submits a prompt.329Logged when a user submits a prompt.

332 330 


337* All [standard attributes](#standard-attributes)335* All [standard attributes](#standard-attributes)

338* `event.name`: `"user_prompt"`336* `event.name`: `"user_prompt"`

339* `event.timestamp`: ISO 8601 timestamp337* `event.timestamp`: ISO 8601 timestamp

338* `event.sequence`: monotonically increasing counter for ordering events within a session

340* `prompt_length`: Length of the prompt339* `prompt_length`: Length of the prompt

341* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)340* `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)

342 341 

343#### Tool Result Event342#### Tool result event

344 343 

345Logged when a tool completes execution.344Logged when a tool completes execution.

346 345 


351* All [standard attributes](#standard-attributes)350* All [standard attributes](#standard-attributes)

352* `event.name`: `"tool_result"`351* `event.name`: `"tool_result"`

353* `event.timestamp`: ISO 8601 timestamp352* `event.timestamp`: ISO 8601 timestamp

353* `event.sequence`: monotonically increasing counter for ordering events within a session

354* `tool_name`: Name of the tool354* `tool_name`: Name of the tool

355* `success`: `"true"` or `"false"`355* `success`: `"true"` or `"false"`

356* `duration_ms`: Execution time in milliseconds356* `duration_ms`: Execution time in milliseconds


359* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`359* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

360* `tool_parameters`: JSON string containing tool-specific parameters (when available)360* `tool_parameters`: JSON string containing tool-specific parameters (when available)

361 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`361 * For Bash tool: includes `bash_command`, `full_command`, `timeout`, `description`, `sandbox`

362 * For MCP tools (when `OTEL_LOG_TOOL_DETAILS=1`): includes `mcp_server_name`, `mcp_tool_name`

363 * For Skill tool (when `OTEL_LOG_TOOL_DETAILS=1`): includes `skill_name`

362 364 

363#### API Request Event365#### API request event

364 366 

365Logged for each API request to Claude.367Logged for each API request to Claude.

366 368 


371* All [standard attributes](#standard-attributes)373* All [standard attributes](#standard-attributes)

372* `event.name`: `"api_request"`374* `event.name`: `"api_request"`

373* `event.timestamp`: ISO 8601 timestamp375* `event.timestamp`: ISO 8601 timestamp

374* `model`: Model used (e.g., "claude-sonnet-4-5-20250929")376* `event.sequence`: monotonically increasing counter for ordering events within a session

377* `model`: Model used (for example, "claude-sonnet-4-5-20250929")

375* `cost_usd`: Estimated cost in USD378* `cost_usd`: Estimated cost in USD

376* `duration_ms`: Request duration in milliseconds379* `duration_ms`: Request duration in milliseconds

377* `input_tokens`: Number of input tokens380* `input_tokens`: Number of input tokens


379* `cache_read_tokens`: Number of tokens read from cache382* `cache_read_tokens`: Number of tokens read from cache

380* `cache_creation_tokens`: Number of tokens used for cache creation383* `cache_creation_tokens`: Number of tokens used for cache creation

381 384 

382#### API Error Event385#### API error event

383 386 

384Logged when an API request to Claude fails.387Logged when an API request to Claude fails.

385 388 


390* All [standard attributes](#standard-attributes)393* All [standard attributes](#standard-attributes)

391* `event.name`: `"api_error"`394* `event.name`: `"api_error"`

392* `event.timestamp`: ISO 8601 timestamp395* `event.timestamp`: ISO 8601 timestamp

393* `model`: Model used (e.g., "claude-sonnet-4-5-20250929")396* `event.sequence`: monotonically increasing counter for ordering events within a session

397* `model`: Model used (for example, "claude-sonnet-4-5-20250929")

394* `error`: Error message398* `error`: Error message

395* `status_code`: HTTP status code (if applicable)399* `status_code`: HTTP status code (if applicable)

396* `duration_ms`: Request duration in milliseconds400* `duration_ms`: Request duration in milliseconds

397* `attempt`: Attempt number (for retried requests)401* `attempt`: Attempt number (for retried requests)

398 402 

399#### Tool Decision Event403#### Tool decision event

400 404 

401Logged when a tool permission decision is made (accept/reject).405Logged when a tool permission decision is made (accept/reject).

402 406 


407* All [standard attributes](#standard-attributes)411* All [standard attributes](#standard-attributes)

408* `event.name`: `"tool_decision"`412* `event.name`: `"tool_decision"`

409* `event.timestamp`: ISO 8601 timestamp413* `event.timestamp`: ISO 8601 timestamp

410* `tool_name`: Name of the tool (e.g., "Read", "Edit", "Write", "NotebookEdit", etc.)414* `event.sequence`: monotonically increasing counter for ordering events within a session

415* `tool_name`: Name of the tool (for example, "Read", "Edit", "Write", "NotebookEdit")

411* `decision`: Either `"accept"` or `"reject"`416* `decision`: Either `"accept"` or `"reject"`

412* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`417* `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`

413 418 

414## Interpreting Metrics and Events Data419## Interpreting metrics and events data

415 420 

416The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:421The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:

417 422 

418### Usage Monitoring423### Usage monitoring

419 424 

420| Metric | Analysis Opportunity |425| Metric | Analysis Opportunity |

421| ------------------------------------------------------------- | --------------------------------------------------------- |426| ------------------------------------------------------------- | --------------------------------------------------------- |


424| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |429| `claude_code.lines_of_code.count` | Measure productivity by tracking code additions/removals |

425| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |430| `claude_code.commit.count` & `claude_code.pull_request.count` | Understand impact on development workflows |

426 431 

427### Cost Monitoring432### Cost monitoring

428 433 

429The `claude_code.cost.usage` metric helps with:434The `claude_code.cost.usage` metric helps with:

430 435 


435 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).440 Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).

436</Note>441</Note>

437 442 

438### Alerting and Segmentation443### Alerting and segmentation

439 444 

440Common alerts to consider:445Common alerts to consider:

441 446 


445 450 

446All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`.451All metrics can be segmented by `user.account_uuid`, `organization.id`, `session.id`, `model`, and `app.version`.

447 452 

448### Event Analysis453### Event analysis

449 454 

450The event data provides detailed insights into Claude Code interactions:455The event data provides detailed insights into Claude Code interactions:

451 456 

452**Tool Usage Patterns**: Analyze tool result events to identify:457**Tool Usage Patterns**: analyze tool result events to identify:

453 458 

454* Most frequently used tools459* Most frequently used tools

455* Tool success rates460* Tool success rates

456* Average tool execution times461* Average tool execution times

457* Error patterns by tool type462* Error patterns by tool type

458 463 

459**Performance Monitoring**: Track API request durations and tool execution times to identify performance bottlenecks.464**Performance Monitoring**: track API request durations and tool execution times to identify performance bottlenecks.

460 465 

461## Backend Considerations466## Backend considerations

462 467 

463Your choice of metrics and logs backends will determine the types of analyses you can perform:468Your choice of metrics and logs backends determines the types of analyses you can perform:

464 469 

465### For Metrics:470### For metrics

466 471 

467* **Time series databases (e.g., Prometheus)**: Rate calculations, aggregated metrics472* **Time series databases (for example, Prometheus)**: Rate calculations, aggregated metrics

468* **Columnar stores (e.g., ClickHouse)**: Complex queries, unique user analysis473* **Columnar stores (for example, ClickHouse)**: Complex queries, unique user analysis

469* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Advanced querying, visualization, alerting474* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Advanced querying, visualization, alerting

470 475 

471### For Events/Logs:476### For events/logs

472 477 

473* **Log aggregation systems (e.g., Elasticsearch, Loki)**: Full-text search, log analysis478* **Log aggregation systems (for example, Elasticsearch, Loki)**: Full-text search, log analysis

474* **Columnar stores (e.g., ClickHouse)**: Structured event analysis479* **Columnar stores (for example, ClickHouse)**: Structured event analysis

475* **Full-featured observability platforms (e.g., Honeycomb, Datadog)**: Correlation between metrics and events480* **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Correlation between metrics and events

476 481 

477For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.482For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.

478 483 

479## Service Information484## Service information

480 485 

481All metrics and events are exported with the following resource attributes:486All metrics and events are exported with the following resource attributes:

482 487 

483* `service.name`: `claude-code`488* `service.name`: `claude-code`

484* `service.version`: Current Claude Code version489* `service.version`: Current Claude Code version

485* `os.type`: Operating system type (e.g., `linux`, `darwin`, `windows`)490* `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`)

486* `os.version`: Operating system version string491* `os.version`: Operating system version string

487* `host.arch`: Host architecture (e.g., `amd64`, `arm64`)492* `host.arch`: Host architecture (for example, `amd64`, `arm64`)

488* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)493* `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)

489* Meter Name: `com.anthropic.claude_code`494* Meter Name: `com.anthropic.claude_code`

490 495 

491## ROI Measurement Resources496## ROI measurement resources

492 497 

493For 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.498For 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.

494 499 

495## Security/Privacy Considerations500## Security/privacy considerations

496 501 

497* Telemetry is opt-in and requires explicit configuration502* Telemetry is opt-in and requires explicit configuration

498* Sensitive information like API keys or file contents are never included in metrics or events503* Sensitive information like API keys or file contents are never included in metrics or events

499* User prompt content is redacted by default - only prompt length is recorded. To enable user prompt logging, set `OTEL_LOG_USER_PROMPTS=1`504* User prompt content is redacted by default, only prompt length is recorded. To enable user prompt logging, set `OTEL_LOG_USER_PROMPTS=1`

505* MCP server/tool names and skill names are not logged by default because they can reveal user-specific configurations. To enable, set `OTEL_LOG_TOOL_DETAILS=1`

500 506 

501## Monitoring Claude Code on Amazon Bedrock507## Monitoring Claude Code on Amazon Bedrock

502 508 

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.

Details

1> ## Documentation Index

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

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

4 

1# Output styles5# Output styles

2 6 

3> Adapt Claude Code for uses beyond software engineering7> Adapt Claude Code for uses beyond software engineering


103settings like the model to use, the tools they have available, and some context107settings like the model to use, the tools they have available, and some context

104about when to use the agent.108about when to use the agent.

105 109 

106### Output Styles vs. [Custom Slash Commands](/en/slash-commands)110### Output Styles vs. [Skills](/en/skills)

107 111 

108You can think of output styles as "stored system prompts" and custom slash112Output 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.

109commands as "stored prompts".

overview.md +167 −74

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 agentic coding tool that reads your codebase, edits files, and runs commands. It works in your terminal, IDE, browser, and as a desktop app.

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

42 Native installations automatically update in the background to keep you on the latest version.

43 </Info>

18 </Tab>44 </Tab>

19 45 

20 <Tab title="Homebrew">46 <Tab title="Homebrew">

21 ```bash theme={null}47 ```sh theme={null}

22 brew install --cask claude-code48 brew install --cask claude-code

23 ```49 ```

50 

51 <Info>

52 Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

53 </Info>

24 </Tab>54 </Tab>

25 55 

26 <Tab title="Windows">56 <Tab title="WinGet">

27 ```powershell theme={null}57 ```powershell theme={null}

28 irm https://claude.ai/install.ps1 | iex58 winget install Anthropic.ClaudeCode

29 ```59 ```

60 

61 <Info>

62 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

63 </Info>

30 </Tab>64 </Tab>

65 </Tabs>

66 

67 Then start Claude Code in any project:

31 68 

32 <Tab title="NPM">

33 ```bash theme={null}69 ```bash theme={null}

34 npm install -g @anthropic-ai/claude-code70 cd your-project

71 claude

35 ```72 ```

36 73 

37 Requires [Node.js 18+](https://nodejs.org/en/download/)74 You'll be prompted to log in on first use. That's it! [Continue with the Quickstart →](/en/quickstart)

75 

76 <Tip>

77 See [advanced setup](/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/en/troubleshooting) if you hit issues.

78 </Tip>

79 </Tab>

80 

81 <Tab title="VS Code">

82 The VS Code extension provides inline diffs, @-mentions, plan review, and conversation history directly in your editor.

83 

84 * [Install for VS Code](vscode:extension/anthropic.claude-code)

85 * [Install for Cursor](cursor:extension/anthropic.claude-code)

86 

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

88 

89 [Get started with VS Code →](/en/vs-code#get-started)

90 </Tab>

91 

92 <Tab title="Desktop app">

93 A standalone app for running Claude Code outside your IDE or terminal. Review diffs visually, run multiple sessions side by side, and kick off cloud sessions.

94 

95 Download and install:

96 

97 * [macOS](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code\&utm_medium=docs) (Intel and Apple Silicon)

98 * [Windows](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code\&utm_medium=docs) (x64)

99 

100 After installing, launch Claude, sign in, and click the **Code** tab to start coding.

101 

102 [Learn more about the desktop app →](/en/desktop#installation-and-setup)

103 </Tab>

104 

105 <Tab title="Web">

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

107 

108 Start coding at [claude.ai/code](https://claude.ai/code).

109 

110 [Get started on the web →](/en/claude-code-on-the-web#getting-started)

111 </Tab>

112 

113 <Tab title="JetBrains">

114 A plugin for IntelliJ IDEA, PyCharm, WebStorm, and other JetBrains IDEs with interactive diff viewing and selection context sharing.

115 

116 Install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains Marketplace and restart your IDE.

117 

118 [Get started with JetBrains →](/en/jetbrains)

38 </Tab>119 </Tab>

39</Tabs>120</Tabs>

40 121 

41**Start using Claude Code:**122## What you can do

42 123 

43```bash theme={null}124Here are some of the ways you can use Claude Code:

44cd your-project

45claude

46```

47 125 

48You'll be prompted to log in on first use. That's it! [Continue with Quickstart (5 mins) →](/en/quickstart)126<AccordionGroup>

127 <Accordion title="Automate the work you keep putting off" icon="wand-magic-sparkles">

128 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 129 

50<Tip>130 ```bash theme={null}

51 See [advanced setup](/en/setup) for installation options or [troubleshooting](/en/troubleshooting) if you hit issues.131 claude "write tests for the auth module, run them, and fix any failures"

52</Tip>132 ```

133 </Accordion>

53 134 

54<Note>135 <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/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.136 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 137 

58## What Claude Code does for you138 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.

139 </Accordion>

59 140 

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.141 <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.142 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/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 143 

65## Why developers love Claude Code144 ```bash theme={null}

145 claude "commit my changes with a descriptive message"

146 ```

66 147 

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.148 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/mcp) lets Claude read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling.149 </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/security), [privacy](/en/data-usage), and [compliance](https://trust.anthropic.com/) is built-in.

71 150 

72## Next steps151 <Accordion title="Connect your tools with MCP" icon="plug">

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

153 </Accordion>

73 154 

74<CardGroup>155 <Accordion title="Customize with instructions, skills, and hooks" icon="sliders">

75 <Card title="Quickstart" icon="rocket" href="/en/quickstart">156 [`CLAUDE.md`](/en/claude-md) is a markdown file you add to your project root that Claude Code reads at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists.

76 See Claude Code in action with practical examples

77 </Card>

78 157 

79 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">158 Create [custom slash commands](/en/skills) to package repeatable workflows your team can share, like `/review-pr` or `/deploy-staging`.

80 Step-by-step guides for common workflows

81 </Card>

82 159 

83 <Card title="Troubleshooting" icon="wrench" href="/en/troubleshooting">160 [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.

84 Solutions for common issues with Claude Code161 </Accordion>

85 </Card>

86 162 

87 <Card title="IDE setup" icon="laptop" href="/en/vs-code">163 <Accordion title="Run agent teams and build custom agents" icon="users">

88 Add Claude Code to your IDE164 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.

89 </Card>

90</CardGroup>

91 165 

92## Additional resources166 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.

167 </Accordion>

93 168 

94<CardGroup>169 <Accordion title="Pipe, script, and automate with the CLI" icon="terminal">

95 <Card title="Build with the Agent SDK" icon="code-branch" href="https://docs.claude.com/en/docs/agent-sdk/overview">170 Claude Code is composable and follows the Unix philosophy. Pipe logs into it, run it in CI, or chain it with other tools:

96 Create custom AI agents with the Claude Agent SDK

97 </Card>

98 171 

99 <Card title="Host on AWS or GCP" icon="cloud" href="/en/third-party-integrations">172 ```bash theme={null}

100 Configure Claude Code with Amazon Bedrock or Google Vertex AI173 # Monitor logs and get alerted

101 </Card>174 tail -f app.log | claude -p "Slack me if you see any anomalies"

175 

176 # Automate translations in CI

177 claude -p "translate new strings into French and raise a PR for review"

178 

179 # Bulk operations across files

180 git diff main --name-only | claude -p "review these changed files for security issues"

181 ```

102 182 

103 <Card title="Settings" icon="gear" href="/en/settings">183 See the [CLI reference](/en/cli-reference) for the full set of commands and flags.

104 Customize Claude Code for your workflow184 </Accordion>

105 </Card>

106 185 

107 <Card title="Commands" icon="terminal" href="/en/cli-reference">186 <Accordion title="Work from anywhere" icon="globe">

108 Learn about CLI commands and controls187 Start a task on your laptop and pick it up on your phone. [Claude Code on the web](/en/claude-code-on-the-web) and the [Claude iOS app](https://apps.apple.com/app/claude-by-anthropic/id6473753684) run sessions on cloud infrastructure, so you can kick off work from anywhere without a local dev environment.

109 </Card>

110 188 

111 <Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">189 You can also route coding tasks straight from team chat: mention `@Claude` in [Slack](/en/slack) with a bug report or feature request, and get a pull request back.

112 Clone our development container reference implementation190 </Accordion>

113 </Card>191</AccordionGroup>

192 

193## Use Claude Code everywhere

194 

195Each surface connects to the same underlying Claude Code engine, so your CLAUDE.md files, settings, and MCP servers work across all of them.

196 

197Beyond 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:

198 

199| I want to... | Best option |

200| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |

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

202| Automate PR reviews and issue triage | [GitHub Actions](/en/github-actions) or [GitLab CI/CD](/en/gitlab-ci-cd) |

203| Route bug reports from Slack to pull requests | [Slack](/en/slack) |

204| Debug live web applications | [Chrome](/en/chrome) |

205| Build custom agents for your own workflows | [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) |

206 

207## Next steps

114 208 

115 <Card title="Security" icon="shield" href="/en/security">209Once you've installed Claude Code, these guides help you go deeper.

116 Discover Claude Code's safeguards and best practices for safe usage

117 </Card>

118 210 

119 <Card title="Privacy and data usage" icon="lock" href="/en/data-usage">211* [Quickstart](/en/quickstart): walk through your first real task, from exploring a codebase to committing a fix

120 Understand how Claude Code handles your data212* Level up with [best practices](/en/best-practices) and [common workflows](/en/common-workflows)

121 </Card>213* [Settings](/en/settings): customize Claude Code for your workflow

122</CardGroup>214* [Troubleshooting](/en/troubleshooting): solutions for common issues

215* [code.claude.com](https://code.claude.com/): demos, pricing, and product details

permissions.md +258 −0 added

Details

1> ## Documentation Index

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

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

4 

5# Configure permissions

6 

7> Control what Claude Code can access and do with fine-grained permission rules, modes, and managed policies.

8 

9Claude Code supports fine-grained permissions so that you can specify exactly what the agent is allowed to do and what it cannot. Permission settings can be checked into version control and distributed to all developers in your organization, as well as customized by individual developers.

10 

11## Permission system

12 

13Claude Code uses a tiered permission system to balance power and safety:

14 

15| Tool type | Example | Approval required | "Yes, don't ask again" behavior |

16| :---------------- | :--------------- | :---------------- | :-------------------------------------------- |

17| Read-only | File reads, Grep | No | N/A |

18| Bash commands | Shell execution | Yes | Permanently per project directory and command |

19| File modification | Edit/write files | Yes | Until session end |

20 

21## Manage permissions

22 

23You can view and manage Claude Code's tool permissions with `/permissions`. This UI lists all permission rules and the settings.json file they are sourced from.

24 

25* **Allow** rules let Claude Code use the specified tool without manual approval.

26* **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool.

27* **Deny** rules prevent Claude Code from using the specified tool.

28 

29Rules are evaluated in order: **deny -> ask -> allow**. The first matching rule wins, so deny rules always take precedence.

30 

31## Permission modes

32 

33Claude Code supports several permission modes that control how tools are approved. Set the `defaultMode` in your [settings files](/en/settings#settings-files):

34 

35| Mode | Description |

36| :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

37| `default` | Standard behavior: prompts for permission on first use of each tool |

38| `acceptEdits` | Automatically accepts file edit permissions for the session |

39| `plan` | Plan Mode: Claude can analyze but not modify files or execute commands |

40| `delegate` | Coordination-only mode for agent team leads. Restricts the lead to team management tools, so all implementation work happens through teammates. Only available when an agent team is active. See [delegate mode](/en/agent-teams#delegate-mode) for details. |

41| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or `permissions.allow` rules |

42| `bypassPermissions` | Skips all permission prompts (requires safe environment, see warning below) |

43 

44<Warning>

45 `bypassPermissions` mode disables all permission checks. Only use this in isolated environments like containers or VMs where Claude Code cannot cause damage. Administrators can prevent this mode by setting `disableBypassPermissionsMode` to `"disable"` in [managed settings](#managed-settings).

46</Warning>

47 

48## Permission rule syntax

49 

50Permission rules follow the format `Tool` or `Tool(specifier)`.

51 

52### Match all uses of a tool

53 

54To match all uses of a tool, use just the tool name without parentheses:

55 

56| Rule | Effect |

57| :--------- | :----------------------------- |

58| `Bash` | Matches all Bash commands |

59| `WebFetch` | Matches all web fetch requests |

60| `Read` | Matches all file reads |

61 

62`Bash(*)` is equivalent to `Bash` and matches all Bash commands.

63 

64### Use specifiers for fine-grained control

65 

66Add a specifier in parentheses to match specific tool uses:

67 

68| Rule | Effect |

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

70| `Bash(npm run build)` | Matches the exact command `npm run build` |

71| `Read(./.env)` | Matches reading the `.env` file in the current directory |

72| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

73 

74### Wildcard patterns

75 

76Bash 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:

77 

78```json theme={null}

79{

80 "permissions": {

81 "allow": [

82 "Bash(npm run *)",

83 "Bash(git commit *)",

84 "Bash(git * main)",

85 "Bash(* --version)",

86 "Bash(* --help *)"

87 ],

88 "deny": [

89 "Bash(git push *)"

90 ]

91 }

92}

93```

94 

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

96 

97## Tool-specific permission rules

98 

99### Bash

100 

101Bash permission rules support wildcard matching with `*`. Wildcards can appear at any position in the command, including at the beginning, middle, or end:

102 

103* `Bash(npm run build)` matches the exact Bash command `npm run build`

104* `Bash(npm run test *)` matches Bash commands starting with `npm run test`

105* `Bash(npm *)` matches any command starting with `npm `

106* `Bash(* install)` matches any command ending with ` install`

107* `Bash(git * main)` matches commands like `git checkout main`, `git merge main`

108 

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

110 

111<Tip>

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

113</Tip>

114 

115<Warning>

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

117 

118 * Options before URL: `curl -X GET http://github.com/...`

119 * Different protocol: `curl https://github.com/...`

120 * Redirects: `curl -L http://bit.ly/xyz` (redirects to github)

121 * Variables: `URL=http://github.com && curl $URL`

122 * Extra spaces: `curl http://github.com`

123 

124 For more reliable URL filtering, consider:

125 

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

127 * **Use PreToolUse hooks**: implement a hook that validates URLs in Bash commands and blocks disallowed domains

128 * Instructing Claude Code about your allowed curl patterns via CLAUDE.md

129 

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

131</Warning>

132 

133### Read and Edit

134 

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

136 

137Read and Edit rules both follow the [gitignore](https://git-scm.com/docs/gitignore) specification with four distinct pattern types:

138 

139| Pattern | Meaning | Example | Matches |

140| ------------------ | -------------------------------------- | -------------------------------- | ---------------------------------- |

141| `//path` | **Absolute** path from filesystem root | `Read(//Users/alice/secrets/**)` | `/Users/alice/secrets/**` |

142| `~/path` | Path from **home** directory | `Read(~/Documents/*.pdf)` | `/Users/alice/Documents/*.pdf` |

143| `/path` | Path **relative to settings file** | `Edit(/src/**/*.ts)` | `<settings file path>/src/**/*.ts` |

144| `path` or `./path` | Path **relative to current directory** | `Read(*.env)` | `<cwd>/*.env` |

145 

146<Warning>

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

148</Warning>

149 

150Examples:

151 

152* `Edit(/docs/**)`: edits in `<project>/docs/` (NOT `/docs/`)

153* `Read(~/.zshrc)`: reads your home directory's `.zshrc`

154* `Edit(//tmp/scratch.txt)`: edits the absolute path `/tmp/scratch.txt`

155* `Read(src/**)`: reads from `<current-directory>/src/`

156 

157<Note>

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

159</Note>

160 

161### WebFetch

162 

163* `WebFetch(domain:example.com)` matches fetch requests to example.com

164 

165### MCP

166 

167* `mcp__puppeteer` matches any tool provided by the `puppeteer` server (name configured in Claude Code)

168* `mcp__puppeteer__*` wildcard syntax that also matches all tools from the `puppeteer` server

169* `mcp__puppeteer__puppeteer_navigate` matches the `puppeteer_navigate` tool provided by the `puppeteer` server

170 

171### Task (subagents)

172 

173Use `Task(AgentName)` rules to control which [subagents](/en/sub-agents) Claude can use:

174 

175* `Task(Explore)` matches the Explore subagent

176* `Task(Plan)` matches the Plan subagent

177* `Task(my-custom-agent)` matches a custom subagent named `my-custom-agent`

178 

179Add these rules to the `deny` array in your settings or use the `--disallowedTools` CLI flag to disable specific agents. To disable the Explore agent:

180 

181```json theme={null}

182{

183 "permissions": {

184 "deny": ["Task(Explore)"]

185 }

186}

187```

188 

189## Extend permissions with hooks

190 

191[Claude Code hooks](/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system, and the hook output can determine whether to approve or deny the tool call in place of the permission system.

192 

193## Working directories

194 

195By default, Claude has access to files in the directory where it was launched. You can extend this access:

196 

197* **During startup**: use `--add-dir <path>` CLI argument

198* **During session**: use `/add-dir` command

199* **Persistent configuration**: add to `additionalDirectories` in [settings files](/en/settings#settings-files)

200 

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

202 

203## How permissions interact with sandboxing

204 

205Permissions and [sandboxing](/en/sandboxing) are complementary security layers:

206 

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

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

209 

210Use both for defense-in-depth:

211 

212* Permission deny rules block Claude from even attempting to access restricted resources

213* Sandbox restrictions prevent Bash commands from reaching resources outside defined boundaries, even if a prompt injection bypasses Claude's decision-making

214* Filesystem restrictions in the sandbox use Read and Edit deny rules, not separate sandbox configuration

215* Network restrictions combine WebFetch permission rules with the sandbox's `allowedDomains` list

216 

217## Managed settings

218 

219For organizations that need centralized control over Claude Code configuration, administrators can deploy `managed-settings.json` files to system directories. These policy files follow the same format as regular settings files and cannot be overridden by user or project settings.

220 

221**Managed settings file locations**:

222 

223* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`

224* **Linux and WSL**: `/etc/claude-code/managed-settings.json`

225* **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json`

226 

227<Note>

228 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.

229</Note>

230 

231### Managed-only settings

232 

233Some settings are only effective in managed settings:

234 

235| Setting | Description |

236| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |

237| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode and the `--dangerously-skip-permissions` flag |

238| `allowManagedPermissionRulesOnly` | When `true`, prevents user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply |

239| `allowManagedHooksOnly` | When `true`, prevents loading of user, project, and plugin hooks. Only managed hooks and SDK hooks are allowed |

240| `strictKnownMarketplaces` | Controls which plugin marketplaces users can add. See [managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) |

241 

242## Settings precedence

243 

244Permission rules follow the same [settings precedence](/en/settings#settings-precedence) as all other Claude Code settings: managed settings have the highest precedence, followed by command line arguments, local project, shared project, and user settings.

245 

246If a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked.

247 

248## Example configurations

249 

250This [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.

251 

252## See also

253 

254* [Settings](/en/settings): complete configuration reference including the permission settings table

255* [Sandboxing](/en/sandboxing): OS-level filesystem and network isolation for Bash commands

256* [Authentication](/en/authentication): set up user access to Claude Code

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

258* [Hooks](/en/hooks-guide): automate workflows and extend permission evaluation

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 

9A marketplace is a JSON file that lists available plugins and describes where to find them. Marketplaces provide:

10 

11* **Centralized discovery**: Browse plugins from multiple sources in one place

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 

16### Prerequisites

17 

18* Claude Code installed and running

19* Basic familiarity with JSON file format

20* For creating marketplaces: Git repository or local development environment

21 

22## Add and use marketplaces

23 10 

24Add marketplaces using the `/plugin marketplace` commands to access plugins from different sources:11Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/en/discover-plugins).

25 12 

26### Add GitHub marketplaces13## Overview

27 

28```shell Add a GitHub repository containing .claude-plugin/marketplace.json theme={null}

29/plugin marketplace add owner/repo

30```

31 

32### Add Git repositories

33 

34```shell Add any git repository theme={null}

35/plugin marketplace add https://gitlab.com/company/plugins.git

36```

37 14 

38### Add local marketplaces for development15Creating and distributing a marketplace involves:

39 16 

40```shell Add local directory containing .claude-plugin/marketplace.json theme={null}171. **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.

41/plugin marketplace add ./my-marketplace182. **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)).

42```193. **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)).

43 21 

44```shell Add direct path to marketplace.json file theme={null}22Once your marketplace is live, you can update it by pushing changes to your repository. Users refresh their local copy with `/plugin marketplace update`.

45/plugin marketplace add ./path/to/marketplace.json

46```

47 23 

48```shell Add remote marketplace.json via URL theme={null}24## Walkthrough: create a local marketplace

49/plugin marketplace add https://url.of/marketplace.json

50```

51 25 

52### Install plugins from marketplaces26This example creates a marketplace with one plugin: a `/review` skill for code reviews. You'll create the directory structure, add a skill, create the plugin manifest and marketplace catalog, then install and test it.

53 27 

54Once you've added marketplaces, install plugins directly:28<Steps>

29 <Step title="Create the directory structure">

30 ```bash theme={null}

31 mkdir -p my-marketplace/.claude-plugin

32 mkdir -p my-marketplace/plugins/review-plugin/.claude-plugin

33 mkdir -p my-marketplace/plugins/review-plugin/skills/review

34 ```

35 </Step>

55 36 

56```shell Install from any known marketplace theme={null}37 <Step title="Create the skill">

57/plugin install plugin-name@marketplace-name38 Create a `SKILL.md` file that defines what the `/review` skill does.

58```

59 39 

60```shell Browse available plugins interactively theme={null}40 ```markdown my-marketplace/plugins/review-plugin/skills/review/SKILL.md theme={null}

61/plugin41 ---

62```42 description: Review code for bugs, security, and performance

43 disable-model-invocation: true

44 ---

63 45 

64### Verify marketplace installation46 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

65 51 

66After adding a marketplace:52 Be concise and actionable.

53 ```

54 </Step>

67 55 

681. **List marketplaces**: Run `/plugin marketplace list` to confirm it's added56 <Step title="Create the plugin manifest">

692. **Browse plugins**: Use `/plugin` to see available plugins from your marketplace57 Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory.

703. **Test installation**: Try installing a plugin to verify the marketplace works correctly

71 58 

72## Configure team marketplaces59 ```json my-marketplace/plugins/review-plugin/.claude-plugin/plugin.json theme={null}

60 {

61 "name": "review-plugin",

62 "description": "Adds a /review skill for quick code reviews",

63 "version": "1.0.0"

64 }

65 ```

66 </Step>

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": "review-plugin",

88 "url": "https://git.company.com/project-plugins.git"80 "source": "./plugins/review-plugin",

89 }81 "description": "Adds a /review skill for quick code reviews"

90 }82 }

83 ]

91 }84 }

92}85 ```

93```86 </Step>

87 

88 <Step title="Add and install">

89 Add the marketplace and install the plugin.

90 

91 ```shell theme={null}

92 /plugin marketplace add ./my-marketplace

93 /plugin install review-plugin@my-plugins

94 ```

95 </Step>

94 96 

95When team members trust the repository folder, Claude Code automatically installs these marketplaces and any plugins specified in the `enabledPlugins` field.97 <Step title="Try it out">

98 Select some code in your editor and run your new command.

96 99 

97***100 ```shell theme={null}

101 /review

102 ```

103 </Step>

104</Steps>

98 105 

99## Create your own marketplace106To learn more about what plugins can do, including hooks, agents, MCP servers, and LSP servers, see [Plugins](/en/plugins).

100 107 

101Build and distribute custom plugin collections for your team or community.108<Note>

109 **How plugins are installed**: When users install a plugin, Claude Code copies the plugin directory to a cache location. This means plugins can't reference files outside their directory using paths like `../shared-utils`, because those files won't be copied.

102 110 

103### Prerequisites for marketplace creation111 If you need to share files across plugins, use symlinks (which are followed during copying) or restructure your marketplace so the shared directory is inside the plugin source path. See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for details.

112</Note>

104 113 

105* Git repository (GitHub, GitLab, or other git hosting)114## Create the marketplace file

106* Understanding of JSON file format

107* One or more plugins to distribute

108 115 

109### Create the marketplace file116Create `.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.

110 117 

111Create `.claude-plugin/marketplace.json` in your repository root: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`, `life-sciences`. Names that impersonate official marketplaces (like `official-claude-plugins` or `anthropic-tools-v2`) are also blocked.

161</Note>

162 

163### 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 |

151 169 

152#### Optional metadata170### 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 | When true (default), marketplace component fields merge with plugin.json. When false, the marketplace entry defines the plugin entirely, and plugin.json must not also declare components. |

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 |

198 215 

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>*216## Plugin sources

200 

201### Plugin sources

202 217 

203#### Relative paths218### Relative paths

204 219 

205For plugins in the same repository:220For plugins in the same repository:

206 221 


211}226}

212```227```

213 228 

214#### GitHub repositories229<Note>

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

231</Note>

232 

233### GitHub repositories

215 234 

216```json theme={null}235```json theme={null}

217{236{


223}242}

224```243```

225 244 

226#### Git repositories245You can pin to a specific branch, tag, or commit:

246 

247```json theme={null}

248{

249 "name": "github-plugin",

250 "source": {

251 "source": "github",

252 "repo": "owner/plugin-repo",

253 "ref": "v2.0.0",

254 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

255 }

256}

257```

258 

259| Field | Type | Description |

260| :----- | :----- | :-------------------------------------------------------------------- |

261| `repo` | string | Required. GitHub repository in `owner/repo` format |

262| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

263| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

264 

265### Git repositories

227 266 

228```json theme={null}267```json theme={null}

229{268{


235}274}

236```275```

237 276 

238#### Advanced plugin entries277You can pin to a specific branch, tag, or commit:

278 

279```json theme={null}

280{

281 "name": "git-plugin",

282 "source": {

283 "source": "url",

284 "url": "https://gitlab.com/team/plugin.git",

285 "ref": "main",

286 "sha": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0"

287 }

288}

289```

290 

291| Field | Type | Description |

292| :---- | :----- | :-------------------------------------------------------------------- |

293| `url` | string | Required. Full git repository URL (must end with `.git`) |

294| `ref` | string | Optional. Git branch or tag (defaults to repository default branch) |

295| `sha` | string | Optional. Full 40-character git commit SHA to pin to an exact version |

296 

297### Advanced plugin entries

239 298 

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/plugins-reference#environment-variables)):299This example shows a plugin entry using many of the optional fields, including custom paths for commands, agents, hooks, and MCP servers:

241 300 

242```json theme={null}301```json theme={null}

243{302{


250 "version": "2.1.0",309 "version": "2.1.0",

251 "author": {310 "author": {

252 "name": "Enterprise Team",311 "name": "Enterprise Team",

253 "email": "enterprise@company.com"312 "email": "enterprise@example.com"

254 },313 },

255 "homepage": "https://docs.company.com/plugins/enterprise-tools",314 "homepage": "https://docs.example.com/plugins/enterprise-tools",

256 "repository": "https://github.com/company/enterprise-plugin",315 "repository": "https://github.com/company/enterprise-plugin",

257 "license": "MIT",316 "license": "MIT",

258 "keywords": ["enterprise", "workflow", "automation"],317 "keywords": ["enterprise", "workflow", "automation"],


262 "./commands/enterprise/",321 "./commands/enterprise/",

263 "./commands/experimental/preview.md"322 "./commands/experimental/preview.md"

264 ],323 ],

265 "agents": [324 "agents": ["./agents/security-reviewer.md", "./agents/compliance-checker.md"],

266 "./agents/security-reviewer.md",

267 "./agents/compliance-checker.md"

268 ],

269 "hooks": {325 "hooks": {

270 "PostToolUse": [326 "PostToolUse": [

271 {327 {

272 "matcher": "Write|Edit",328 "matcher": "Write|Edit",

273 "hooks": [{"type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"}]329 "hooks": [

330 {

331 "type": "command",

332 "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"

333 }

334 ]

274 }335 }

275 ]336 ]

276 },337 },


284}345}

285```346```

286 347 

287<Note>348Key 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 349 

291***350* **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root.

351* **`${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.

352* **`strict: false`**: Since this is set to false, the plugin doesn't need its own `plugin.json`. The marketplace entry defines everything.

292 353 

293## Host and distribute marketplaces354## Host and distribute marketplaces

294 355 

295Choose the best hosting strategy for your plugin distribution needs.

296 

297### Host on GitHub (recommended)356### Host on GitHub (recommended)

298 357 

299GitHub provides the easiest distribution method:358GitHub provides the easiest distribution method:

300 359 

3011. **Create a repository**: Set up a new repository for your marketplace3601. **Create a repository**: Set up a new repository for your marketplace

3022. **Add marketplace file**: Create `.claude-plugin/marketplace.json` with your plugin definitions3612. **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`3623. **Share with teams**: Users add your marketplace with `/plugin marketplace add owner/repo`

304 363 

305**Benefits**: Built-in version control, issue tracking, and team collaboration features.364**Benefits**: Built-in version control, issue tracking, and team collaboration features.

306 365 

307### Host on other git services366### Host on other git services

308 367 

309Any git hosting service works for marketplace distribution, using a URL to an arbitrary git repository.368Any 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 369 

313```shell theme={null}370```shell theme={null}

314/plugin marketplace add https://gitlab.com/company/plugins.git371/plugin marketplace add https://gitlab.com/company/plugins.git

315```372```

316 373 

317### Use local marketplaces for development374### Private repositories

318 375 

319Test your marketplace locally before distribution:376Claude 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 377 

321```shell Add local marketplace for testing theme={null}378Background 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-marketplace379 

380| Provider | Environment variables | Notes |

381| :-------- | :--------------------------- | :---------------------------------------- |

382| GitHub | `GITHUB_TOKEN` or `GH_TOKEN` | Personal access token or GitHub App token |

383| GitLab | `GITLAB_TOKEN` or `GL_TOKEN` | Personal access token or project token |

384| Bitbucket | `BITBUCKET_TOKEN` | App password or repository access token |

385 

386Set the token in your shell configuration (for example, `.bashrc`, `.zshrc`) or pass it when running Claude Code:

387 

388```bash theme={null}

389export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

323```390```

324 391 

325```shell Test plugin installation theme={null}392<Note>

393 For CI/CD environments, configure the token as a secret environment variable. GitHub Actions automatically provides `GITHUB_TOKEN` for repositories in the same organization.

394</Note>

395 

396### Test locally before distribution

397 

398Test your marketplace locally before sharing:

399 

400```shell theme={null}

401/plugin marketplace add ./my-local-marketplace

326/plugin install test-plugin@my-local-marketplace402/plugin install test-plugin@my-local-marketplace

327```403```

328 404 

329## Manage marketplace operations405For the full range of add commands (GitHub, Git URLs, local paths, remote URLs), see [Add marketplaces](/en/discover-plugins#add-marketplaces).

330 406 

331### List known marketplaces407### Require marketplaces for your team

332 408 

333```shell List all configured marketplaces theme={null}409You 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 list410 

411```json theme={null}

412{

413 "extraKnownMarketplaces": {

414 "company-tools": {

415 "source": {

416 "source": "github",

417 "repo": "your-org/claude-plugins"

418 }

419 }

420 }

421}

335```422```

336 423 

337Shows all configured marketplaces with their sources and status.424You can also specify which plugins should be enabled by default:

425 

426```json theme={null}

427{

428 "enabledPlugins": {

429 "code-formatter@company-tools": true,

430 "deployment-tools@company-tools": true

431 }

432}

433```

434 

435For full configuration options, see [Plugin settings](/en/settings#plugin-settings).

436 

437### Managed marketplace restrictions

438 

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

338 440 

339### Update marketplace metadata441When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value:

340 442 

341```shell Refresh marketplace metadata theme={null}443| Value | Behavior |

342/plugin marketplace update marketplace-name444| ------------------- | ---------------------------------------------------------------- |

445| Undefined (default) | No restrictions. Users can add any marketplace |

446| Empty array `[]` | Complete lockdown. Users cannot add any new marketplaces |

447| List of sources | Users can only add marketplaces that match the allowlist exactly |

448 

449#### Common configurations

450 

451Disable all marketplace additions:

452 

453```json theme={null}

454{

455 "strictKnownMarketplaces": []

456}

343```457```

344 458 

345Refreshes plugin listings and metadata from the marketplace source.459Allow specific marketplaces only:

346 460 

347### Remove a marketplace461```json theme={null}

462{

463 "strictKnownMarketplaces": [

464 {

465 "source": "github",

466 "repo": "acme-corp/approved-plugins"

467 },

468 {

469 "source": "github",

470 "repo": "acme-corp/security-tools",

471 "ref": "v2.0"

472 },

473 {

474 "source": "url",

475 "url": "https://plugins.example.com/marketplace.json"

476 }

477 ]

478}

479```

480 

481Allow all marketplaces from an internal git server using regex pattern matching:

348 482 

349```shell Remove a marketplace theme={null}483```json theme={null}

350/plugin marketplace remove marketplace-name484{

485 "strictKnownMarketplaces": [

486 {

487 "source": "hostPattern",

488 "hostPattern": "^github\\.example\\.com$"

489 }

490 ]

491}

351```492```

352 493 

353Removes the marketplace from your configuration.494#### How restrictions work

495 

496Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.

497 

498The allowlist uses exact matching for most source types. For a marketplace to be allowed, all specified fields must match exactly:

354 499 

355<Warning>500* For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist

356 Removing a marketplace will uninstall any plugins you installed from it.501* For URL sources: the full URL must match exactly

357</Warning>502* For `hostPattern` sources: the marketplace host is matched against the regex pattern

358 503 

359***504Because `strictKnownMarketplaces` is set in [managed settings](/en/settings#settings-files), individual users and project configurations cannot override these restrictions.

360 505 

361## Troubleshooting marketplaces506For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces).

362 507 

363### Common marketplace issues508## Validation and testing

364 509 

365#### Marketplace not loading510Test your marketplace before sharing.

511 

512Validate your marketplace JSON syntax:

513 

514```bash theme={null}

515claude plugin validate .

516```

517 

518Or from within Claude Code:

519 

520```shell theme={null}

521/plugin validate .

522```

523 

524Add the marketplace for testing:

525 

526```shell theme={null}

527/plugin marketplace add ./path/to/marketplace

528```

529 

530Install a test plugin to verify everything works:

531 

532```shell theme={null}

533/plugin install test-plugin@marketplace-name

534```

535 

536For complete plugin testing workflows, see [Test your plugins locally](/en/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/en/plugins-reference).

537 

538## Troubleshooting

539 

540### Marketplace not loading

366 541 

367**Symptoms**: Can't add marketplace or see plugins from it542**Symptoms**: Can't add marketplace or see plugins from it

368 543 


370 545 

371* Verify the marketplace URL is accessible546* Verify the marketplace URL is accessible

372* Check that `.claude-plugin/marketplace.json` exists at the specified path547* Check that `.claude-plugin/marketplace.json` exists at the specified path

373* Ensure JSON syntax is valid using `claude plugin validate`548* Ensure JSON syntax is valid using `claude plugin validate` or `/plugin validate`

374* For private repositories, confirm you have access permissions549* For private repositories, confirm you have access permissions

375 550 

376#### Plugin installation failures551### Marketplace validation errors

552 

553Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. Common errors:

554 

555| Error | Cause | Solution |

556| :------------------------------------------------ | :------------------------------ | :------------------------------------------------------------ |

557| `File not found: .claude-plugin/marketplace.json` | Missing manifest | Create `.claude-plugin/marketplace.json` with required fields |

558| `Invalid JSON syntax: Unexpected token...` | JSON syntax error | Check for missing commas, extra commas, or unquoted strings |

559| `Duplicate plugin name "x" found in marketplace` | Two plugins share the same name | Give each plugin a unique `name` value |

560| `plugins[0].source: Path traversal not allowed` | Source path contains `..` | Use paths relative to marketplace root without `..` |

561 

562**Warnings** (non-blocking):

563 

564* `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array

565* `No marketplace description provided`: add `metadata.description` to help users understand your marketplace

566* `Plugin "x" uses npm source which is not yet fully implemented`: use `github` or local path sources instead

567 

568### Plugin installation failures

377 569 

378**Symptoms**: Marketplace appears but plugin installation fails570**Symptoms**: Marketplace appears but plugin installation fails

379 571 


384* For GitHub sources, ensure repositories are public or you have access576* For GitHub sources, ensure repositories are public or you have access

385* Test plugin sources manually by cloning/downloading577* Test plugin sources manually by cloning/downloading

386 578 

387### Validation and testing579### Private repository authentication fails

388 580 

389Test your marketplace before sharing:581**Symptoms**: Authentication errors when installing plugins from private repositories

390 582 

391```bash Validate marketplace JSON syntax theme={null}583**Solutions**:

392claude plugin validate .

393```

394 584 

395```shell Add marketplace for testing theme={null}585For manual installation and updates:

396/plugin marketplace add ./path/to/marketplace

397```

398 586 

399```shell Install test plugin theme={null}587* Verify you're authenticated with your git provider (for example, run `gh auth status` for GitHub)

400/plugin install test-plugin@marketplace-name588* Check that your credential helper is configured correctly: `git config --global credential.helper`

401```589* Try cloning the repository manually to verify your credentials work

402 590 

403For complete plugin testing workflows, see [Test your plugins locally](/en/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/en/plugins-reference).591For background auto-updates:

592 

593* Set the appropriate token in your environment: `echo $GITHUB_TOKEN`

594* Check that the token has the required permissions (read access to the repository)

595* For GitHub, ensure the token has the `repo` scope for private repositories

596* For GitLab, ensure the token has at least `read_repository` scope

597* Verify the token hasn't expired

598 

599### Plugins with relative paths fail in URL-based marketplaces

404 600 

405***601**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.

406 602 

407## Next steps603**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.

604 

605**Solutions**:

408 606 

409### For marketplace users607* **Use external sources**: Change plugin entries to use GitHub, npm, or git URL sources instead of relative paths:

608 ```json theme={null}

609 { "name": "my-plugin", "source": { "source": "github", "repo": "owner/repo" } }

610 ```

611* **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 612 

411* **Discover community marketplaces**: Search GitHub for Claude Code plugin collections613### 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 614 

415### For marketplace creators615**Symptoms**: Plugin installs but references to files fail, especially files outside the plugin directory

416 616 

417* **Build plugin collections**: Create themed marketplace around specific use cases617**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 618 

422### For organizations619**Solutions**: See [Plugin caching and file resolution](/en/plugins-reference#plugin-caching-and-file-resolution) for workarounds including symlinks and directory restructuring.

423 620 

424* **Private marketplaces**: Set up internal marketplaces for proprietary tools621For 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 622 

428## See also623## See also

429 624 

430* [Plugins](/en/plugins) - Installing and using plugins625* [Discover and install prebuilt plugins](/en/discover-plugins) - Installing plugins from existing marketplaces

626* [Plugins](/en/plugins) - Creating your own plugins

431* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas627* [Plugins reference](/en/plugins-reference) - Complete technical specifications and schemas

432* [Plugin development](/en/plugins#develop-more-complex-plugins) - Creating your own plugins628* [Plugin settings](/en/settings#plugin-settings) - Plugin configuration options

433* [Settings](/en/settings#plugin-configuration) - Plugin configuration options629* [strictKnownMarketplaces reference](/en/settings#strictknownmarketplaces) - Managed marketplace restrictions

plugins.md +272 −253

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 `/review`

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/plugins-reference). For marketplace management, see [Plugin marketplaces](/en/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/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* Claude Code version 1.0.33 or later (run `claude --version` to check)

49 

50<Note>

51 If you don't see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/en/troubleshooting) for upgrade instructions.

52</Note>

19 53 

20### Create your first plugin54### Create your first plugin

21 55 

22<Steps>56<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">57 <Step title="Create the plugin directory">

58 Every plugin lives in its own directory containing a manifest and your skills, agents, or hooks. Create one now:

59 

31 ```bash theme={null}60 ```bash theme={null}

32 mkdir my-first-plugin61 mkdir my-first-plugin

33 cd my-first-plugin

34 ```62 ```

35 </Step>63 </Step>

36 64 

37 <Step title="Create the plugin manifest">65 <Step title="Create the plugin manifest">

38 ```bash Create .claude-plugin/plugin.json theme={null}66 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-plugin67 

40 cat > .claude-plugin/plugin.json << 'EOF'68 Create the `.claude-plugin` directory inside your plugin folder:

69 

70 ```bash theme={null}

71 mkdir my-first-plugin/.claude-plugin

72 ```

73 

74 Then create `my-first-plugin/.claude-plugin/plugin.json` with this content:

75 

76 ```json my-first-plugin/.claude-plugin/plugin.json theme={null}

41 {77 {

42 "name": "my-first-plugin",78 "name": "my-first-plugin",

43 "description": "A simple greeting plugin to learn the basics",79 "description": "A greeting plugin to learn the basics",

44 "version": "1.0.0",80 "version": "1.0.0",

45 "author": {81 "author": {

46 "name": "Your Name"82 "name": "Your Name"

47 }83 }

48 }84 }

49 EOF

50 ```85 ```

86 

87 | Field | Purpose |

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

89 | `name` | Unique identifier and skill namespace. Skills are prefixed with this (e.g., `/my-first-plugin:hello`). |

90 | `description` | Shown in the plugin manager when browsing or installing plugins. |

91 | `version` | Track releases using [semantic versioning](/en/plugins-reference#version-management). |

92 | `author` | Optional. Helpful for attribution. |

93 

94 For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema).

51 </Step>95 </Step>

52 96 

53 <Step title="Add a custom command">97 <Step title="Add a skill">

54 ```bash Create commands/hello.md theme={null}98 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 99 

61 # Hello Command100 Create a skill directory in your plugin folder:

62 101 

63 Greet the user warmly and ask how you can help them today. Make the greeting personal and encouraging.102 ```bash theme={null}

64 EOF103 mkdir -p my-first-plugin/skills/hello

65 ```104 ```

66 </Step>

67 105 

68 <Step title="Create the marketplace manifest">106 Then create `my-first-plugin/skills/hello/SKILL.md` with this content:

69 ```bash Create marketplace.json theme={null}107 

70 cd ..108 ```markdown my-first-plugin/skills/hello/SKILL.md theme={null}

71 mkdir .claude-plugin109 ---

72 cat > .claude-plugin/marketplace.json << 'EOF'110 description: Greet the user with a friendly message

73 {111 disable-model-invocation: true

74 "name": "test-marketplace",112 ---

75 "owner": {113 

76 "name": "Test User"114 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 ```115 ```

88 </Step>116 </Step>

89 117 

90 <Step title="Install and test your plugin">118 <Step title="Test your plugin">

91 ```bash Start Claude Code from parent directory theme={null}119 Run Claude Code with the `--plugin-dir` flag to load your plugin:

92 cd ..120 

93 claude121 ```bash theme={null}

122 claude --plugin-dir ./my-first-plugin

94 ```123 ```

95 124 

96 ```shell Add the test marketplace theme={null}125 Once Claude Code starts, try your new command:

97 /plugin marketplace add ./test-marketplace126 

127 ```shell theme={null}

128 /my-first-plugin:hello

98 ```129 ```

99 130 

100 ```shell Install your plugin theme={null}131 You'll see Claude respond with a greeting. Run `/help` to see your command listed under the plugin namespace.

101 /plugin install my-first-plugin@test-marketplace132 

133 <Note>

134 **Why namespacing?** Plugin skills are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have skills with the same name.

135 

136 To change the namespace prefix, update the `name` field in `plugin.json`.

137 </Note>

138 </Step>

139 

140 <Step title="Add skill arguments">

141 Make your skill dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the skill name.

142 

143 Update your `hello.md` file:

144 

145 ```markdown my-first-plugin/commands/hello.md theme={null}

146 ---

147 description: Greet the user with a personalized message

148 ---

149 

150 # Hello Command

151 

152 Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.

102 ```153 ```

103 154 

104 Select "Install now". You'll then need to restart Claude Code in order to use the new plugin.155 Restart Claude Code to pick up the changes, then try the command with your name:

105 156 

106 ```shell Try your new command theme={null}157 ```shell theme={null}

107 /hello158 /my-first-plugin:hello Alex

108 ```159 ```

109 160 

110 You'll see Claude use your greeting command! Check `/help` to see your new command listed.161 Claude will greet you by name. For more on passing arguments to skills, see [Skills](/en/skills#pass-arguments-to-skills).

111 </Step>162 </Step>

112</Steps>163</Steps>

113 164 

114You've successfully created and tested a plugin with these key components:165You've successfully created and tested a plugin with these key components:

115 166 

116* **Plugin manifest** (`.claude-plugin/plugin.json`) - Describes your plugin's metadata167* **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata

117* **Commands directory** (`commands/`) - Contains your custom slash commands168* **Commands directory** (`commands/`): contains your custom skills

118* **Test marketplace** - Allows you to test your plugin locally169* **Skill arguments** (`$ARGUMENTS`): captures user input for dynamic behavior

119 170 

120### Plugin structure overview171<Tip>

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

173</Tip>

121 174 

122Your plugin follows this basic structure:175## Plugin structure overview

123 176 

124```177You'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 178 

139**Additional components you can add:**179<Warning>

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

181</Warning>

140 182 

141* **Commands**: Create markdown files in `commands/` directory183| Directory | Location | Purpose |

142* **Agents**: Create agent definitions in `agents/` directory184| :---------------- | :---------- | :----------------------------------------------------------------------------- |

143* **Skills**: Create `SKILL.md` files in `skills/` directory185| `.claude-plugin/` | Plugin root | Contains `plugin.json` manifest (optional if components use default locations) |

144* **Hooks**: Create `hooks/hooks.json` for event handling186| `commands/` | Plugin root | Skills as Markdown files |

145* **MCP servers**: Create `.mcp.json` for external tool integration187| `agents/` | Plugin root | Custom agent definitions |

188| `skills/` | Plugin root | Agent Skills with `SKILL.md` files |

189| `hooks/` | Plugin root | Event handlers in `hooks.json` |

190| `.mcp.json` | Plugin root | MCP server configurations |

191| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |

146 192 

147<Note>193<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/plugins-reference).194 **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>195</Note>

150 196 

151***197## Develop more complex plugins

152 

153## Install and manage plugins

154 

155Learn how to discover, install, and manage plugins to extend your Claude Code capabilities.

156 198 

157### Prerequisites199Once you're comfortable with basic plugins, you can create more sophisticated extensions.

158 200 

159* Claude Code installed and running201### Add Skills to your plugin

160* Basic familiarity with command-line interfaces

161 202 

162### Add marketplaces203Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked: Claude automatically uses them based on the task context.

163 204 

164Marketplaces are catalogs of available plugins. Add them to discover and install plugins:205Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:

165 206 

166```shell Add a marketplace theme={null}

167/plugin marketplace add your-org/claude-plugins

168```207```

169 208my-plugin/

170```shell Browse available plugins theme={null}209├── .claude-plugin/

171/plugin210│ └── plugin.json

211└── skills/

212 └── code-review/

213 └── SKILL.md

172```214```

173 215 

174For detailed marketplace management including Git repositories, local development, and team distribution, see [Plugin marketplaces](/en/plugin-marketplaces).216Each `SKILL.md` needs frontmatter with `name` and `description` fields, followed by instructions:

175 

176### Install plugins

177 217 

178#### Via interactive menu (recommended for discovery)218```yaml theme={null}

219---

220name: code-review

221description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.

222---

179 223 

180```shell Open the plugin management interface theme={null}224When reviewing code, check for:

181/plugin2251. Code organization and structure

2262. Error handling

2273. Security concerns

2284. Test coverage

182```229```

183 230 

184Select "Browse Plugins" to see available options with descriptions, features, and installation options.231After installing the plugin, restart Claude Code to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills).

185 232 

186#### Via direct commands (for quick installation)233### Add LSP servers to your plugin

187 234 

188```shell Install a specific plugin theme={null}235<Tip>

189/plugin install formatter@your-org236 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.

190```237</Tip>

191 238 

192```shell Enable a disabled plugin theme={null}239LSP (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:

193/plugin enable plugin-name@marketplace-name

194```

195 240 

196```shell Disable without uninstalling theme={null}241```json .lsp.json theme={null}

197/plugin disable plugin-name@marketplace-name242{

243 "go": {

244 "command": "gopls",

245 "args": ["serve"],

246 "extensionToLanguage": {

247 ".go": "go"

248 }

249 }

250}

198```251```

199 252 

200```shell Completely remove a plugin theme={null}253Users installing your plugin must have the language server binary installed on their machine.

201/plugin uninstall plugin-name@marketplace-name

202```

203 254 

204### Verify installation255For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers).

205 256 

206After installing a plugin:257### Organize complex plugins

207 258 

2081. **Check available commands**: Run `/help` to see new commands259For 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).

2092. **Test plugin features**: Try the plugin's commands and features

2103. **Review plugin details**: Use `/plugin` → "Manage Plugins" to see what the plugin provides

211 260 

212## Set up team plugin workflows261### Test your plugins locally

213 262 

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.263Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation.

215 264 

216**To set up team plugins:**265```bash theme={null}

266claude --plugin-dir ./my-plugin

267```

217 268 

2181. Add marketplace and plugin configuration to your repository's `.claude/settings.json`269As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components:

2192. Team members trust the repository folder

2203. Plugins install automatically for all team members

221 270 

222For complete instructions including configuration examples, marketplace setup, and rollout best practices, see [Configure team marketplaces](/en/plugin-marketplaces#how-to-configure-team-marketplaces).271* Try your commands with `/command-name`

272* Check that agents appear in `/agents`

273* Verify hooks work as expected

223 274 

224***275<Tip>

276 You can load multiple plugins at once by specifying the flag multiple times:

225 277 

226## Develop more complex plugins278 ```bash theme={null}

279 claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two

280 ```

281</Tip>

227 282 

228Once you're comfortable with basic plugins, you can create more sophisticated extensions.283### Debug plugin issues

229 284 

230### Add Skills to your plugin285If your plugin isn't working as expected:

231 286 

232Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked—Claude autonomously uses them based on the task context.2871. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`

2882. **Test components individually**: Check each command, agent, and hook separately

2893. **Use validation and debugging tools**: See [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques

233 290 

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.291### Share your plugins

235 292 

236For complete Skill authoring guidance, see [Agent Skills](/en/skills).293When your plugin is ready to share:

237 294 

238### Organize complex plugins2951. **Add documentation**: Include a `README.md` with installation and usage instructions

2962. **Version your plugin**: Use [semantic versioning](/en/plugins-reference#version-management) in your `plugin.json`

2973. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation

2984. **Test with others**: Have team members test the plugin before wider distribution

239 299 

240For 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).300Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins).

241 301 

242### Test your plugins locally302<Note>

303 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).

304</Note>

243 305 

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.306## Convert existing configurations to plugins

245 307 

246<Steps>308If you already have skills or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution.

247 <Step title="Set up your development structure">

248 Organize your plugin and marketplace for testing:

249 309 

250 ```bash Create directory structure theme={null}310### Migration steps

251 mkdir dev-marketplace

252 cd dev-marketplace

253 mkdir my-plugin

254 ```

255 311 

256 This creates:312<Steps>

313 <Step title="Create the plugin structure">

314 Create a new plugin directory:

257 315 

316 ```bash theme={null}

317 mkdir -p my-plugin/.claude-plugin

258 ```318 ```

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 319 

269 <Step title="Create the marketplace manifest">320 Create the manifest file at `my-plugin/.claude-plugin/plugin.json`:

270 ```bash Create marketplace.json theme={null}321 

271 mkdir .claude-plugin322 ```json my-plugin/.claude-plugin/plugin.json theme={null}

272 cat > .claude-plugin/marketplace.json << 'EOF'

273 {

274 "name": "dev-marketplace",

275 "owner": {

276 "name": "Developer"

277 },

278 "plugins": [

279 {323 {

280 "name": "my-plugin",324 "name": "my-plugin",

281 "source": "./my-plugin",325 "description": "Migrated from standalone configuration",

282 "description": "Plugin under development"326 "version": "1.0.0"

283 }

284 ]

285 }327 }

286 EOF

287 ```328 ```

288 </Step>329 </Step>

289 330 

290 <Step title="Install and test">331 <Step title="Copy your existing files">

291 ```bash Start Claude Code from parent directory theme={null}332 Copy your existing configurations to the plugin directory:

292 cd ..

293 claude

294 ```

295 

296 ```shell Add your development marketplace theme={null}

297 /plugin marketplace add ./dev-marketplace

298 ```

299 333 

300 ```shell Install your plugin theme={null}334 ```bash theme={null}

301 /plugin install my-plugin@dev-marketplace335 # Copy commands

302 ```336 cp -r .claude/commands my-plugin/

303 337 

304 Test your plugin components:338 # Copy agents (if any)

339 cp -r .claude/agents my-plugin/

305 340 

306 * Try your commands with `/command-name`341 # Copy skills (if any)

307 * Check that agents appear in `/agents`342 cp -r .claude/skills my-plugin/

308 * Verify hooks work as expected343 ```

309 </Step>344 </Step>

310 345 

311 <Step title="Iterate on your plugin">346 <Step title="Migrate hooks">

312 After making changes to your plugin code:347 If you have hooks in your settings, create a hooks directory:

313 348 

314 ```shell Uninstall the current version theme={null}349 ```bash theme={null}

315 /plugin uninstall my-plugin@dev-marketplace350 mkdir my-plugin/hooks

316 ```351 ```

317 352 

318 ```shell Reinstall to test changes theme={null}353 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 354 

322 Repeat this cycle as you develop and refine your plugin.355 ```json my-plugin/hooks/hooks.json theme={null}

356 {

357 "hooks": {

358 "PostToolUse": [

359 {

360 "matcher": "Write|Edit",

361 "hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npm run lint:fix" }]

362 }

363 ]

364 }

365 }

366 ```

323 </Step>367 </Step>

324</Steps>

325 368 

326<Note>369 <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/plugin-marketplaces#plugin-sources) for organization patterns.370 Load your plugin to verify everything works:

328</Note>

329 371 

330### Debug plugin issues372 ```bash theme={null}

331 373 claude --plugin-dir ./my-plugin

332If your plugin isn't working as expected:374 ```

333 

3341. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`

3352. **Test components individually**: Check each command, agent, and hook separately

3363. **Use validation and debugging tools**: See [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques

337 375 

338### Share your plugins376 Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly.

377 </Step>

378</Steps>

339 379 

340When your plugin is ready to share:380### What changes when migrating

341 381 

3421. **Add documentation**: Include a README.md with installation and usage instructions382| Standalone (`.claude/`) | Plugin |

3432. **Version your plugin**: Use semantic versioning in your `plugin.json`383| :---------------------------- | :------------------------------- |

3443. **Create or use a marketplace**: Distribute through plugin marketplaces for easy installation384| Only available in one project | Can be shared via marketplaces |

3454. **Test with others**: Have team members test the plugin before wider distribution385| Files in `.claude/commands/` | Files in `plugin-name/commands/` |

386| Hooks in `settings.json` | Hooks in `hooks/hooks.json` |

387| Must manually copy to share | Install with `/plugin install` |

346 388 

347<Note>389<Note>

348 For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).390 After migrating, you can remove the original files from `.claude/` to avoid duplicates. The plugin version will take precedence when loaded.

349</Note>391</Note>

350 392 

351***

352 

353## Next steps393## Next steps

354 394 

355Now that you understand Claude Code's plugin system, here are suggested paths for different goals:395Now that you understand Claude Code's plugin system, here are suggested paths for different goals:

356 396 

357### For plugin users397### For plugin users

358 398 

359* **Discover plugins**: Browse community marketplaces for useful tools399* [Discover and install plugins](/en/discover-plugins): browse marketplaces and install plugins

360* **Team adoption**: Set up repository-level plugins for your projects400* [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 401 

364### For plugin developers402### For plugin developers

365 403 

366* **Create your first marketplace**: [Plugin marketplaces guide](/en/plugin-marketplaces)404* [Create and distribute a marketplace](/en/plugin-marketplaces): package and share your plugins

367* **Advanced components**: Dive deeper into specific plugin components:405* [Plugins reference](/en/plugins-reference): complete technical specifications

368 * [Slash commands](/en/slash-commands) - Command development details406* Dive deeper into specific plugin components:

369 * [Subagents](/en/sub-agents) - Agent configuration and capabilities407 * [Skills](/en/skills): skill development details

370 * [Agent Skills](/en/skills) - Extend Claude's capabilities408 * [Subagents](/en/sub-agents): agent configuration and capabilities

371 * [Hooks](/en/hooks) - Event handling and automation409 * [Hooks](/en/hooks): event handling and automation

372 * [MCP](/en/mcp) - External tool integration410 * [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/plugin-marketplaces) - Creating and managing plugin catalogs

386* [Slash commands](/en/slash-commands) - Understanding custom commands

387* [Subagents](/en/sub-agents) - Creating and using specialized agents

388* [Agent Skills](/en/skills) - Extend Claude's capabilities

389* [Hooks](/en/hooks) - Automating workflows with event handlers

390* [MCP](/en/mcp) - Connecting to external tools and services

391* [Settings](/en/settings) - Configuration options for plugins

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/plugins). For plugin management across teams and communities, see [Plugin marketplaces](/en/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 

11## Plugin components reference15## Plugin components reference

12 16 

13This section documents the five types of components that plugins can provide.17This section documents the types of components that plugins can provide.

18 

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

20 26 

21**File format**: Markdown files with frontmatter27**Skill structure**:

22 28 

23For complete details on plugin command structure, invocation patterns, and features, see [Plugin commands](/en/slash-commands#plugin-commands).29```

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

44 

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

39---61---

40 62 

41# Agent Name63Detailed 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```64```

53 65 

54**Integration points**:66**Integration points**:


58* Agents can be invoked manually by users70* Agents can be invoked manually by users

59* Plugin agents work alongside built-in Claude agents71* Plugin agents work alongside built-in Claude agents

60 72 

61### Skills73For 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/skills)

90* [Agent Skills overview](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview#skill-structure)

91 74 

92### Hooks75### Hooks

93 76 


120**Available events**:103**Available events**:

121 104 

122* `PreToolUse`: Before Claude uses any tool105* `PreToolUse`: Before Claude uses any tool

123* `PostToolUse`: After Claude uses any tool106* `PostToolUse`: After Claude successfully uses any tool

107* `PostToolUseFailure`: After Claude tool execution fails

108* `PermissionRequest`: When a permission dialog is shown

124* `UserPromptSubmit`: When user submits a prompt109* `UserPromptSubmit`: When user submits a prompt

125* `Notification`: When Claude Code sends notifications110* `Notification`: When Claude Code sends notifications

126* `Stop`: When Claude attempts to stop111* `Stop`: When Claude attempts to stop

112* `SubagentStart`: When a subagent is started

127* `SubagentStop`: When a subagent attempts to stop113* `SubagentStop`: When a subagent attempts to stop

128* `SessionStart`: At the beginning of sessions114* `SessionStart`: At the beginning of sessions

129* `SessionEnd`: At the end of sessions115* `SessionEnd`: At the end of sessions

116* `TeammateIdle`: When an agent team teammate is about to go idle

117* `TaskCompleted`: When a task is being marked as completed

130* `PreCompact`: Before conversation history is compacted118* `PreCompact`: Before conversation history is compacted

131 119 

132**Hook types**:120**Hook types**:

133 121 

134* `command`: Execute shell commands or scripts122* `command`: Execute shell commands or scripts

135* `validation`: Validate file contents or project state123* `prompt`: Evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context)

136* `notification`: Send alerts or status updates124* `agent`: Run an agentic verifier with tools for complex verification tasks

137 125 

138### MCP servers126### MCP servers

139 127 


171* Server capabilities integrate seamlessly with Claude's existing tools159* Server capabilities integrate seamlessly with Claude's existing tools

172* Plugin servers can be configured independently of user MCP servers160* Plugin servers can be configured independently of user MCP servers

173 161 

162### LSP servers

163 

164<Tip>

165 Looking to use LSP plugins? Install them from the official marketplace: search for "lsp" in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace.

166</Tip>

167 

168Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase.

169 

170LSP integration provides:

171 

172* **Instant diagnostics**: Claude sees errors and warnings immediately after each edit

173* **Code navigation**: go to definition, find references, and hover information

174* **Language awareness**: type information and documentation for code symbols

175 

176**Location**: `.lsp.json` in plugin root, or inline in `plugin.json`

177 

178**Format**: JSON configuration mapping language server names to their configurations

179 

180**`.lsp.json` file format**:

181 

182```json theme={null}

183{

184 "go": {

185 "command": "gopls",

186 "args": ["serve"],

187 "extensionToLanguage": {

188 ".go": "go"

189 }

190 }

191}

192```

193 

194**Inline in `plugin.json`**:

195 

196```json theme={null}

197{

198 "name": "my-plugin",

199 "lspServers": {

200 "go": {

201 "command": "gopls",

202 "args": ["serve"],

203 "extensionToLanguage": {

204 ".go": "go"

205 }

206 }

207 }

208}

209```

210 

211**Required fields:**

212 

213| Field | Description |

214| :-------------------- | :------------------------------------------- |

215| `command` | The LSP binary to execute (must be in PATH) |

216| `extensionToLanguage` | Maps file extensions to language identifiers |

217 

218**Optional fields:**

219 

220| Field | Description |

221| :---------------------- | :-------------------------------------------------------- |

222| `args` | Command-line arguments for the LSP server |

223| `transport` | Communication transport: `stdio` (default) or `socket` |

224| `env` | Environment variables to set when starting the server |

225| `initializationOptions` | Options passed to the server during initialization |

226| `settings` | Settings passed via `workspace/didChangeConfiguration` |

227| `workspaceFolder` | Workspace folder path for the server |

228| `startupTimeout` | Max time to wait for server startup (milliseconds) |

229| `shutdownTimeout` | Max time to wait for graceful shutdown (milliseconds) |

230| `restartOnCrash` | Whether to automatically restart the server if it crashes |

231| `maxRestarts` | Maximum number of restart attempts before giving up |

232 

233<Warning>

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

235</Warning>

236 

237**Available LSP plugins:**

238 

239| Plugin | Language server | Install command |

240| :--------------- | :------------------------- | :----------------------------------------------------------------------------------------- |

241| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |

242| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |

243| `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |

244 

245Install the language server first, then install the plugin from the marketplace.

246 

247***

248 

249## Plugin installation scopes

250 

251When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:

252 

253| Scope | Settings file | Use case |

254| :-------- | :---------------------------- | :------------------------------------------------------- |

255| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |

256| `project` | `.claude/settings.json` | Team plugins shared via version control |

257| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |

258| `managed` | `managed-settings.json` | Managed plugins (read-only, update only) |

259 

260Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/en/settings#configuration-scopes).

261 

174***262***

175 263 

176## Plugin manifest schema264## Plugin manifest schema

177 265 

178The `plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.266The `.claude-plugin/plugin.json` file defines your plugin's metadata and configuration. This section documents all supported fields and options.

267 

268The manifest is optional. If omitted, Claude Code auto-discovers components in [default locations](#file-locations-reference) and derives the plugin name from the directory name. Use a manifest when you need to provide metadata or custom component paths.

179 269 

180### Complete schema270### Complete schema

181 271 


195 "keywords": ["keyword1", "keyword2"],285 "keywords": ["keyword1", "keyword2"],

196 "commands": ["./custom/commands/special.md"],286 "commands": ["./custom/commands/special.md"],

197 "agents": "./custom/agents/",287 "agents": "./custom/agents/",

288 "skills": "./custom/skills/",

198 "hooks": "./config/hooks.json",289 "hooks": "./config/hooks.json",

199 "mcpServers": "./mcp-config.json"290 "mcpServers": "./mcp-config.json",

291 "outputStyles": "./styles/",

292 "lspServers": "./.lsp.json"

200}293}

201```294```

202 295 

203### Required fields296### Required fields

204 297 

298If you include a manifest, `name` is the only required field.

299 

205| Field | Type | Description | Example |300| Field | Type | Description | Example |

206| :----- | :----- | :---------------------------------------- | :------------------- |301| :----- | :----- | :---------------------------------------- | :------------------- |

207| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |302| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |

208 303 

304This name is used for namespacing components. For example, in the UI, the

305agent `agent-creator` for the plugin with name `plugin-dev` will appear as

306`plugin-dev:agent-creator`.

307 

209### Metadata fields308### Metadata fields

210 309 

211| Field | Type | Description | Example |310| Field | Type | Description | Example |

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

213| `version` | string | Semantic version | `"2.1.0"` |312| `version` | string | Semantic version. If also set in the marketplace entry, `plugin.json` takes priority. You only need to set it in one place. | `"2.1.0"` |

214| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |313| `description` | string | Brief explanation of plugin purpose | `"Deployment automation tools"` |

215| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |314| `author` | object | Author information | `{"name": "Dev Team", "email": "dev@company.com"}` |

216| `homepage` | string | Documentation URL | `"https://docs.example.com"` |315| `homepage` | string | Documentation URL | `"https://docs.example.com"` |


221### Component path fields320### Component path fields

222 321 

223| Field | Type | Description | Example |322| Field | Type | Description | Example |

224| :----------- | :------------- | :----------------------------------- | :------------------------------------- |323| :------------- | :-------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------- |

225| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |324| `commands` | string\|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |

226| `agents` | string\|array | Additional agent files | `"./custom/agents/"` |325| `agents` | string\|array | Additional agent files | `"./custom/agents/reviewer.md"` |

227| `hooks` | string\|object | Hook config path or inline config | `"./hooks.json"` |326| `skills` | string\|array | Additional skill directories | `"./custom/skills/"` |

228| `mcpServers` | string\|object | MCP config path or inline config | `"./mcp.json"` |327| `hooks` | string\|array\|object | Hook config paths or inline config | `"./my-extra-hooks.json"` |

328| `mcpServers` | string\|array\|object | MCP config paths or inline config | `"./my-extra-mcp-config.json"` |

329| `outputStyles` | string\|array | Additional output style files/directories | `"./styles/"` |

330| `lspServers` | string\|array\|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) configs for code intelligence (go to definition, find references, etc.) | `"./.lsp.json"` |

229 331 

230### Path behavior rules332### Path behavior rules

231 333 


274 376 

275***377***

276 378 

379## Plugin caching and file resolution

380 

381For security and verification purposes, Claude Code copies plugins to a cache directory rather than using them in-place. Understanding this behavior is important when developing plugins that reference external files.

382 

383### How plugin caching works

384 

385Plugins are specified in one of two ways:

386 

387* Through `claude --plugin-dir`, for the duration of a session.

388* Through a marketplace, installed to the local plugin cache.

389 

390When you install a plugin, Claude Code locates its marketplace and the plugin's `source` field within that marketplace.

391 

392The source can be one of five types:

393 

394* Relative path: copied recursively to the plugin cache. For example, if your marketplace entry specifies `"source": "./plugins/my-plugin"`, the entire `./plugins/my-plugin` directory is copied.

395* npm - copied to the plugin cache from npm

396* pip - copied to the plugin cache from pip

397* url - any https\:// URL ending in .git

398* github - any owner/repo shorthand

399 

400### Path traversal limitations

401 

402Plugins cannot reference files outside their copied directory structure. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache.

403 

404### Working with external dependencies

405 

406If your plugin needs to access files outside its directory, you have two options:

407 

408**Option 1: Use symlinks**

409 

410Create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process:

411 

412```bash theme={null}

413# Inside your plugin directory

414ln -s /path/to/shared-utils ./shared-utils

415```

416 

417The symlinked content will be copied into the plugin cache.

418 

419**Option 2: Restructure your marketplace**

420 

421Set the plugin path to a parent directory that contains all required files, then provide the rest of the plugin manifest directly in the marketplace entry:

422 

423```json theme={null}

424{

425 "name": "my-plugin",

426 "source": "./",

427 "description": "Plugin that needs root-level access",

428 "commands": ["./plugins/my-plugin/commands/"],

429 "agents": ["./plugins/my-plugin/agents/"],

430 "strict": false

431}

432```

433 

434This approach copies the entire marketplace root, giving your plugin access to sibling directories.

435 

436<Note>

437 Symlinks that point to locations outside the plugin's logical root are followed during copying. This provides flexibility while maintaining the security benefits of the caching system.

438</Note>

439 

440***

441 

277## Plugin directory structure442## Plugin directory structure

278 443 

279### Standard plugin layout444### Standard plugin layout


282 447 

283```448```

284enterprise-plugin/449enterprise-plugin/

285├── .claude-plugin/ # Metadata directory450├── .claude-plugin/ # Metadata directory (optional)

286│ └── plugin.json # Required: plugin manifest451│ └── plugin.json # plugin manifest

287├── commands/ # Default command location452├── commands/ # Default command location

288│ ├── status.md453│ ├── status.md

289│ └── logs.md454│ └── logs.md


301│ ├── hooks.json # Main hook config466│ ├── hooks.json # Main hook config

302│ └── security-hooks.json # Additional hooks467│ └── security-hooks.json # Additional hooks

303├── .mcp.json # MCP server definitions468├── .mcp.json # MCP server definitions

469├── .lsp.json # LSP server configurations

304├── scripts/ # Hook and utility scripts470├── scripts/ # Hook and utility scripts

305│ ├── security-scan.sh471│ ├── security-scan.sh

306│ ├── format-code.py472│ ├── format-code.py


316### File locations reference482### File locations reference

317 483 

318| Component | Default Location | Purpose |484| Component | Default Location | Purpose |

319| :-------------- | :--------------------------- | :------------------------------- |485| :-------------- | :--------------------------- | :---------------------------------------------------------- |

320| **Manifest** | `.claude-plugin/plugin.json` | Required metadata file |486| **Manifest** | `.claude-plugin/plugin.json` | Plugin metadata and configuration (optional) |

321| **Commands** | `commands/` | Slash command markdown files |487| **Commands** | `commands/` | Skill Markdown files (legacy; use `skills/` for new skills) |

322| **Agents** | `agents/` | Subagent markdown files |488| **Agents** | `agents/` | Subagent Markdown files |

323| **Skills** | `skills/` | Agent Skills with SKILL.md files |489| **Skills** | `skills/` | Skills with `<name>/SKILL.md` structure |

324| **Hooks** | `hooks/hooks.json` | Hook configuration |490| **Hooks** | `hooks/hooks.json` | Hook configuration |

325| **MCP servers** | `.mcp.json` | MCP server definitions |491| **MCP servers** | `.mcp.json` | MCP server definitions |

492| **LSP servers** | `.lsp.json` | Language server configurations |

326 493 

327***494***

328 495 

329## Debugging and development tools496## CLI commands reference

330 497 

331### Debugging commands498Claude Code provides CLI commands for non-interactive plugin management, useful for scripting and automation.

499 

500### plugin install

501 

502Install a plugin from available marketplaces.

503 

504```bash theme={null}

505claude plugin install <plugin> [options]

506```

507 

508**Arguments:**

509 

510* `<plugin>`: Plugin name or `plugin-name@marketplace-name` for a specific marketplace

511 

512**Options:**

513 

514| Option | Description | Default |

515| :-------------------- | :------------------------------------------------ | :------ |

516| `-s, --scope <scope>` | Installation scope: `user`, `project`, or `local` | `user` |

517| `-h, --help` | Display help for command | |

518 

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

520 

521**Examples:**

522 

523```bash theme={null}

524# Install to user scope (default)

525claude plugin install formatter@my-marketplace

526 

527# Install to project scope (shared with team)

528claude plugin install formatter@my-marketplace --scope project

529 

530# Install to local scope (gitignored)

531claude plugin install formatter@my-marketplace --scope local

532```

533 

534### plugin uninstall

535 

536Remove an installed plugin.

537 

538```bash theme={null}

539claude plugin uninstall <plugin> [options]

540```

541 

542**Arguments:**

543 

544* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

545 

546**Options:**

547 

548| Option | Description | Default |

549| :-------------------- | :-------------------------------------------------- | :------ |

550| `-s, --scope <scope>` | Uninstall from scope: `user`, `project`, or `local` | `user` |

551| `-h, --help` | Display help for command | |

552 

553**Aliases:** `remove`, `rm`

554 

555### plugin enable

556 

557Enable a disabled plugin.

558 

559```bash theme={null}

560claude plugin enable <plugin> [options]

561```

562 

563**Arguments:**

564 

565* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

566 

567**Options:**

568 

569| Option | Description | Default |

570| :-------------------- | :--------------------------------------------- | :------ |

571| `-s, --scope <scope>` | Scope to enable: `user`, `project`, or `local` | `user` |

572| `-h, --help` | Display help for command | |

573 

574### plugin disable

575 

576Disable a plugin without uninstalling it.

577 

578```bash theme={null}

579claude plugin disable <plugin> [options]

580```

581 

582**Arguments:**

583 

584* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

585 

586**Options:**

587 

588| Option | Description | Default |

589| :-------------------- | :---------------------------------------------- | :------ |

590| `-s, --scope <scope>` | Scope to disable: `user`, `project`, or `local` | `user` |

591| `-h, --help` | Display help for command | |

592 

593### plugin update

332 594 

333Use `claude --debug` to see plugin loading details:595Update a plugin to the latest version.

334 596 

335```bash theme={null}597```bash theme={null}

336claude --debug598claude plugin update <plugin> [options]

337```599```

338 600 

601**Arguments:**

602 

603* `<plugin>`: Plugin name or `plugin-name@marketplace-name`

604 

605**Options:**

606 

607| Option | Description | Default |

608| :-------------------- | :-------------------------------------------------------- | :------ |

609| `-s, --scope <scope>` | Scope to update: `user`, `project`, `local`, or `managed` | `user` |

610| `-h, --help` | Display help for command | |

611 

612***

613 

614## Debugging and development tools

615 

616### Debugging commands

617 

618Use `claude --debug` (or `/debug` within the TUI) to see plugin loading details:

619 

339This shows:620This shows:

340 621 

341* Which plugins are being loaded622* Which plugins are being loaded


346### Common issues627### Common issues

347 628 

348| Issue | Cause | Solution |629| Issue | Cause | Solution |

349| :--------------------- | :------------------------------ | :--------------------------------------------------- |630| :---------------------------------- | :------------------------------ | :-------------------------------------------------------------------------------- |

350| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax |631| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax with `claude plugin validate` or `/plugin validate` |

351| Commands not appearing | Wrong directory structure | Ensure `commands/` at root, not in `.claude-plugin/` |632| 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` |633| 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 |634| 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 `./` |635| Path errors | Absolute paths used | All paths must be relative and start with `./` |

636| LSP `Executable not found in $PATH` | Language server not installed | Install the binary (e.g., `npm install -g typescript-language-server typescript`) |

637 

638### Example error messages

639 

640**Manifest validation errors**:

641 

642* `Invalid JSON syntax: Unexpected token } in JSON at position 142`: check for missing commas, extra commas, or unquoted strings

643* `Plugin has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: name: Required`: a required field is missing

644* `Plugin has a corrupt manifest file at .claude-plugin/plugin.json. JSON parse error: ...`: JSON syntax error

645 

646**Plugin loading errors**:

647 

648* `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

649* `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

650* `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

651 

652### Hook troubleshooting

653 

654**Hook script not executing**:

655 

6561. Check the script is executable: `chmod +x ./scripts/your-script.sh`

6572. Verify the shebang line: First line should be `#!/bin/bash` or `#!/usr/bin/env bash`

6583. Check the path uses `${CLAUDE_PLUGIN_ROOT}`: `"command": "${CLAUDE_PLUGIN_ROOT}/scripts/your-script.sh"`

6594. Test the script manually: `./scripts/your-script.sh`

660 

661**Hook not triggering on expected events**:

662 

6631. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse`

6642. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations

6653. Confirm the hook type is valid: `command`, `prompt`, or `agent`

666 

667### MCP server troubleshooting

668 

669**Server not starting**:

670 

6711. Check the command exists and is executable

6722. Verify all paths use `${CLAUDE_PLUGIN_ROOT}` variable

6733. Check the MCP server logs: `claude --debug` shows initialization errors

6744. Test the server manually outside of Claude Code

675 

676**Server tools not appearing**:

677 

6781. Ensure the server is properly configured in `.mcp.json` or `plugin.json`

6792. Verify the server implements the MCP protocol correctly

6803. Check for connection timeouts in debug output

681 

682### Directory structure mistakes

683 

684**Symptoms**: Plugin loads but components (commands, agents, hooks) are missing.

685 

686**Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`.

687 

688```

689my-plugin/

690├── .claude-plugin/

691│ └── plugin.json ← Only manifest here

692├── commands/ ← At root level

693├── agents/ ← At root level

694└── hooks/ ← At root level

695```

696 

697If your components are inside `.claude-plugin/`, move them to the plugin root.

698 

699**Debug checklist**:

700 

7011. Run `claude --debug` and look for "loading plugin" messages

7022. Check that each component directory is listed in the debug output

7033. Verify file permissions allow reading the plugin files

355 704 

356***705***

357 706 


362Follow semantic versioning for plugin releases:711Follow semantic versioning for plugin releases:

363 712 

364```json theme={null}713```json theme={null}

714{

715 "name": "my-plugin",

716 "version": "2.1.0"

717}

718```

719 

720**Version format**: `MAJOR.MINOR.PATCH`

721 

722* **MAJOR**: Breaking changes (incompatible API changes)

723* **MINOR**: New features (backward-compatible additions)

724* **PATCH**: Bug fixes (backward-compatible fixes)

725 

726**Best practices**:

727 

728* Start at `1.0.0` for your first stable release

729* Update the version in `plugin.json` before distributing changes

730* Document changes in a `CHANGELOG.md` file

731* Use pre-release versions like `2.0.0-beta.1` for testing

732 

733***

365 734 

366## See also735## See also

367 736 

368- [Plugins](/en/plugins) - Tutorials and practical usage737* [Plugins](/en/plugins) - Tutorials and practical usage

369- [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces738* [Plugin marketplaces](/en/plugin-marketplaces) - Creating and managing marketplaces

370- [Slash commands](/en/slash-commands) - Command development details739* [Skills](/en/skills) - Skill development details

371- [Subagents](/en/sub-agents) - Agent configuration and capabilities740* [Subagents](/en/sub-agents) - Agent configuration and capabilities

372- [Agent Skills](/en/skills) - Extend Claude's capabilities741* [Hooks](/en/hooks) - Event handling and automation

373- [Hooks](/en/hooks) - Event handling and automation742* [MCP](/en/mcp) - External tool integration

374- [MCP](/en/mcp) - External tool integration743* [Settings](/en/settings) - Configuration options for plugins

375- [Settings](/en/settings) - Configuration options for plugins

376```

quickstart.md +76 −69

Details

1> ## Documentation Index

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

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

4 

1# Quickstart5# Quickstart

2 6 

3> Welcome to Claude Code!7> Welcome to Claude Code!


10 14 

11* A terminal or command prompt open15* A terminal or command prompt open

12* A code project to work with16* A code project to work with

13* A [Claude.ai](https://claude.ai) (recommended) or [Claude Console](https://console.anthropic.com/) account17* A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise), [Claude Console](https://console.anthropic.com/) account, or access through a [supported cloud provider](/en/third-party-integrations)

18 

19<Note>

20 This guide covers the terminal CLI. Claude Code is also available on the [web](https://claude.ai/code), as a [desktop app](/en/desktop), in [VS Code](/en/vs-code) and [JetBrains IDEs](/en/jetbrains), in [Slack](/en/slack), and in CI/CD with [GitHub Actions](/en/github-actions) and [GitLab](/en/gitlab-ci-cd). See [all interfaces](/en/overview#use-claude-code-everywhere).

21</Note>

14 22 

15## Step 1: Install Claude Code23## Step 1: Install Claude Code

16 24 


18 26 

19<Tabs>27<Tabs>

20 <Tab title="Native Install (Recommended)">28 <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:**29 **macOS, Linux, WSL:**

28 30 

29 ```bash theme={null}31 ```bash theme={null}


41 ```batch theme={null}43 ```batch theme={null}

42 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd44 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

43 ```45 ```

44 </Tab>

45 46 

46 <Tab title="NPM">47 <Info>

47 If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/):48 Native installations automatically update in the background to keep you on the latest version.

49 </Info>

50 </Tab>

48 51 

52 <Tab title="Homebrew">

49 ```sh theme={null}53 ```sh theme={null}

50 npm install -g @anthropic-ai/claude-code54 brew install --cask claude-code

51 ```55 ```

56 

57 <Info>

58 Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

59 </Info>

60 </Tab>

61 

62 <Tab title="WinGet">

63 ```powershell theme={null}

64 winget install Anthropic.ClaudeCode

65 ```

66 

67 <Info>

68 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

69 </Info>

52 </Tab>70 </Tab>

53</Tabs>71</Tabs>

54 72 


66# Follow the prompts to log in with your account84# Follow the prompts to log in with your account

67```85```

68 86 

69You can log in using either account type:87You can log in using any of these account types:

70 88 

71* [Claude.ai](https://claude.ai) (subscription plans - recommended)89* [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended)

72* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits)90* [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits). On first login, a "Claude Code" workspace is automatically created in the Console for centralized cost tracking.

91* [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) (enterprise cloud providers)

73 92 

74Once logged in, your credentials are stored and you won't need to log in again.93Once logged in, your credentials are stored and you won't need to log in again. To switch accounts later, use the `/login` command.

75 

76<Note>

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 94 

84## Step 3: Start your first session95## Step 3: Start your first session

85 96 


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.104You'll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.

94 105 

95<Tip>106<Tip>

96 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/iam#credential-management).107 After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/en/authentication#credential-management).

97</Tip>108</Tip>

98 109 

99## Step 4: Ask your first question110## Step 4: Ask your first question


101Let's start with understanding your codebase. Try one of these commands:112Let's start with understanding your codebase. Try one of these commands:

102 113 

103```114```

104> what does this project do?115what does this project do?

105```116```

106 117 

107Claude will analyze your files and provide a summary. You can also ask more specific questions:118Claude will analyze your files and provide a summary. You can also ask more specific questions:

108 119 

109```120```

110> what technologies does this project use?121what technologies does this project use?

111```122```

112 123 

113```124```

114> where is the main entry point?125where is the main entry point?

115```126```

116 127 

117```128```

118> explain the folder structure129explain the folder structure

119```130```

120 131 

121You can also ask Claude about its own capabilities:132You can also ask Claude about its own capabilities:

122 133 

123```134```

124> what can Claude Code do?135what can Claude Code do?

125```136```

126 137 

127```138```

128> how do I use slash commands in Claude Code?139how do I create custom skills in Claude Code?

129```140```

130 141 

131```142```

132> can Claude Code work with Docker?143can Claude Code work with Docker?

133```144```

134 145 

135<Note>146<Note>


141Now let's make Claude Code do some actual coding. Try a simple task:152Now let's make Claude Code do some actual coding. Try a simple task:

142 153 

143```154```

144> add a hello world function to the main file155add a hello world function to the main file

145```156```

146 157 

147Claude Code will:158Claude Code will:


160Claude Code makes Git operations conversational:171Claude Code makes Git operations conversational:

161 172 

162```173```

163> what files have I changed?174what files have I changed?

164```175```

165 176 

166```177```

167> commit my changes with a descriptive message178commit my changes with a descriptive message

168```179```

169 180 

170You can also prompt for more complex Git operations:181You can also prompt for more complex Git operations:

171 182 

172```183```

173> create a new branch called feature/quickstart184create a new branch called feature/quickstart

174```185```

175 186 

176```187```

177> show me the last 5 commits188show me the last 5 commits

178```189```

179 190 

180```191```

181> help me resolve merge conflicts192help me resolve merge conflicts

182```193```

183 194 

184## Step 7: Fix a bug or add a feature195## Step 7: Fix a bug or add a feature


188Describe what you want in natural language:199Describe what you want in natural language:

189 200 

190```201```

191> add input validation to the user registration form202add input validation to the user registration form

192```203```

193 204 

194Or fix existing issues:205Or fix existing issues:

195 206 

196```207```

197> there's a bug where users can submit empty forms - fix it208there's a bug where users can submit empty forms - fix it

198```209```

199 210 

200Claude Code will:211Claude Code will:


211**Refactor code**222**Refactor code**

212 223 

213```224```

214> refactor the authentication module to use async/await instead of callbacks225refactor the authentication module to use async/await instead of callbacks

215```226```

216 227 

217**Write tests**228**Write tests**

218 229 

219```230```

220> write unit tests for the calculator functions231write unit tests for the calculator functions

221```232```

222 233 

223**Update documentation**234**Update documentation**

224 235 

225```236```

226> update the README with installation instructions237update the README with installation instructions

227```238```

228 239 

229**Code review**240**Code review**

230 241 

231```242```

232> review my changes and suggest improvements243review my changes and suggest improvements

233```244```

234 245 

235<Tip>246<Tip>


241Here are the most important commands for daily use:252Here are the most important commands for daily use:

242 253 

243| Command | What it does | Example |254| Command | What it does | Example |

244| ------------------- | --------------------------------- | ----------------------------------- |255| ------------------- | ------------------------------------------------------ | ----------------------------------- |

245| `claude` | Start interactive mode | `claude` |256| `claude` | Start interactive mode | `claude` |

246| `claude "task"` | Run a one-time task | `claude "fix the build error"` |257| `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"` |258| `claude -p "query"` | Run one-off query, then exit | `claude -p "explain this function"` |

248| `claude -c` | Continue most recent conversation | `claude -c` |259| `claude -c` | Continue most recent conversation in current directory | `claude -c` |

249| `claude -r` | Resume a previous conversation | `claude -r` |260| `claude -r` | Resume a previous conversation | `claude -r` |

250| `claude commit` | Create a Git commit | `claude commit` |261| `claude commit` | Create a Git commit | `claude commit` |

251| `/clear` | Clear conversation history | `> /clear` |262| `/clear` | Clear conversation history | `/clear` |

252| `/help` | Show available commands | `> /help` |263| `/help` | Show available commands | `/help` |

253| `exit` or Ctrl+C | Exit Claude Code | `> exit` |264| `exit` or Ctrl+C | Exit Claude Code | `exit` |

254 265 

255See the [CLI reference](/en/cli-reference) for a complete list of commands.266See the [CLI reference](/en/cli-reference) for a complete list of commands.

256 267 

257## Pro tips for beginners268## Pro tips for beginners

258 269 

270For more, see [best practices](/en/best-practices) and [common workflows](/en/common-workflows).

271 

259<AccordionGroup>272<AccordionGroup>

260 <Accordion title="Be specific with your requests">273 <Accordion title="Be specific with your requests">

261 Instead of: "fix the bug"274 Instead of: "fix the bug"


267 Break complex tasks into steps:280 Break complex tasks into steps:

268 281 

269 ```282 ```

270 > 1. create a new database table for user profiles283 1. create a new database table for user profiles

271 ```284 2. create an API endpoint to get and update user profiles

272 285 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 ```286 ```

280 </Accordion>287 </Accordion>

281 288 


283 Before making changes, let Claude understand your code:290 Before making changes, let Claude understand your code:

284 291 

285 ```292 ```

286 > analyze the database schema293 analyze the database schema

287 ```294 ```

288 295 

289 ```296 ```

290 > build a dashboard showing products that are most frequently returned by our UK customers297 build a dashboard showing products that are most frequently returned by our UK customers

291 ```298 ```

292 </Accordion>299 </Accordion>

293 300 


295 * Press `?` to see all available keyboard shortcuts302 * Press `?` to see all available keyboard shortcuts

296 * Use Tab for command completion303 * Use Tab for command completion

297 * Press ↑ for command history304 * Press ↑ for command history

298 * Type `/` to see all slash commands305 * Type `/` to see all commands and skills

299 </Accordion>306 </Accordion>

300</AccordionGroup>307</AccordionGroup>

301 308 


303 310 

304Now that you've learned the basics, explore more advanced features:311Now that you've learned the basics, explore more advanced features:

305 312 

306<CardGroup cols={3}>313<CardGroup cols={2}>

307 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">314 <Card title="How Claude Code works" icon="microchip" href="/en/how-claude-code-works">

308 Step-by-step guides for common tasks315 Understand the agentic loop, built-in tools, and how Claude Code interacts with your project

309 </Card>316 </Card>

310 317 

311 <Card title="CLI reference" icon="terminal" href="/en/cli-reference">318 <Card title="Best practices" icon="star" href="/en/best-practices">

312 Master all commands and options319 Get better results with effective prompting and project setup

313 </Card>320 </Card>

314 321 

315 <Card title="Configuration" icon="gear" href="/en/settings">322 <Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">

316 Customize Claude Code for your workflow323 Step-by-step guides for common tasks

317 </Card>324 </Card>

318 325 

319 <Card title="Claude Code on the web" icon="cloud" href="/en/claude-code-on-the-web">326 <Card title="Extend Claude Code" icon="puzzle-piece" href="/en/features-overview">

320 Run tasks asynchronously in the cloud327 Customize with CLAUDE.md, skills, hooks, MCP, and more

321 </Card>328 </Card>

322</CardGroup>329</CardGroup>

323 330 

sandboxing.md +65 −9

Details

1> ## Documentation Index

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

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

4 

1# Sandboxing5# Sandboxing

2 6 

3> Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution.7> Learn how Claude Code's sandboxed bash tool provides filesystem and network isolation for safer, more autonomous agent execution.


51 55 

52The sandboxed bash tool leverages operating system security primitives:56The sandboxed bash tool leverages operating system security primitives:

53 57 

54* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation

55* **macOS**: Uses Seatbelt for sandbox enforcement58* **macOS**: Uses Seatbelt for sandbox enforcement

59* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation

60* **WSL2**: Uses bubblewrap, same as Linux

61 

62WSL1 is not supported because bubblewrap requires kernel features only available in WSL2.

56 63 

57These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries.64These OS-level restrictions ensure that all child processes spawned by Claude Code's commands inherit the same security boundaries.

58 65 

59## Getting started66## Getting started

60 67 

68### Prerequisites

69 

70On **macOS**, sandboxing works out of the box using the built-in Seatbelt framework.

71 

72On **Linux and WSL2**, install the required packages first:

73 

74<Tabs>

75 <Tab title="Ubuntu/Debian">

76 ```bash theme={null}

77 sudo apt-get install bubblewrap socat

78 ```

79 </Tab>

80 

81 <Tab title="Fedora">

82 ```bash theme={null}

83 sudo dnf install bubblewrap socat

84 ```

85 </Tab>

86</Tabs>

87 

61### Enable sandboxing88### Enable sandboxing

62 89 

63You can enable sandboxing by running the `/sandbox` slash command:90You can enable sandboxing by running the `/sandbox` command:

64 91 

65```92```

66> /sandbox93> /sandbox

67```94```

68 95 

69This activates the sandboxed bash tool with default settings, allowing access to your current working directory while blocking access to sensitive system locations.96This opens a menu where you can choose between sandbox modes. If required dependencies are missing (such as `bubblewrap` or `socat` on Linux), the menu displays installation instructions for your platform.

97 

98### Sandbox modes

99 

100Claude Code offers two sandbox modes:

101 

102**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 ask/deny rules you've configured are always respected.

103 

104**Regular permissions mode**: All bash commands go through the standard permission flow, even when sandboxed. This provides more control but requires more approvals.

105 

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

107 

108<Info>

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

110</Info>

70 111 

71### Configure sandboxing112### Configure sandboxing

72 113 


96 137 

97* Cannot modify critical config files such as `~/.bashrc`138* Cannot modify critical config files such as `~/.bashrc`

98* Cannot modify system-level files in `/bin/`139* Cannot modify system-level files in `/bin/`

99* Cannot read files that are denied in your [Claude permission settings](/en/iam#configuring-permissions)140* Cannot read files that are denied in your [Claude permission settings](/en/permissions#manage-permissions)

100 141 

101**Network protection:**142**Network protection:**

102 143 


141 182 

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.183* 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.184* Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files.

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.185* Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used in cases where additional isolation is otherwise enforced.

186 

187## How sandboxing relates to permissions

188 

189Sandboxing and [permissions](/en/permissions) are complementary security layers that work together:

190 

191* **Permissions** control which tools Claude Code can use and are evaluated before any tool runs. They apply to all tools: Bash, Read, Edit, WebFetch, MCP, and others.

192* **Sandboxing** provides OS-level enforcement that restricts what Bash commands can access at the filesystem and network level. It applies only to Bash commands and their child processes.

193 

194Filesystem and network restrictions are configured through permission rules, not sandbox settings:

195 

196* Use `Read` and `Edit` deny rules to block access to specific files or directories

197* Use `WebFetch` allow/deny rules to control domain access

198* Use sandbox `allowedDomains` to control which domains Bash commands can reach

199 

200This [repository](https://github.com/anthropics/claude-code/tree/main/examples/settings) includes starter settings configurations for common deployment scenarios, including sandbox-specific examples. Use these as starting points and adjust them to fit your needs.

145 201 

146## Advanced usage202## Advanced usage

147 203 


169 225 

170The sandboxed bash tool works alongside:226The sandboxed bash tool works alongside:

171 227 

172* **IAM policies**: Combine with [permission settings](/en/iam) for defense-in-depth228* **Permission rules**: Combine with [permission settings](/en/permissions) for defense-in-depth

173* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation229* **Development containers**: Use with [devcontainers](/en/devcontainer) for additional isolation

174* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)230* **Enterprise policies**: Enforce sandbox configurations through [managed settings](/en/settings#settings-precedence)

175 231 


195 251 

196* **Performance overhead**: Minimal, but some filesystem operations may be slightly slower252* **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 sandbox253* **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox

198* **Platform support**: Currently supports Linux and macOS; Windows support planned254* **Platform support**: Supports macOS, Linux, and WSL2. WSL1 is not supported. Native Windows support is planned.

199 255 

200## See also256## See also

201 257 

202* [Security](/en/security) - Comprehensive security features and best practices258* [Security](/en/security) - Comprehensive security features and best practices

203* [IAM](/en/iam) - Permission configuration and access control259* [Permissions](/en/permissions) - Permission configuration and access control

204* [Settings](/en/settings) - Complete configuration reference260* [Settings](/en/settings) - Complete configuration reference

205* [CLI reference](/en/cli-reference) - Command-line options including `-sb`261* [CLI reference](/en/cli-reference) - Command-line options

security.md +10 −6

Details

1> ## Documentation Index

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

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

4 

1# Security5# Security

2 6 

3> Learn about Claude Code's security safeguards and best practices for safe usage.7> Learn about Claude Code's security safeguards and best practices for safe usage.


14 18 

15We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.19We designed Claude Code to be transparent and secure. For example, we require approval for bash commands before executing them, giving you direct control. This approach enables users and organizations to configure permissions directly.

16 20 

17For detailed permission configuration, see [Identity and Access Management](/en/iam).21For detailed permission configuration, see [Permissions](/en/permissions).

18 22 

19### Built-in protections23### Built-in protections

20 24 


38* **Permission system**: Sensitive operations require explicit approval42* **Permission system**: Sensitive operations require explicit approval

39* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request43* **Context-aware analysis**: Detects potentially harmful instructions by analyzing the full request

40* **Input sanitization**: Prevents command injection by processing user inputs44* **Input sanitization**: Prevents command injection by processing user inputs

41* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/iam#tool-specific-permission-rules)45* **Command blocklist**: Blocks risky commands that fetch arbitrary content from the web like `curl` and `wget` by default. When explicitly allowed, be aware of [permission pattern limitations](/en/permissions#tool-specific-permission-rules)

42 46 

43### Privacy safeguards47### Privacy safeguards

44 48 


59* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted63* **Command injection detection**: Suspicious bash commands require manual approval even if previously allowlisted

60* **Fail-closed matching**: Unmatched commands default to requiring manual approval64* **Fail-closed matching**: Unmatched commands default to requiring manual approval

61* **Natural language descriptions**: Complex bash commands include explanations for user understanding65* **Natural language descriptions**: Complex bash commands include explanations for user understanding

62* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/iam#credential-management)66* **Secure credential storage**: API keys and tokens are encrypted. See [Credential Management](/en/authentication#credential-management)

63 67 

64<Warning>68<Warning>

65 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.69 **Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20\(WebDAV\)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.


87 91 

88## IDE security92## IDE security

89 93 

90See [here](/en/vs-code#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 


113 117 

114### Team security118### Team security

115 119 

116* Use [enterprise managed policies](/en/iam#enterprise-managed-policy-settings) to enforce organizational standards120* Use [managed settings](/en/permissions#managed-settings) to enforce organizational standards

117* Share approved permission configurations through version control121* Share approved permission configurations through version control

118* Train team members on security best practices122* Train team members on security best practices

119* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)123* Monitor Claude Code usage through [OpenTelemetry metrics](/en/monitoring-usage)


130## Related resources134## Related resources

131 135 

132* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands136* [Sandboxing](/en/sandboxing) - Filesystem and network isolation for bash commands

133* [Identity and Access Management](/en/iam) - Configure permissions and access controls137* [Permissions](/en/permissions) - Configure permissions and access controls

134* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity138* [Monitoring usage](/en/monitoring-usage) - Track and audit Claude Code activity

135* [Development containers](/en/devcontainer) - Secure, isolated environments139* [Development containers](/en/devcontainer) - Secure, isolated environments

136* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance140* [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance

settings.md +653 −127

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** | 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/*.local.*` files | 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/` | — |

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 our official mechanism for configuring Claude


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 `managed-settings.json` and `managed-mcp.json` files that can be deployed to system directories:

18 managed policy settings**. These take precedence over user and project87 

19 settings. System administrators can deploy policies to:88 * macOS: `/Library/Application Support/ClaudeCode/`

20 * macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`89 * Linux and WSL: `/etc/claude-code/`

21 * Linux and WSL: `/etc/claude-code/managed-settings.json`90 * Windows: `C:\Program Files\ClaudeCode\`

22 * Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`91 

23* Enterprise deployments can also configure **managed MCP servers** that override92 <Note>

24 user-configured servers. See [Enterprise MCP configuration](/en/mcp#enterprise-mcp-configuration):93 These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.

25 * macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`94 </Note>

26 * Linux and WSL: `/etc/claude-code/managed-mcp.json`95 

27 * Windows: `C:\ProgramData\ClaudeCode\managed-mcp.json`96 See [Managed settings](/en/permissions#managed-settings) and [Managed MCP configuration](/en/mcp#managed-mcp-configuration) for details.

97 

98 <Note>

99 Managed deployments can also restrict **plugin marketplace additions** using

100 `strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions).

101 </Note>

102* **Other configuration** is stored in `~/.claude.json`. This file contains your preferences (theme, notification settings, editor mode), OAuth session, [MCP server](/en/mcp) configurations for user and local scopes, per-project state (allowed tools, trust settings), and various caches. Project-scoped MCP servers are stored separately in `.mcp.json`.

103 

104<Note>

105 Claude Code automatically creates timestamped backups of configuration files and retains the five most recent backups to prevent data loss.

106</Note>

28 107 

29```JSON Example settings.json theme={null}108```JSON Example settings.json theme={null}

30{109{

110 "$schema": "https://json.schemastore.org/claude-code-settings.json",

31 "permissions": {111 "permissions": {

32 "allow": [112 "allow": [

33 "Bash(npm run lint)",113 "Bash(npm run lint)",

34 "Bash(npm run test:*)",114 "Bash(npm run test *)",

35 "Read(~/.zshrc)"115 "Read(~/.zshrc)"

36 ],116 ],

37 "deny": [117 "deny": [

38 "Bash(curl:*)",118 "Bash(curl *)",

39 "Read(./.env)",119 "Read(./.env)",

40 "Read(./.env.*)",120 "Read(./.env.*)",

41 "Read(./secrets/**)"121 "Read(./secrets/**)"


53}133}

54```134```

55 135 

136The `$schema` line in the example above points to the [official JSON schema](https://json.schemastore.org/claude-code-settings.json) for Claude Code settings. Adding it to your `settings.json` enables autocomplete and inline validation in VS Code, Cursor, and any other editor that supports JSON schema validation.

137 

56### Available settings138### Available settings

57 139 

58`settings.json` supports a number of options:140`settings.json` supports a number of options:

59 141 

60| Key | Description | Example |142| Key | Description | Example |

61| :--------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------- |143| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------- |

62| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |144| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |

63| `cleanupPeriodDays` | How long to locally retain chat transcripts based on last activity date (default: 30 days) | `20` |145| `cleanupPeriodDays` | Sessions inactive for longer than this period are deleted at startup. Setting to `0` immediately deletes all sessions. (default: 30 days) | `20` |

64| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |146| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |

65| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |147| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |

66| `includeCoAuthoredBy` | Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |148| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |

149| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |

67| `permissions` | See table below for structure of permissions. | |150| `permissions` | See table below for structure of permissions. | |

68| `hooks` | Configure custom commands to run before or after tool executions. See [hooks documentation](/en/hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` |151| `hooks` | Configure custom commands to run at lifecycle events. See [hooks documentation](/en/hooks) for format | See [hooks](/en/hooks) |

69| `disableAllHooks` | Disable all [hooks](/en/hooks) | `true` |152| `disableAllHooks` | Disable all [hooks](/en/hooks) and any custom [status line](/en/statusline) | `true` |

153| `allowManagedHooksOnly` | (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See [Hook configuration](#hook-configuration) | `true` |

154| `allowManagedPermissionRulesOnly` | (Managed settings only) Prevent user and project settings from defining `allow`, `ask`, or `deny` permission rules. Only rules in managed settings apply. See [Managed-only settings](/en/permissions#managed-only-settings) | `true` |

70| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` |155| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` |

71| `statusLine` | Configure a custom status line to display context. See [statusLine documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |156| `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically (see [Dynamic headers](/en/monitoring-usage#dynamic-headers)) | `/bin/generate_otel_headers.sh` |

157| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |

158| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |

159| `respectGitignore` | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions | `false` |

72| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/en/output-styles) | `"Explanatory"` |160| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/en/output-styles) | `"Explanatory"` |

73| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |161| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |

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

75| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |163| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |

76| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |164| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |

77| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |165| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |

78| `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/mcp#enterprise-mcp-configuration) | `[{ "serverName": "github" }]` |166| `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" }]` |

79| `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/mcp#enterprise-mcp-configuration) | `[{ "serverName": "filesystem" }]` |167| `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" }]` |

168| `strictKnownMarketplaces` | When set in managed-settings.json, allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Applies to marketplace additions only. See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |

80| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |169| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |

81| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |170| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |

171| `alwaysThinkingEnabled` | Enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) by default for all sessions. Typically configured via the `/config` command rather than editing directly | `true` |

172| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |

173| `showTurnDuration` | Show turn duration messages after responses (e.g., "Cooked for 1m 6s"). Set to `false` to hide these messages | `true` |

174| `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"]}` |

175| `language` | Configure Claude's preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default | `"japanese"` |

176| `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` |

177| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |

178| `terminalProgressBarEnabled` | Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: `true`) | `false` |

179| `prefersReducedMotion` | Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility | `true` |

180| `teammateMode` | How [agent team](/en/agent-teams) teammates display: `auto` (picks split panes in tmux or iTerm2, in-process otherwise), `in-process`, or `tmux`. See [set up agent teams](/en/agent-teams#set-up-agent-teams) | `"in-process"` |

82 181 

83### Permission settings182### Permission settings

84 183 

85| Keys | Description | Example |184| Keys | Description | Example |

86| :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------- |185| :----------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------- |

87| `allow` | Array of [permission rules](/en/iam#configuring-permissions) to allow tool use. **Note:** Bash rules use prefix matching, not regex | `[ "Bash(git diff:*)" ]` |186| `allow` | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details | `[ "Bash(git diff *)" ]` |

88| `ask` | Array of [permission rules](/en/iam#configuring-permissions) to ask for confirmation upon tool use. | `[ "Bash(git push:*)" ]` |187| `ask` | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below | `[ "Bash(git push *)" ]` |

89| `deny` | Array of [permission rules](/en/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/iam#tool-specific-permission-rules)) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` |188| `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/**)" ]` |

90| `additionalDirectories` | Additional [working directories](/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` |189| `additionalDirectories` | Additional [working directories](/en/permissions#working-directories) that Claude has access to | `[ "../docs/" ]` |

91| `defaultMode` | Default [permission mode](/en/iam#permission-modes) when opening Claude Code | `"acceptEdits"` |190| `defaultMode` | Default [permission mode](/en/permissions#permission-modes) when opening Claude Code | `"acceptEdits"` |

92| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed policy settings](/en/iam#enterprise-managed-policy-settings) | `"disable"` |191| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed settings](/en/permissions#managed-settings) | `"disable"` |

192 

193### Permission rule syntax

194 

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

196 

197Quick examples:

198 

199| Rule | Effect |

200| :----------------------------- | :--------------------------------------- |

201| `Bash` | Matches all Bash commands |

202| `Bash(npm run *)` | Matches commands starting with `npm run` |

203| `Read(./.env)` | Matches reading the `.env` file |

204| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |

205 

206For the complete rule syntax reference, including wildcard behavior, tool-specific patterns for Read, Edit, WebFetch, MCP, and Task rules, and security limitations of Bash patterns, see [Permission rule syntax](/en/permissions#permission-rule-syntax).

93 207 

94### Sandbox settings208### Sandbox settings

95 209 


98**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.212**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.

99 213 

100| Keys | Description | Example |214| Keys | Description | Example |

101| :-------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------ |215| :---------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------ |

102| `enabled` | Enable bash sandboxing (macOS/Linux only). Default: false | `true` |216| `enabled` | Enable bash sandboxing (macOS, Linux, and WSL2). Default: false | `true` |

103| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |217| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |

104| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |218| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |

105| `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` |219| `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` |

106| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |220| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |

107| `network.allowLocalBinding` | Allow binding to localhost ports (MacOS only). Default: false | `true` |221| `network.allowAllUnixSockets` | Allow all Unix socket connections in sandbox. Default: false | `true` |

222| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |

223| `network.allowedDomains` | Array of domains to allow for outbound network traffic. Supports wildcards (e.g., `*.example.com`). | `["github.com", "*.npmjs.org"]` |

108| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |224| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |

109| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |225| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |

110| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux only). **Reduces security.** Default: false | `true` |226| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux and WSL2 only). **Reduces security.** Default: false | `true` |

111 227 

112**Configuration example:**228**Configuration example:**

113 229 


118 "autoAllowBashIfSandboxed": true,234 "autoAllowBashIfSandboxed": true,

119 "excludedCommands": ["docker"],235 "excludedCommands": ["docker"],

120 "network": {236 "network": {

237 "allowedDomains": ["github.com", "*.npmjs.org", "registry.yarnpkg.com"],

121 "allowUnixSockets": [238 "allowUnixSockets": [

122 "/var/run/docker.sock"239 "/var/run/docker.sock"

123 ],240 ],


133}250}

134```251```

135 252 

136**Filesystem access** is controlled via Read/Edit permissions:253**Filesystem and network restrictions** use standard permission rules:

254 

255* Use `Read` deny rules to block Claude from reading specific files or directories

256* Use `Edit` allow rules to let Claude write to directories beyond the current working directory

257* Use `Edit` deny rules to block writes to specific paths

258* Use `WebFetch` allow/deny rules to control which network domains Claude can access

259 

260### Attribution settings

261 

262Claude Code adds attribution to git commits and pull requests. These are configured separately:

263 

264* Commits use [git trailers](https://git-scm.com/docs/git-interpret-trailers) (like `Co-Authored-By`) by default, which can be customized or disabled

265* Pull request descriptions are plain text

266 

267| Keys | Description |

268| :------- | :----------------------------------------------------------------------------------------- |

269| `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution |

270| `pr` | Attribution for pull request descriptions. Empty string hides pull request attribution |

271 

272**Default commit attribution:**

273 

274```

275🤖 Generated with [Claude Code](https://claude.com/claude-code)

276 

277 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

278```

279 

280**Default pull request attribution:**

281 

282```

283🤖 Generated with [Claude Code](https://claude.com/claude-code)

284```

285 

286**Example:**

287 

288```json theme={null}

289{

290 "attribution": {

291 "commit": "Generated with AI\n\nCo-Authored-By: AI <ai@example.com>",

292 "pr": ""

293 }

294}

295```

296 

297<Note>

298 The `attribution` setting takes precedence over the deprecated `includeCoAuthoredBy` setting. To hide all attribution, set `commit` and `pr` to empty strings.

299</Note>

300 

301### File suggestion settings

302 

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

304 

305```json theme={null}

306{

307 "fileSuggestion": {

308 "type": "command",

309 "command": "~/.claude/file-suggestion.sh"

310 }

311}

312```

313 

314The command runs with the same environment variables as [hooks](/en/hooks), including `CLAUDE_PROJECT_DIR`. It receives JSON via stdin with a `query` field:

315 

316```json theme={null}

317{"query": "src/comp"}

318```

319 

320Output newline-separated file paths to stdout (currently limited to 15):

321 

322```

323src/components/Button.tsx

324src/components/Modal.tsx

325src/components/Form.tsx

326```

327 

328**Example:**

329 

330```bash theme={null}

331#!/bin/bash

332query=$(cat | jq -r '.query')

333your-repo-file-index --query "$query" | head -20

334```

335 

336### Hook configuration

337 

338**Managed settings only**: Controls which hooks are allowed to run. This setting can only be configured in [managed settings](#settings-files) and provides administrators with strict control over hook execution.

339 

340**Behavior when `allowManagedHooksOnly` is `true`:**

137 341 

138* Read deny rules block file reads in sandbox342* Managed hooks and SDK hooks are loaded

139* Edit allow rules permit file writes (in addition to the defaults, e.g. the current working directory)343* User hooks, project hooks, and plugin hooks are blocked

140* Edit deny rules block writes within allowed paths

141 344 

142**Network access** is controlled via WebFetch permissions:345**Configuration:**

143 346 

144* WebFetch allow rules permit network domains347```json theme={null}

145* WebFetch deny rules block network domains348{

349 "allowManagedHooksOnly": true

350}

351```

146 352 

147### Settings precedence353### Settings precedence

148 354 

149Settings are applied in order of precedence (highest to lowest):355Settings apply in order of precedence. From highest to lowest:

150 356 

1511. **Enterprise managed policies** (`managed-settings.json`)3571. **Managed settings** (`managed-settings.json`)

152 * Deployed by IT/DevOps358 * Policies deployed by IT/DevOps to system directories

153 * Cannot be overridden359 * Cannot be overridden by user or project settings

154 360 

1552. **Command line arguments**3612. **Command line arguments**

156 * Temporary overrides for a specific session362 * Temporary overrides for a specific session


1645. **User settings** (`~/.claude/settings.json`)3705. **User settings** (`~/.claude/settings.json`)

165 * Personal global settings371 * Personal global settings

166 372 

167This hierarchy ensures that enterprise security policies are always enforced while still allowing teams and individuals to customize their experience.373This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience.

374 

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

168 376 

169### Key points about the configuration system377### Key points about the configuration system

170 378 

171* **Memory files (CLAUDE.md)**: Contain instructions and context that Claude loads at startup379* **Memory files (`CLAUDE.md`)**: Contain instructions and context that Claude loads at startup

172* **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior380* **Settings files (JSON)**: Configure permissions, environment variables, and tool behavior

173* **Slash commands**: Custom commands that can be invoked during a session with `/command-name`381* **Skills**: Custom prompts that can be invoked with `/skill-name` or loaded by Claude automatically

174* **MCP servers**: Extend Claude Code with additional tools and integrations382* **MCP servers**: Extend Claude Code with additional tools and integrations

175* **Precedence**: Higher-level configurations (Enterprise) override lower-level ones (User/Project)383* **Precedence**: Higher-level configurations (Managed) override lower-level ones (User/Project)

176* **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones384* **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones

177 385 

178### System prompt availability386### System prompt

179 387 

180<Note>388Claude Code's internal system prompt is not published. To add custom instructions, use `CLAUDE.md` files or the `--append-system-prompt` flag.

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

182</Note>

183 389 

184### Excluding sensitive files390### Excluding sensitive files

185 391 

186To 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:392To 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:

187 393 

188```json theme={null}394```json theme={null}

189{395{


199}405}

200```406```

201 407 

202This replaces the deprecated `ignorePatterns` configuration. Files matching these patterns will be completely invisible to Claude Code, preventing any accidental exposure of sensitive data.408This 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.

203 409 

204## Subagent configuration410## Subagent configuration

205 411 


212 418 

213## Plugin configuration419## Plugin configuration

214 420 

215Claude 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.421Claude 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.

216 422 

217### Plugin settings423### Plugin settings

218 424 


221```json theme={null}427```json theme={null}

222{428{

223 "enabledPlugins": {429 "enabledPlugins": {

224 "formatter@company-tools": true,430 "formatter@acme-tools": true,

225 "deployer@company-tools": true,431 "deployer@acme-tools": true,

226 "analyzer@security-plugins": false432 "analyzer@security-plugins": false

227 },433 },

228 "extraKnownMarketplaces": {434 "extraKnownMarketplaces": {

229 "company-tools": {435 "acme-tools": {

230 "source": "github",436 "source": "github",

231 "repo": "company/claude-plugins"437 "repo": "acme-corp/claude-plugins"

232 }438 }

233 }439 }

234}440}


272```json theme={null}478```json theme={null}

273{479{

274 "extraKnownMarketplaces": {480 "extraKnownMarketplaces": {

275 "company-tools": {481 "acme-tools": {

276 "source": {482 "source": {

277 "source": "github",483 "source": "github",

278 "repo": "company-org/claude-plugins"484 "repo": "acme-corp/claude-plugins"

279 }485 }

280 },486 },

281 "security-plugins": {487 "security-plugins": {

282 "source": {488 "source": {

283 "source": "git",489 "source": "git",

284 "url": "https://git.company.com/security/plugins.git"490 "url": "https://git.example.com/security/plugins.git"

285 }491 }

286 }492 }

287 }493 }


293* `github`: GitHub repository (uses `repo`)499* `github`: GitHub repository (uses `repo`)

294* `git`: Any git URL (uses `url`)500* `git`: Any git URL (uses `url`)

295* `directory`: Local filesystem path (uses `path`, for development only)501* `directory`: Local filesystem path (uses `path`, for development only)

502* `hostPattern`: regex pattern to match marketplace hosts (uses `hostPattern`)

503 

504#### `strictKnownMarketplaces`

505 

506**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [`managed-settings.json`](/en/permissions#managed-settings) and provides administrators with strict control over marketplace sources.

507 

508**Managed settings file locations**:

509 

510* **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`

511* **Linux and WSL**: `/etc/claude-code/managed-settings.json`

512* **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json`

513 

514**Key characteristics**:

515 

516* Only available in managed settings (`managed-settings.json`)

517* Cannot be overridden by user or project settings (highest precedence)

518* Enforced BEFORE network/filesystem operations (blocked sources never execute)

519* Uses exact matching for source specifications (including `ref`, `path` for git sources), except `hostPattern`, which uses regex matching

520 

521**Allowlist behavior**:

522 

523* `undefined` (default): No restrictions - users can add any marketplace

524* Empty array `[]`: Complete lockdown - users cannot add any new marketplaces

525* List of sources: Users can only add marketplaces that match exactly

526 

527**All supported source types**:

528 

529The allowlist supports seven marketplace source types. Most sources use exact matching, while `hostPattern` uses regex matching against the marketplace host.

530 

5311. **GitHub repositories**:

532 

533```json theme={null}

534{ "source": "github", "repo": "acme-corp/approved-plugins" }

535{ "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }

536{ "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" }

537```

538 

539Fields: `repo` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)

540 

5412. **Git repositories**:

542 

543```json theme={null}

544{ "source": "git", "url": "https://gitlab.example.com/tools/plugins.git" }

545{ "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" }

546{ "source": "git", "url": "ssh://git@git.example.com/plugins.git", "ref": "v3.1", "path": "approved" }

547```

548 

549Fields: `url` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)

550 

5513. **URL-based marketplaces**:

552 

553```json theme={null}

554{ "source": "url", "url": "https://plugins.example.com/marketplace.json" }

555{ "source": "url", "url": "https://cdn.example.com/marketplace.json", "headers": { "Authorization": "Bearer ${TOKEN}" } }

556```

557 

558Fields: `url` (required), `headers` (optional: HTTP headers for authenticated access)

559 

560<Note>

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

562</Note>

563 

5644. **NPM packages**:

565 

566```json theme={null}

567{ "source": "npm", "package": "@acme-corp/claude-plugins" }

568{ "source": "npm", "package": "@acme-corp/approved-marketplace" }

569```

570 

571Fields: `package` (required, supports scoped packages)

572 

5735. **File paths**:

574 

575```json theme={null}

576{ "source": "file", "path": "/usr/local/share/claude/acme-marketplace.json" }

577{ "source": "file", "path": "/opt/acme-corp/plugins/marketplace.json" }

578```

579 

580Fields: `path` (required: absolute path to marketplace.json file)

581 

5826. **Directory paths**:

583 

584```json theme={null}

585{ "source": "directory", "path": "/usr/local/share/claude/acme-plugins" }

586{ "source": "directory", "path": "/opt/acme-corp/approved-marketplaces" }

587```

588 

589Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)

590 

5917. **Host pattern matching**:

592 

593```json theme={null}

594{ "source": "hostPattern", "hostPattern": "^github\\.example\\.com$" }

595{ "source": "hostPattern", "hostPattern": "^gitlab\\.internal\\.example\\.com$" }

596```

597 

598Fields: `hostPattern` (required: regex pattern to match against the marketplace host)

599 

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

601 

602Host extraction by source type:

603 

604* `github`: always matches against `github.com`

605* `git`: extracts hostname from the URL (supports both HTTPS and SSH formats)

606* `url`: extracts hostname from the URL

607* `npm`, `file`, `directory`: not supported for host pattern matching

608 

609**Configuration examples**:

610 

611Example: allow specific marketplaces only:

612 

613```json theme={null}

614{

615 "strictKnownMarketplaces": [

616 {

617 "source": "github",

618 "repo": "acme-corp/approved-plugins"

619 },

620 {

621 "source": "github",

622 "repo": "acme-corp/security-tools",

623 "ref": "v2.0"

624 },

625 {

626 "source": "url",

627 "url": "https://plugins.example.com/marketplace.json"

628 },

629 {

630 "source": "npm",

631 "package": "@acme-corp/compliance-plugins"

632 }

633 ]

634}

635```

636 

637Example - Disable all marketplace additions:

638 

639```json theme={null}

640{

641 "strictKnownMarketplaces": []

642}

643```

644 

645Example: allow all marketplaces from an internal git server:

646 

647```json theme={null}

648{

649 "strictKnownMarketplaces": [

650 {

651 "source": "hostPattern",

652 "hostPattern": "^github\\.example\\.com$"

653 }

654 ]

655}

656```

657 

658**Exact matching requirements**:

659 

660Marketplace sources must match **exactly** for a user's addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:

661 

662* The `repo` or `url` must match exactly

663* The `ref` field must match exactly (or both be undefined)

664* The `path` field must match exactly (or both be undefined)

665 

666Examples of sources that **do NOT match**:

667 

668```json theme={null}

669// These are DIFFERENT sources:

670{ "source": "github", "repo": "acme-corp/plugins" }

671{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }

672 

673// These are also DIFFERENT:

674{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }

675{ "source": "github", "repo": "acme-corp/plugins" }

676```

677 

678**Comparison with `extraKnownMarketplaces`**:

679 

680| Aspect | `strictKnownMarketplaces` | `extraKnownMarketplaces` |

681| --------------------- | ------------------------------------ | ------------------------------------ |

682| **Purpose** | Organizational policy enforcement | Team convenience |

683| **Settings file** | `managed-settings.json` only | Any settings file |

684| **Behavior** | Blocks non-allowlisted additions | Auto-installs missing marketplaces |

685| **When enforced** | Before network/filesystem operations | After user trust prompt |

686| **Can be overridden** | No (highest precedence) | Yes (by higher precedence settings) |

687| **Source format** | Direct source object | Named marketplace with nested source |

688| **Use case** | Compliance, security restrictions | Onboarding, standardization |

689 

690**Format difference**:

691 

692`strictKnownMarketplaces` uses direct source objects:

693 

694```json theme={null}

695{

696 "strictKnownMarketplaces": [

697 { "source": "github", "repo": "acme-corp/plugins" }

698 ]

699}

700```

701 

702`extraKnownMarketplaces` requires named marketplaces:

703 

704```json theme={null}

705{

706 "extraKnownMarketplaces": {

707 "acme-tools": {

708 "source": { "source": "github", "repo": "acme-corp/plugins" }

709 }

710 }

711}

712```

713 

714**Important notes**:

715 

716* Restrictions are checked BEFORE any network requests or filesystem operations

717* When blocked, users see clear error messages indicating the source is blocked by managed policy

718* The restriction applies only to adding NEW marketplaces; previously installed marketplaces remain accessible

719* Managed settings have the highest precedence and cannot be overridden

720 

721See [Managed marketplace restrictions](/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation.

296 722 

297### Managing plugins723### Managing plugins

298 724 


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

315</Note>741</Note>

316 742 

317| Variable | Purpose |743| Variable | Purpose | |

318| :----------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |744| :--------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- |

319| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |745| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) | |

320| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) |746| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer `) | |

321| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers you want to add to the request (in `Name: Value` format) |747| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers to add to requests (`Name: Value` format, newline-separated for multiple headers) | |

322| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) |748| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/en/model-config#environment-variables) | |

323| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/model-config#environment-variables) |749| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/en/model-config#environment-variables) | |

324| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/model-config#environment-variables) |750| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/en/model-config#environment-variables) | |

325| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Azure AI Foundry authentication (see [Azure AI Foundry](/en/azure-ai-foundry)) |751| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry authentication (see [Microsoft Foundry](/en/microsoft-foundry)) | |

326| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) |752| `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)) | |

327| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) |753| `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)) | |

328| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |754| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/en/model-config#environment-variables)) | |

329| `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/)) |755| `ANTHROPIC_SMALL_FAST_MODEL` | \[DEPRECATED] Name of [Haiku-class model for background tasks](/en/costs) | |

330| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |756| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock | |

331| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |757| `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/)) | |

332| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |758| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands | |

333| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |759| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated | |

334| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) |760| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands | |

335| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |761| `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) | |

336| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |762| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command | |

337| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |763| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load CLAUDE.md files from directories specified with `--add-dir`. By default, additional directories do not load memory files | `1` |

338| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to disable Anthropic API-specific `anthropic-beta` headers. Use this if experiencing issues like "Unexpected value(s) for the `anthropic-beta` header" when using an LLM gateway with third-party providers |764| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Set to `1` to enable [agent teams](/en/agent-teams). Agent teams are experimental and disabled by default | |

339| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |765| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) | |

340| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |766| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication | |

341| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |767| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) | |

342| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests |768| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication | |

343| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (e.g. when using an LLM gateway) |769| `CLAUDE_CODE_EFFORT_LEVEL` | Set the effort level for supported models. Values: `low`, `medium`, `high` (default). Lower effort is faster and cheaper, higher effort provides deeper reasoning. Currently supported with Opus 4.6 only. See [Adjust effort level](/en/model-config#adjust-effort-level) | |

344| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for AI Foundry (e.g. when using an LLM gateway) |770| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to disable Anthropic API-specific `anthropic-beta` headers. Use this if experiencing issues like "Unexpected value(s) for the `anthropic-beta` header" when using an LLM gateway with third-party providers | |

345| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (e.g. when using an LLM gateway) |771| `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 | |

346| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) |772| `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 | |

347| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) |773| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Set to `1` to disable the "How is Claude doing?" session quality surveys. Also disabled when using third-party providers or when telemetry is disabled. See [Session quality surveys](/en/data-usage#session-quality-surveys) | |

348| `CLAUDE_CODE_USE_FOUNDRY` | Use [Azure AI Foundry](/en/azure-ai-foundry) |774| `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 | |

349| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) |775| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `true` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution | |

350| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. |776| `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) | |

351| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |777| `CLAUDE_CODE_TEAM_NAME` | Name of the agent team this teammate belongs to. Set automatically on [agent team](/en/agent-teams) members | |

352| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |778| `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude/` to this path. Default: `/tmp` on Unix/macOS, `os.tmpdir()` on Windows | |

353| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |779| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` | |

354| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text |780| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context | |

355| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |781| `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) | |

356| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |782| `CLAUDE_CODE_ENABLE_TASKS` | Set to `false` to temporarily revert to the previous TODO list instead of the task tracking system. Default: `true`. See [Task list](/en/interactive-mode#task-list) | |

357| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |783| `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) | |

358| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |784| `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 | |

359| `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) |785| `CLAUDE_CODE_HIDE_ACCOUNT_INFO` | Set to `1` to hide your email address and organization name from the Claude Code UI. Useful when streaming or recording | |

360| `HTTP_PROXY` | Specify HTTP proxy server for network connections |786| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions | |

361| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |787| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Default: 32,000. Maximum: 64,000. Increasing this value reduces the effective context window available before [auto-compaction](/en/costs#reduce-token-usage) triggers. | |

362| `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) |788| `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) | |

363| `MAX_THINKING_TOKENS` | Enable [extended thinking](https://docs.claude.com/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](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#caching-with-thinking-blocks). Disabled by default. |789| `CLAUDE_CODE_PLAN_MODE_REQUIRED` | Auto-set to `true` on [agent team](/en/agent-teams) teammates that require plan approval. Read-only: set by Claude Code when spawning teammates. See [require plan approval](/en/agent-teams#require-plan-approval-for-teammates) | |

364| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |790| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) | |

365| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |791| `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>` | |

366| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |792| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) | |

367| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Maximum number of characters for slash command metadata shown to [SlashCommand tool](/en/slash-commands#slashcommand-tool) (default: 15000) |793| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) | |

368| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` intead of `rg` included with Claude Code |794| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) | |

369| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |795| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/en/model-config) | |

370| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |796| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/en/amazon-bedrock) | |

371| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |797| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/en/microsoft-foundry) | |

372| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |798| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/en/google-vertex-ai) | |

373| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |799| `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files | |

800| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. | |

801| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command | |

802| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages | |

803| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting | |

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

805| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text | |

806| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) | |

807| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models | |

808| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models | |

809| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models | |

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

811| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/en/mcp#scale-with-mcp-tool-search). Values: `auto` (default, enables at 10% context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `true` (always on), `false` (disabled) | |

812| `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` | |

813| `HTTP_PROXY` | Specify HTTP proxy server for network connections | |

814| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections | |

815| `IS_DEMO` | Set to `true` to enable demo mode: hides email and organization from the UI, skips onboarding, and hides internal commands. Useful for streaming or recording sessions | |

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

817| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) token budget. Thinking is enabled at max budget (31,999 tokens) by default. Use this to limit the budget (for example, `MAX_THINKING_TOKENS=10000`) or disable thinking entirely (`MAX_THINKING_TOKENS=0`). For Opus 4.6, thinking depth is controlled by [effort level](/en/model-config#adjust-effort-level) instead, and this variable is ignored unless set to `0` to disable thinking. | |

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

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

820| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup | |

821| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution | |

822| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy | |

823| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Override the character budget for skill metadata shown to the [Skill tool](/en/skills#control-who-invokes-a-skill). The budget scales dynamically at 2% of the context window, with a fallback of 16,000 characters. Legacy name kept for backwards compatibility | |

824| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code | |

825| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI | |

826| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI | |

827| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI | |

828| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI | |

829| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI | |

374 830 

375## Tools available to Claude831## Tools available to Claude

376 832 

377Claude Code has access to a set of powerful tools that help it understand and modify your codebase:833Claude Code has access to a set of powerful tools that help it understand and modify your codebase:

378 834 

379| Tool | Description | Permission Required |835| Tool | Description | Permission Required |

380| :--------------- | :------------------------------------------------------------------ | :------------------ |836| :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------ |

381| **Bash** | Executes shell commands in your environment | Yes |837| **AskUserQuestion** | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |

838| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes |

839| **TaskOutput** | Retrieves output from a background task (bash shell or subagent) | No |

382| **Edit** | Makes targeted edits to specific files | Yes |840| **Edit** | Makes targeted edits to specific files | Yes |

841| **ExitPlanMode** | Prompts the user to exit plan mode and start coding | Yes |

383| **Glob** | Finds files based on pattern matching | No |842| **Glob** | Finds files based on pattern matching | No |

384| **Grep** | Searches for patterns in file contents | No |843| **Grep** | Searches for patterns in file contents | No |

844| **KillShell** | Kills a running background bash shell by its ID | No |

845| **MCPSearch** | Searches for and loads MCP tools when [tool search](/en/mcp#scale-with-mcp-tool-search) is enabled | No |

385| **NotebookEdit** | Modifies Jupyter notebook cells | Yes |846| **NotebookEdit** | Modifies Jupyter notebook cells | Yes |

386| **NotebookRead** | Reads and displays Jupyter notebook contents | No |

387| **Read** | Reads the contents of files | No |847| **Read** | Reads the contents of files | No |

388| **SlashCommand** | Runs a [custom slash command](/en/slash-commands#slashcommand-tool) | Yes |848| **Skill** | Executes a [skill](/en/skills#control-who-invokes-a-skill) within the main conversation | Yes |

389| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |849| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |

390| **TodoWrite** | Creates and manages structured task lists | No |850| **TaskCreate** | Creates a new task in the task list | No |

851| **TaskGet** | Retrieves full details for a specific task | No |

852| **TaskList** | Lists all tasks with their current status | No |

853| **TaskUpdate** | Updates task status, dependencies, details, or deletes tasks | No |

391| **WebFetch** | Fetches content from a specified URL | Yes |854| **WebFetch** | Fetches content from a specified URL | Yes |

392| **WebSearch** | Performs web searches with domain filtering | Yes |855| **WebSearch** | Performs web searches with domain filtering | Yes |

393| **Write** | Creates or overwrites files | Yes |856| **Write** | Creates or overwrites files | Yes |

857| **LSP** | Code intelligence via language servers. Reports type errors and warnings automatically after file edits. Also supports navigation operations: jump to definitions, find references, get type info, list symbols, find implementations, trace call hierarchies. Requires a [code intelligence plugin](/en/discover-plugins#code-intelligence) and its language server binary | No |

858 

859Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/permissions#tool-specific-permission-rules).

860 

861### Bash tool behavior

862 

863The Bash tool executes shell commands with the following persistence behavior:

864 

865* **Working directory persists**: When Claude changes the working directory (for example, `cd /path/to/dir`), subsequent Bash commands will execute in that directory. You can use `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1` to reset to the project directory after each command.

866* **Environment variables do NOT persist**: Environment variables set in one Bash command (for example, `export MY_VAR=value`) are **not** available in subsequent Bash commands. Each Bash command runs in a fresh shell environment.

867 

868To make environment variables available in Bash commands, you have **three options**:

869 

870**Option 1: Activate environment before starting Claude Code** (simplest approach)

871 

872Activate your virtual environment in your terminal before launching Claude Code:

873 

874```bash theme={null}

875conda activate myenv

876# or: source /path/to/venv/bin/activate

877claude

878```

879 

880This works for shell environments but environment variables set within Claude's Bash commands will not persist between commands.

881 

882**Option 2: Set CLAUDE\_ENV\_FILE before starting Claude Code** (persistent environment setup)

883 

884Export the path to a shell script containing your environment setup:

885 

886```bash theme={null}

887export CLAUDE_ENV_FILE=/path/to/env-setup.sh

888claude

889```

890 

891Where `/path/to/env-setup.sh` contains:

892 

893```bash theme={null}

894conda activate myenv

895# or: source /path/to/venv/bin/activate

896# or: export MY_VAR=value

897```

898 

899Claude Code will source this file before each Bash command, making the environment persistent across all commands.

900 

901**Option 3: Use a SessionStart hook** (project-specific configuration)

902 

903Configure in `.claude/settings.json`:

904 

905```json theme={null}

906{

907 "hooks": {

908 "SessionStart": [{

909 "matcher": "startup",

910 "hooks": [{

911 "type": "command",

912 "command": "echo 'conda activate myenv' >> \"$CLAUDE_ENV_FILE\""

913 }]

914 }]

915 }

916}

917```

918 

919The hook writes to `$CLAUDE_ENV_FILE`, which is then sourced before each Bash command. This is ideal for team-shared project configurations.

394 920 

395Permission rules can be configured using `/allowed-tools` or in [permission settings](/en/settings#available-settings). Also see [Tool-specific permission rules](/en/iam#tool-specific-permission-rules).921See [SessionStart hooks](/en/hooks#persist-environment-variables) for more details on Option 3.

396 922 

397### Extending tools with hooks923### Extending tools with hooks

398 924 


405 931 

406## See also932## See also

407 933 

408* [Identity and Access Management](/en/iam#configuring-permissions) - Learn about Claude Code's permission system934* [Permissions](/en/permissions): permission system, rule syntax, tool-specific patterns, and managed policies

409* [IAM and access control](/en/iam#enterprise-managed-policy-settings) - Enterprise policy management935* [Authentication](/en/authentication): set up user access to Claude Code

410* [Troubleshooting](/en/troubleshooting#auto-updater-issues) - Solutions for common configuration issues936* [Troubleshooting](/en/troubleshooting): solutions for common configuration issues

setup.md +243 −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# Set up Claude Code5# Set up Claude Code

2 6 

3> Install, authenticate, and start using Claude Code on your development machine.7> Install, authenticate, and start using Claude Code on your development machine.

4 8 

5## System requirements9## System requirements

6 10 

7* **Operating Systems**: macOS 10.15+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows)11* **Operating System**:

8* **Hardware**: 4GB+ RAM12 * macOS 13.0+

9* **Software**: [Node.js 18+](https://nodejs.org/en/download) (only required for NPM installation)13 * Windows 10 1809+ or Windows Server 2019+ ([see setup notes](#platform-specific-setup))

10* **Network**: Internet connection required for authentication and AI processing14 * Ubuntu 20.04+

11* **Shell**: Works best in Bash, Zsh or Fish15 * Debian 10+

16 * Alpine Linux 3.19+ ([additional dependencies required](#platform-specific-setup))

17* **Hardware**: 4 GB+ RAM

18* **Network**: Internet connection required (see [network configuration](/en/network-config#network-access-requirements))

19* **Shell**: Works best in Bash or Zsh

12* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)20* **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)

13 21 

14### Additional dependencies22### Additional dependencies

15 23 

16* **ripgrep**: Usually included with Claude Code. If search functionality fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues).24* **ripgrep**: Usually included with Claude Code. If search fails, see [search troubleshooting](/en/troubleshooting#search-and-discovery-issues).

25* **[Node.js 18+](https://nodejs.org/en/download)**: Only required for [deprecated npm installation](#npm-installation-deprecated)

17 26 

18## Standard installation27## Installation

19 28 

20To install Claude Code, use one of the following methods:29To install Claude Code, use one of the following methods:

21 30 

22<Tabs>31<Tabs>

23 <Tab title="Native Install (Recommended)">32 <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:**33 **macOS, Linux, WSL:**

31 34 

32 ```bash theme={null}35 ```bash theme={null}


44 ```batch theme={null}47 ```batch theme={null}

45 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd48 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

46 ```49 ```

47 </Tab>

48 50 

49 <Tab title="NPM">51 <Info>

50 If you have [Node.js 18 or newer installed](https://nodejs.org/en/download/):52 Native installations automatically update in the background to keep you on the latest version.

53 </Info>

54 </Tab>

51 55 

56 <Tab title="Homebrew">

52 ```sh theme={null}57 ```sh theme={null}

53 npm install -g @anthropic-ai/claude-code58 brew install --cask claude-code

54 ```59 ```

60 

61 <Info>

62 Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.

63 </Info>

55 </Tab>64 </Tab>

56</Tabs>

57 65 

58<Note>66 <Tab title="WinGet">

59 Some users may be automatically migrated to an improved installation method.67 ```powershell theme={null}

60</Note>68 winget install Anthropic.ClaudeCode

69 ```

70 

71 <Info>

72 WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.

73 </Info>

74 </Tab>

75</Tabs>

61 76 

62After the installation process completes, navigate to your project and start Claude Code:77After the installation process completes, navigate to your project and start Claude Code:

63 78 


66claude81claude

67```82```

68 83 

69Claude Code offers the following authentication options:84If you encounter any issues during installation, consult the [troubleshooting guide](/en/troubleshooting).

70 

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.

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, Google Vertex AI, or Azure AI Foundry](/en/third-party-integrations) for enterprise deployments with your existing cloud infrastructure.

74 

75<Note>

76 Claude Code securely stores your credentials. See [Credential Management](/en/iam#credential-management) for details.

77</Note>

78 85 

79## Windows setup86<Tip>

87 Run `claude doctor` after installation to check your installation type and version.

88</Tip>

80 89 

81**Option 1: Claude Code within WSL**90### Platform-specific setup

82 91 

83* Both WSL 1 and WSL 2 are supported92**Windows**: Run Claude Code natively (requires [Git Bash](https://git-scm.com/downloads/win)) or inside WSL. Both WSL 1 and WSL 2 are supported, but WSL 1 has limited support and does not support features like Bash tool sandboxing.

84 93 

85**Option 2: Claude Code on native Windows with Git Bash**94**Alpine Linux and other musl/uClibc-based distributions**:

86 95 

87* Requires [Git for Windows](https://git-scm.com/downloads/win)96The native installer on Alpine and other musl/uClibc-based distributions requires `libgcc`, `libstdc++`, and `ripgrep`. Install these using your distribution's package manager, then set `USE_BUILTIN_RIPGREP=0`.

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 

93## Alternative installation methods

94 

95Claude Code offers multiple installation methods to suit different environments.

96 97 

97If you encounter any issues during installation, consult the [troubleshooting guide](/en/troubleshooting#linux-permission-issues).98On Alpine:

98 99 

99<Tip>100```bash theme={null}

100 Run `claude doctor` after installation to check your installation type and version.101apk add libgcc libstdc++ ripgrep

101</Tip>102```

102 103 

103### Native installation options104### Authentication

104 105 

105The native installation is the recommended method and offers several benefits:106#### For individuals

106 107 

107* One self-contained executable1081. **Claude Pro or Max plan** (recommended): Subscribe to Claude's [Pro or Max plan](https://claude.ai/pricing) for a unified subscription that includes both Claude Code and Claude on the web. Manage your account in one place and log in with your Claude.ai account.

108* No Node.js dependency1092. **Claude Console**: Connect through the [Claude Console](https://console.anthropic.com) and complete the OAuth process. Requires active billing in the Anthropic Console. A "Claude Code" workspace is automatically created for usage tracking and cost management. You can't create API keys for the Claude Code workspace; it's dedicated exclusively for Claude Code usage.

109* Improved auto-updater stability

110 110 

111If you have an existing installation of Claude Code, use `claude install` to migrate to the native binary installation.111#### For teams and organizations

112 112 

113For advanced installation options with the native installer:1131. **Claude for Teams or Enterprise** (recommended): Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or [Claude for Enterprise](https://anthropic.com/contact-sales) for centralized billing, team management, and access to both Claude Code and Claude on the web. Team members log in with their Claude.ai accounts.

1142. **Claude Console with team billing**: Set up a shared [Claude Console](https://console.anthropic.com) organization with team billing. Invite team members and assign roles for usage tracking.

1153. **Cloud providers**: Configure Claude Code to use [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/en/third-party-integrations) for deployments with your existing cloud infrastructure.

114 116 

115**macOS, Linux, WSL:**117### Install a specific version

116 118 

117```bash theme={null}119The 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.

118# Install stable version (default)

119curl -fsSL https://claude.ai/install.sh | bash

120 120 

121# Install latest version121To install the latest version (default):

122curl -fsSL https://claude.ai/install.sh | bash -s latest

123 122 

124# Install specific version number123<Tabs>

125curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58124 <Tab title="macOS, Linux, WSL">

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

127 126 curl -fsSL https://claude.ai/install.sh | bash

128<Note>127 ```

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`.128 </Tab>

130</Note>

131 129 

132<Note>130 <Tab title="Windows PowerShell">

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).131 ```powershell theme={null}

134</Note>132 irm https://claude.ai/install.ps1 | iex

133 ```

134 </Tab>

135 135 

136**Windows PowerShell:**136 <Tab title="Windows CMD">

137 ```batch theme={null}

138 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

139 ```

140 </Tab>

141</Tabs>

137 142 

138```powershell theme={null}143To install the stable version:

139# Install stable version (default)

140irm https://claude.ai/install.ps1 | iex

141 144 

142# Install latest version145<Tabs>

143& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest146 <Tab title="macOS, Linux, WSL">

147 ```bash theme={null}

148 curl -fsSL https://claude.ai/install.sh | bash -s stable

149 ```

150 </Tab>

144 151 

145# Install specific version number152 <Tab title="Windows PowerShell">

146& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58153 ```powershell theme={null}

147```154 & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) stable

155 ```

156 </Tab>

148 157 

149**Windows CMD:**158 <Tab title="Windows CMD">

159 ```batch theme={null}

160 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd stable && del install.cmd

161 ```

162 </Tab>

163</Tabs>

150 164 

151```batch theme={null}165To install a specific version number:

152REM Install stable version (default)

153curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

154 166 

155REM Install latest version167<Tabs>

156curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd latest && del install.cmd168 <Tab title="macOS, Linux, WSL">

169 ```bash theme={null}

170 curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58

171 ```

172 </Tab>

157 173 

158REM Install specific version number174 <Tab title="Windows PowerShell">

159curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd175 ```powershell theme={null}

160```176 & ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58

177 ```

178 </Tab>

161 179 

162<Tip>180 <Tab title="Windows CMD">

163 Make sure that you remove any outdated aliases or symlinks before installing.181 ```batch theme={null}

164</Tip>182 curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd

183 ```

184 </Tab>

185</Tabs>

165 186 

166**Binary integrity and code signing**187### Binary integrity and code signing

167 188 

168* SHA256 checksums for all platforms are published in the release manifests, currently located at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json` (example: replace `{VERSION}` with `2.0.30`)189* SHA256 checksums for all platforms are published in the release manifests, currently located at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json` (example: replace `{VERSION}` with `2.0.30`)

169* Signed binaries are distributed for the following platforms:190* Signed binaries are distributed for the following platforms:

170 * macOS: Signed by "Anthropic PBC" and notarized by Apple191 * macOS: Signed by "Anthropic PBC" and notarized by Apple

171 * Windows: Signed by "Anthropic, PBC"192 * Windows: Signed by "Anthropic, PBC"

172 193 

173### NPM installation194## NPM installation (deprecated)

174 195 

175For environments where NPM is preferred or required:196NPM installation is deprecated. Use the [native installation](#installation) method when possible. To migrate an existing npm installation to native, run `claude install`.

197 

198**Global npm installation**

176 199 

177```sh theme={null}200```sh theme={null}

178npm install -g @anthropic-ai/claude-code201npm install -g @anthropic-ai/claude-code


180 203 

181<Warning>204<Warning>

182 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks.205 Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks.

183 If you encounter permission errors, see [configure Claude Code](/en/troubleshooting#linux-permission-issues) for recommended solutions.206 If you encounter permission errors, see [troubleshooting permission errors](/en/troubleshooting#command-not-found-claude-or-permission-errors) for recommended solutions.

184</Warning>207</Warning>

185 208 

186### Local installation209## Windows setup

187 210 

188* After global install via npm, use `claude migrate-installer` to move to local211**Option 1: Claude Code within WSL**

189* Avoids autoupdater npm permission issues

190* Some users may be automatically migrated to this method

191 212 

192## Running on AWS or GCP213* Both WSL 1 and WSL 2 are supported

214* WSL 2 supports [sandboxing](/en/sandboxing) for enhanced security. WSL 1 does not support sandboxing.

193 215 

194By default, Claude Code uses the Claude API.216**Option 2: Claude Code on native Windows with Git Bash**

195 217 

196For details on running Claude Code on AWS or GCP, see [third-party integrations](/en/third-party-integrations).218* Requires [Git for Windows](https://git-scm.com/downloads/win)

219* For portable Git installations, specify the path to your `bash.exe`:

220 ```powershell theme={null}

221 $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"

222 ```

197 223 

198## Update Claude Code224## Update Claude Code

199 225 


206* **Notifications**: You'll see a notification when updates are installed232* **Notifications**: You'll see a notification when updates are installed

207* **Applying updates**: Updates take effect the next time you start Claude Code233* **Applying updates**: Updates take effect the next time you start Claude Code

208 234 

209**Disable auto-updates:**235<Note>

236 Homebrew and WinGet installations do not auto-update. Use `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update manually.

237 

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

239</Note>

240 

241### Configure release channel

242 

243Configure which release channel Claude Code follows for both auto-updates and `claude update` with the `autoUpdatesChannel` setting:

244 

245* `"latest"` (default): Receive new features as soon as they're released

246* `"stable"`: Use a version that is typically about one week old, skipping releases with major regressions

247 

248Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/en/settings):

249 

250```json theme={null}

251{

252 "autoUpdatesChannel": "stable"

253}

254```

255 

256For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/en/permissions#managed-settings).

257 

258### Disable auto-updates

210 259 

211Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/settings):260Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/en/settings):

212 261 


219```bash theme={null}268```bash theme={null}

220claude update269claude update

221```270```

271 

272## Uninstall Claude Code

273 

274If you need to uninstall Claude Code, follow the instructions for your installation method.

275 

276### Native installation

277 

278Remove the Claude Code binary and version files:

279 

280**macOS, Linux, WSL:**

281 

282```bash theme={null}

283rm -f ~/.local/bin/claude

284rm -rf ~/.local/share/claude

285```

286 

287**Windows PowerShell:**

288 

289```powershell theme={null}

290Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force

291Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force

292```

293 

294**Windows CMD:**

295 

296```batch theme={null}

297del "%USERPROFILE%\.local\bin\claude.exe"

298rmdir /s /q "%USERPROFILE%\.local\share\claude"

299```

300 

301### Homebrew installation

302 

303```bash theme={null}

304brew uninstall --cask claude-code

305```

306 

307### WinGet installation

308 

309```powershell theme={null}

310winget uninstall Anthropic.ClaudeCode

311```

312 

313### NPM installation

314 

315```bash theme={null}

316npm uninstall -g @anthropic-ai/claude-code

317```

318 

319### Clean up configuration files (optional)

320 

321<Warning>

322 Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.

323</Warning>

324 

325To remove Claude Code settings and cached data:

326 

327**macOS, Linux, WSL:**

328 

329```bash theme={null}

330# Remove user settings and state

331rm -rf ~/.claude

332rm ~/.claude.json

333 

334# Remove project-specific settings (run from your project directory)

335rm -rf .claude

336rm -f .mcp.json

337```

338 

339**Windows PowerShell:**

340 

341```powershell theme={null}

342# Remove user settings and state

343Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force

344Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force

345 

346# Remove project-specific settings (run from your project directory)

347Remove-Item -Path ".claude" -Recurse -Force

348Remove-Item -Path ".mcp.json" -Force

349```

350 

351**Windows CMD:**

352 

353```batch theme={null}

354REM Remove user settings and state

355rmdir /s /q "%USERPROFILE%\.claude"

356del "%USERPROFILE%\.claude.json"

357 

358REM Remove project-specific settings (run from your project directory)

359rmdir /s /q ".claude"

360del ".mcp.json"

361```

skills.md +492 −413

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

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/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](https://docs.claude.com/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 [interactive mode](/en/interactive-mode#built-in-commands).

13 

14 **Custom slash commands have been merged into skills.** A file at `.claude/commands/review.md` and a skill at `.claude/skills/review/SKILL.md` both create `/review` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to [control whether you or Claude invokes them](#control-who-invokes-a-skill), and the ability for Claude to load them automatically when relevant.

29</Note>15</Note>

30 16 

31## Create a Skill17Claude 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).

32 18 

33Skills are stored as directories containing a `SKILL.md` file.19## Getting started

34 20 

35### Personal Skills21### Create your first skill

36 22 

37Personal Skills are available across all your projects. Store them in `~/.claude/skills/`:23This 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`.

38 24 

39```bash theme={null}25<Steps>

40mkdir -p ~/.claude/skills/my-skill-name26 <Step title="Create the skill directory">

41```27 Create a directory for the skill in your personal skills folder. Personal skills are available across all your projects.

42 28 

43**Use personal Skills for**:29 ```bash theme={null}

30 mkdir -p ~/.claude/skills/explain-code

31 ```

32 </Step>

44 33 

45* Your individual workflows and preferences34 <Step title="Write SKILL.md">

46* Experimental Skills you're developing35 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.

47* Personal productivity tools

48 36 

49### Project Skills37 Create `~/.claude/skills/explain-code/SKILL.md`:

50 38 

51Project Skills are shared with your team. Store them in `.claude/skills/` within your project:39 ```yaml theme={null}

40 ---

41 name: explain-code

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

43 ---

52 44 

53```bash theme={null}45 When explaining code, always include:

54mkdir -p .claude/skills/my-skill-name

55```

56 

57**Use project Skills for**:

58 

59* Team workflows and conventions

60* Project-specific expertise

61* Shared utilities and scripts

62 46 

63Project Skills are checked into git and automatically available to team members.47 1. **Start with an analogy**: Compare the code to something from everyday life

48 2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships

49 3. **Walk through the code**: Explain step-by-step what happens

50 4. **Highlight a gotcha**: What's a common mistake or misconception?

64 51 

65### Plugin Skills52 Keep explanations conversational. For complex concepts, use multiple analogies.

53 ```

54 </Step>

66 55 

67Skills can also come from [Claude Code plugins](/en/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.56 <Step title="Test the skill">

57 You can test it two ways:

68 58 

69## Write SKILL.md59 **Let Claude invoke it automatically** by asking something that matches the description:

70 60 

71Create a `SKILL.md` file with YAML frontmatter and Markdown content:61 ```

62 How does this code work?

63 ```

72 64 

73```yaml theme={null}65 **Or invoke it directly** with the skill name:

74name: your-skill-name

75description: Brief description of what this Skill does and when to use it

76 66 

77# Your Skill Name67 ```

68 /explain-code src/auth/login.ts

69 ```

78 70 

79## Instructions71 Either way, Claude should include an analogy and ASCII diagram in its explanation.

80Provide clear, step-by-step guidance for Claude.72 </Step>

73</Steps>

81 74 

82## Examples75### Where skills live

83Show concrete examples of using this Skill.

84```

85 76 

86**Field requirements**:77Where you store a skill determines who can use it:

87 78 

88* `name`: Must use lowercase letters, numbers, and hyphens only (max 64 characters)79| Location | Path | Applies to |

89* `description`: Brief description of what the Skill does and when to use it (max 1024 characters)80| :--------- | :------------------------------------------------------- | :----------------------------- |

81| Enterprise | See [managed settings](/en/permissions#managed-settings) | All users in your organization |

82| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |

83| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |

84| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |

90 85 

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.86When skills share the same name across levels, higher-priority locations win: enterprise > personal > project. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict with other levels. If you have files in `.claude/commands/`, those work the same way, but if a skill and a command share the same name, the skill takes precedence.

92 87 

93See the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules.88#### Automatic discovery from nested directories

94 89 

95## Add supporting files90When 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.

96 91 

97Create additional files alongside SKILL.md:92Each skill is a directory with `SKILL.md` as the entrypoint:

98 93 

99```94```

100my-skill/95my-skill/

101├── SKILL.md (required)96├── SKILL.md # Main instructions (required)

102├── reference.md (optional documentation)97├── template.md # Template for Claude to fill in

103├── examples.md (optional examples)98├── examples/

104── scripts/99│ └── sample.md # Example output showing expected format

105└── helper.py (optional utility)100└── scripts/

106└── templates/101 └── validate.sh # Script Claude can execute

107 └── template.txt (optional template)

108```

109 

110Reference these files from SKILL.md:

111 

112````markdown theme={null}

113For advanced usage, see [reference.md](reference.md).

114 

115Run the helper script:

116```bash

117python scripts/helper.py input.txt

118```

119````

120 

121Claude reads these files only when needed, using progressive disclosure to manage context efficiently.

122 

123## Restrict tool access with allowed-tools

124 

125Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active:

126 

127```yaml theme={null}

128name: safe-file-reader

129description: Read files without making changes. Use when you need read-only file access.

130allowed-tools: Read, Grep, Glob

131 

132# Safe File Reader

133 

134This Skill provides read-only file access.

135 

136## Instructions

1371. Use Read to view file contents

1382. Use Grep to search within files

1393. Use Glob to find files by pattern

140```102```

141 103 

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:104The `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 105 

150<Note>106<Note>

151 `allowed-tools` is only supported for Skills in Claude Code.107 Files in `.claude/commands/` still work and support the same [frontmatter](#frontmatter-reference). Skills are recommended since they support additional features like supporting files.

152</Note>108</Note>

153 109 

154## View available Skills110#### Skills from additional directories

155 

156Skills are automatically discovered by Claude from three sources:

157 111 

158* Personal Skills: `~/.claude/skills/`112Skills defined in `.claude/skills/` within directories added via `--add-dir` are loaded automatically and picked up by live change detection, so you can edit them during a session without restarting.

159* Project Skills: `.claude/skills/`

160* Plugin Skills: bundled with installed plugins

161 113 

162**To view all available Skills**, ask Claude directly:114<Note>

163 115 CLAUDE.md files from `--add-dir` directories are not loaded by default. To load them, set `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`. See [Load memory from additional directories](/en/memory#load-memory-from-additional-directories).

164```116</Note>

165What Skills are available?

166```

167 117 

168or118## Configure skills

169 119 

170```120Skills are configured through YAML frontmatter at the top of `SKILL.md` and the markdown content that follows.

171List all available Skills

172```

173 121 

174This will show all Skills from all sources, including plugin Skills.122### Types of skill content

175 123 

176**To inspect a specific Skill**, you can also check the filesystem:124Skill files can contain any instructions, but thinking about how you want to invoke them helps guide what to include:

177 125 

178```bash theme={null}126**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 127 

182# List project Skills (if in a project directory)128```yaml theme={null}

183ls .claude/skills/129---

130name: api-conventions

131description: API design patterns for this codebase

132---

184 133 

185# View a specific Skill's content134When writing API endpoints:

186cat ~/.claude/skills/my-skill/SKILL.md135- Use RESTful naming conventions

136- Return consistent error formats

137- Include request validation

187```138```

188 139 

189## Test a Skill140**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 141 

191After creating a Skill, test it by asking questions that match your description.142```yaml theme={null}

192 143---

193**Example**: If your description mentions "PDF files":144name: deploy

145description: Deploy the application to production

146context: fork

147disable-model-invocation: true

148---

194 149 

150Deploy the application:

1511. Run the test suite

1522. Build the application

1533. Push to the deployment target

195```154```

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 155 

203If Claude doesn't use your Skill, check these common issues:156Your `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 157 

205### Make description specific158### Frontmatter reference

206 159 

207**Too vague**:160Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:

208 161 

209```yaml theme={null}162```yaml theme={null}

210description: Helps with documents163---

211```164name: my-skill

212 165description: What this skill does

213**Specific**:166disable-model-invocation: true

167allowed-tools: Read, Grep

168---

214 169 

215```yaml theme={null}170Your 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```171```

218 172 

219Include both what the Skill does and when to use it in the description.173All fields are optional. Only `description` is recommended so Claude knows when to use the skill.

220 174 

221### Verify file path175| Field | Required | Description |

176| :------------------------- | :---------- | :---------------------------------------------------------------------------------------------------------------------------------------------------- |

177| `name` | No | Display name for the skill. If omitted, uses the directory name. Lowercase letters, numbers, and hyphens only (max 64 characters). |

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

179| `argument-hint` | No | Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. |

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

181| `user-invocable` | No | Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn't invoke directly. Default: `true`. |

182| `allowed-tools` | No | Tools Claude can use without asking permission when this skill is active. |

183| `model` | No | Model to use when this skill is active. |

184| `context` | No | Set to `fork` to run in a forked subagent context. |

185| `agent` | No | Which subagent type to use when `context: fork` is set. |

186| `hooks` | No | Hooks scoped to this skill's lifecycle. See [Hooks in skills and agents](/en/hooks#hooks-in-skills-and-agents) for configuration format. |

222 187 

223**Personal Skills**: `~/.claude/skills/skill-name/SKILL.md`188#### Available string substitutions

224**Project Skills**: `.claude/skills/skill-name/SKILL.md`

225 189 

226Check the file exists:190Skills support string substitution for dynamic values in the skill content:

227 191 

228```bash theme={null}192| Variable | Description |

229# Personal193| :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |

230ls ~/.claude/skills/my-skill/SKILL.md194| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |

231 195| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |

232# Project196| `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. |

233ls .claude/skills/my-skill/SKILL.md197| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |

234```

235 198 

236### Check YAML syntax199**Example using substitutions:**

237 200 

238Invalid YAML prevents the Skill from loading. Verify the frontmatter:201```yaml theme={null}

239 202---

240```bash theme={null}203name: session-logger

241cat SKILL.md | head -n 10204description: Log activity for this session

242```205---

243 

244Ensure:

245 

246* Opening `---` on line 1

247* Closing `---` before Markdown content

248* Valid YAML syntax (no tabs, correct indentation)

249 

250### View errors

251 206 

252Run Claude Code with debug mode to see Skill loading errors:207Log the following to logs/${CLAUDE_SESSION_ID}.log:

253 208 

254```bash theme={null}209$ARGUMENTS

255claude --debug

256```210```

257 211 

258## Share Skills with your team212### Add supporting files

259 

260**Recommended approach**: Distribute Skills through [plugins](/en/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 213 

268For complete instructions, see [Add Skills to your plugin](/en/plugins#add-skills-to-your-plugin).214Skills 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.

269 215 

270You can also share Skills directly through project repositories:

271 

272### Step 1: Add Skill to your project

273 

274Create a project Skill:

275 

276```bash theme={null}

277mkdir -p .claude/skills/team-skill

278# Create SKILL.md

279```216```

280 217my-skill/

281### Step 2: Commit to git218├── SKILL.md (required - overview and navigation)

282 219├── reference.md (detailed API docs - loaded when needed)

283```bash theme={null}220├── examples.md (usage examples - loaded when needed)

284git add .claude/skills/221└── scripts/

285git commit -m "Add team Skill for PDF processing"222 └── helper.py (utility script - executed, not loaded)

286git push

287```223```

288 224 

289### Step 3: Team members get Skills automatically225Reference supporting files from `SKILL.md` so Claude knows what each file contains and when to load it:

290 226 

291When team members pull the latest changes, Skills are immediately available:227```markdown theme={null}

228## Additional resources

292 229 

293```bash theme={null}230- For complete API details, see [reference.md](reference.md)

294git pull231- For usage examples, see [examples.md](examples.md)

295claude # Skills are now available

296```232```

297 233 

298## Update a Skill234<Tip>Keep `SKILL.md` under 500 lines. Move detailed reference material to separate files.</Tip>

299 235 

300Edit SKILL.md directly:236### Control who invokes a skill

301 237 

302```bash theme={null}238By 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:

303# Personal Skill

304code ~/.claude/skills/my-skill/SKILL.md

305 239 

306# Project Skill240* **`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.

307code .claude/skills/my-skill/SKILL.md

308```

309 241 

310Changes take effect the next time you start Claude Code. If Claude Code is already running, restart it to load the updates.242* **`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.

311 243 

312## Remove a Skill244This example creates a deploy skill that only you can trigger. The `disable-model-invocation: true` field prevents Claude from running it automatically:

313 245 

314Delete the Skill directory:246```yaml theme={null}

247---

248name: deploy

249description: Deploy the application to production

250disable-model-invocation: true

251---

315 252 

316```bash theme={null}253Deploy $ARGUMENTS to production:

317# Personal

318rm -rf ~/.claude/skills/my-skill

319 254 

320# Project2551. Run the test suite

321rm -rf .claude/skills/my-skill2562. Build the application

322git commit -m "Remove unused Skill"2573. Push to the deployment target

2584. Verify the deployment succeeded

323```259```

324 260 

325## Best practices261Here's how the two fields affect invocation and context loading:

326 

327### Keep Skills focused

328 262 

329One Skill should address one capability:263| Frontmatter | You can invoke | Claude can invoke | When loaded into context |

264| :------------------------------- | :------------- | :---------------- | :----------------------------------------------------------- |

265| (default) | Yes | Yes | Description always in context, full skill loads when invoked |

266| `disable-model-invocation: true` | Yes | No | Description not in context, full skill loads when you invoke |

267| `user-invocable: false` | No | Yes | Description always in context, full skill loads when invoked |

330 268 

331**Focused**:269<Note>

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

271</Note>

332 272 

333* "PDF form filling"273### Restrict tool access

334* "Excel data analysis"

335* "Git commit messages"

336 274 

337**Too broad**:275Use 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:

338 276 

339* "Document processing" (split into separate Skills)277```yaml theme={null}

340* "Data tools" (split by data type or operation)278---

279name: safe-reader

280description: Read files without making changes

281allowed-tools: Read, Grep, Glob

282---

283```

341 284 

342### Write clear descriptions285### Pass arguments to skills

343 286 

344Help Claude discover when to use Skills by including specific triggers in your description:287Both you and Claude can pass arguments when invoking a skill. Arguments are available via the `$ARGUMENTS` placeholder.

345 288 

346**Clear**:289This skill fixes a GitHub issue by number. The `$ARGUMENTS` placeholder gets replaced with whatever follows the skill name:

347 290 

348```yaml theme={null}291```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.292---

350```293name: fix-issue

294description: Fix a GitHub issue

295disable-model-invocation: true

296---

351 297 

352**Vague**:298Fix GitHub issue $ARGUMENTS following our coding standards.

353 299 

354```yaml theme={null}3001. Read the issue description

355description: For files3012. Understand the requirements

3023. Implement the fix

3034. Write tests

3045. Create a commit

356```305```

357 306 

358### Test with your team307When you run `/fix-issue 123`, Claude receives "Fix GitHub issue 123 following our coding standards..."

359 308 

360Have teammates use Skills and provide feedback:309If you invoke a skill with arguments but the skill doesn't include `$ARGUMENTS`, Claude Code appends `ARGUMENTS: <your input>` to the end of the skill content so Claude still sees what you typed.

361 310 

362* Does the Skill activate when expected?311To access individual arguments by position, use `$ARGUMENTS[N]` or the shorter `$N`:

363* Are the instructions clear?

364* Are there missing examples or edge cases?

365 312 

366### Document Skill versions313```yaml theme={null}

367 314---

368You can document Skill versions in your SKILL.md content to track changes over time. Add a version history section:315name: migrate-component

369 316description: Migrate a component from one framework to another

370```markdown theme={null}317---

371# My Skill

372 318 

373## Version History319Migrate the $ARGUMENTS[0] component from $ARGUMENTS[1] to $ARGUMENTS[2].

374- v2.0.0 (2025-10-01): Breaking changes to API320Preserve 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```321```

378 322 

379This helps team members understand what changed between versions.323Running `/migrate-component SearchBar React Vue` replaces `$ARGUMENTS[0]` with `SearchBar`, `$ARGUMENTS[1]` with `React`, and `$ARGUMENTS[2]` with `Vue`. The same skill using the `$N` shorthand:

380 324 

381## Troubleshooting325```yaml theme={null}

326---

327name: migrate-component

328description: Migrate a component from one framework to another

329---

382 330 

383### Claude doesn't use my Skill331Migrate the $0 component from $1 to $2.

332Preserve all existing behavior and tests.

333```

384 334 

385**Symptom**: You ask a relevant question but Claude doesn't use your Skill.335## Advanced patterns

386 336 

387**Check**: Is the description specific enough?337### Inject dynamic context

388 338 

389Vague descriptions make discovery difficult. Include both what the Skill does and when to use it, with key terms users would mention.339The `!`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.

390 340 

391**Too generic**:341This 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:

392 342 

393```yaml theme={null}343```yaml theme={null}

394description: Helps with data344---

395```345name: pr-summary

346description: Summarize changes in a pull request

347context: fork

348agent: Explore

349allowed-tools: Bash(gh *)

350---

396 351 

397**Specific**:352## Pull request context

353- PR diff: !`gh pr diff`

354- PR comments: !`gh pr view --comments`

355- Changed files: !`gh pr diff --name-only`

398 356 

399```yaml theme={null}357## Your task

400description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files.358Summarize this pull request...

401```359```

402 360 

403**Check**: Is the YAML valid?361When this skill runs:

404 362 

405Run validation to check for syntax errors:3631. Each `!`command\`\` executes immediately (before Claude sees anything)

3642. The output replaces the placeholder in the skill content

3653. Claude receives the fully-rendered prompt with actual PR data

406 366 

407```bash theme={null}367This is preprocessing, not something Claude executes. Claude only sees the final result.

408# View frontmatter

409cat .claude/skills/my-skill/SKILL.md | head -n 15

410 368 

411# Check for common issues369<Tip>

412# - Missing opening or closing ---370 To enable [extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) in a skill, include the word "ultrathink" anywhere in your skill content.

413# - Tabs instead of spaces371</Tip>

414# - Unquoted strings with special characters

415```

416 372 

417**Check**: Is the Skill in the correct location?373### Run skills in a subagent

418 374 

419```bash theme={null}375Add `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.

420# Personal Skills

421ls ~/.claude/skills/*/SKILL.md

422 376 

423# Project Skills377<Warning>

424ls .claude/skills/*/SKILL.md378 `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.

425```379</Warning>

426 380 

427### Skill has errors381Skills and [subagents](/en/sub-agents) work together in two directions:

428 382 

429**Symptom**: The Skill loads but doesn't work correctly.383| Approach | System prompt | Task | Also loads |

384| :--------------------------- | :---------------------------------------- | :-------------------------- | :--------------------------- |

385| Skill with `context: fork` | From agent type (`Explore`, `Plan`, etc.) | SKILL.md content | CLAUDE.md |

386| Subagent with `skills` field | Subagent's markdown body | Claude's delegation message | Preloaded skills + CLAUDE.md |

430 387 

431**Check**: Are dependencies available?388With `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).

432 389 

433Claude will automatically install required dependencies (or ask for permission to install them) when it needs them.390#### Example: Research skill using Explore agent

434 391 

435**Check**: Do scripts have execute permissions?392This 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:

436 393 

437```bash theme={null}394```yaml theme={null}

438chmod +x .claude/skills/my-skill/scripts/*.py395---

439```396name: deep-research

397description: Research a topic thoroughly

398context: fork

399agent: Explore

400---

440 401 

441**Check**: Are file paths correct?402Research $ARGUMENTS thoroughly:

442 403 

443Use forward slashes (Unix style) in all paths:4041. Find relevant files using Glob and Grep

4052. Read and analyze the code

4063. Summarize findings with specific file references

407```

444 408 

445**Correct**: `scripts/helper.py`409When this skill runs:

446**Wrong**: `scripts\helper.py` (Windows style)

447 410 

448### Multiple Skills conflict4111. A new isolated context is created

4122. The subagent receives the skill content as its prompt ("Research \$ARGUMENTS thoroughly...")

4133. The `agent` field determines the execution environment (model, tools, and permissions)

4144. Results are summarized and returned to your main conversation

449 415 

450**Symptom**: Claude uses the wrong Skill or seems confused between similar Skills.416The `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`.

451 417 

452**Be specific in descriptions**: Help Claude choose the right Skill by using distinct trigger terms in your descriptions.418### Restrict Claude's skill access

453 419 

454Instead of:420By default, Claude can invoke any skill that doesn't have `disable-model-invocation: true` set. Skills that define `allowed-tools` grant Claude access to those tools without per-use approval when the skill is active. Your [permission settings](/en/permissions) still govern baseline approval behavior for all other tools. Built-in commands like `/compact` and `/init` are not available through the Skill tool.

455 421 

456```yaml theme={null}422Three ways to control which skills Claude can invoke:

457# Skill 1423 

458description: For data analysis424**Disable all skills** by denying the Skill tool in `/permissions`:

459 425 

460# Skill 2426```

461description: For analyzing data427# Add to deny rules:

428Skill

462```429```

463 430 

464Use:431**Allow or deny specific skills** using [permission rules](/en/permissions):

465 432 

466```yaml theme={null}433```

467# Skill 1434# Allow only specific skills

468description: Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking.435Skill(commit)

436Skill(review-pr *)

469 437 

470# Skill 2438# Deny specific skills

471description: Analyze log files and system metrics data. Use for performance monitoring, debugging, and system diagnostics.439Skill(deploy *)

472```440```

473 441 

474## Examples442Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments.

475 443 

476### Simple Skill (single file)444**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.

477 445 

478```446<Note>

479commit-helper/447 The `user-invocable` field only controls menu visibility, not Skill tool access. Use `disable-model-invocation: true` to block programmatic invocation.

480└── SKILL.md448</Note>

481```

482 449 

483```yaml theme={null}450## Share skills

484name: generating-commit-messages

485description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes.

486 451 

487# Generating Commit Messages452Skills can be distributed at different scopes depending on your audience:

488 453 

489## Instructions454* **Project skills**: Commit `.claude/skills/` to version control

455* **Plugins**: Create a `skills/` directory in your [plugin](/en/plugins)

456* **Managed**: Deploy organization-wide through [managed settings](/en/permissions#managed-settings)

490 457 

4911. Run `git diff --staged` to see changes458### Generate visual output

4922. I'll suggest a commit message with:

493 - Summary under 50 characters

494 - Detailed description

495 - Affected components

496 459 

497## Best practices460Skills 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 461 

499- Use present tense462This 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 463 

503### Skill with tool permissions464Create the Skill directory:

504 465 

505```466```bash theme={null}

506code-reviewer/467mkdir -p ~/.claude/skills/codebase-visualizer/scripts

507└── SKILL.md

508```468```

509 469 

510```yaml theme={null}470Create `~/.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:

471 

472````yaml theme={null}

511---473---

512name: code-reviewer474name: codebase-visualizer

513description: Review code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.475description: 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, Glob476allowed-tools: Bash(python *)

515---477---

516 478 

517# Code Reviewer479# Codebase Visualizer

518 480 

519## Review checklist481Generate an interactive HTML tree view that shows your project's file structure with collapsible directories.

520 482 

5211. Code organization and structure483## Usage

5222. Error handling

5233. Performance considerations

5244. Security concerns

5255. Test coverage

526 484 

527## Instructions485Run the visualization script from your project root:

528 486 

5291. Read the target files using Read tool487```bash

5302. Search for patterns using Grep488python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .

5313. Find related files using Glob

5324. Provide detailed feedback on code quality

533```489```

534 490 

535### Multi-file Skill491This creates `codebase-map.html` in the current directory and opens it in your default browser.

536 492 

537```493## 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 494 

547**SKILL.md**:495- **Collapsible directories**: Click folders to expand/collapse

548 496- **File sizes**: Displayed next to each file

549````yaml theme={null}497- **Colors**: Different colors for different file types

550name: pdf-processing498- **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.499````

552 500 

553# PDF Processing501Create `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with:

502 

503* A **summary sidebar** showing file count, directory count, total size, and number of file types

504* A **bar chart** breaking down the codebase by file type (top 8 by size)

505* A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators

506 

507The script requires Python but uses only built-in libraries, so there are no packages to install:

508 

509```python expandable theme={null}

510#!/usr/bin/env python3

511"""Generate an interactive collapsible tree visualization of a codebase."""

512 

513import json

514import sys

515import webbrowser

516from pathlib import Path

517from collections import Counter

518 

519IGNORE = {'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build'}

520 

521def scan(path: Path, stats: dict) -> dict:

522 result = {"name": path.name, "children": [], "size": 0}

523 try:

524 for item in sorted(path.iterdir()):

525 if item.name in IGNORE or item.name.startswith('.'):

526 continue

527 if item.is_file():

528 size = item.stat().st_size

529 ext = item.suffix.lower() or '(no ext)'

530 result["children"].append({"name": item.name, "size": size, "ext": ext})

531 result["size"] += size

532 stats["files"] += 1

533 stats["extensions"][ext] += 1

534 stats["ext_sizes"][ext] += size

535 elif item.is_dir():

536 stats["dirs"] += 1

537 child = scan(item, stats)

538 if child["children"]:

539 result["children"].append(child)

540 result["size"] += child["size"]

541 except PermissionError:

542 pass

543 return result

544 

545def generate_html(data: dict, stats: dict, output: Path) -> None:

546 ext_sizes = stats["ext_sizes"]

547 total_size = sum(ext_sizes.values()) or 1

548 sorted_exts = sorted(ext_sizes.items(), key=lambda x: -x[1])[:8]

549 colors = {

550 '.js': '#f7df1e', '.ts': '#3178c6', '.py': '#3776ab', '.go': '#00add8',

551 '.rs': '#dea584', '.rb': '#cc342d', '.css': '#264de4', '.html': '#e34c26',

552 '.json': '#6b7280', '.md': '#083fa1', '.yaml': '#cb171e', '.yml': '#cb171e',

553 '.mdx': '#083fa1', '.tsx': '#3178c6', '.jsx': '#61dafb', '.sh': '#4eaa25',

554 }

555 lang_bars = "".join(

556 f'<div class="bar-row"><span class="bar-label">{ext}</span>'

557 f'<div class="bar" style="width:{(size/total_size)*100}%;background:{colors.get(ext,"#6b7280")}"></div>'

558 f'<span class="bar-pct">{(size/total_size)*100:.1f}%</span></div>'

559 for ext, size in sorted_exts

560 )

561 def fmt(b):

562 if b < 1024: return f"{b} B"

563 if b < 1048576: return f"{b/1024:.1f} KB"

564 return f"{b/1048576:.1f} MB"

565 

566 html = f'''<!DOCTYPE html>

567<html><head>

568 <meta charset="utf-8"><title>Codebase Explorer</title>

569 <style>

570 body {{ font: 14px/1.5 system-ui, sans-serif; margin: 0; background: #1a1a2e; color: #eee; }}

571 .container {{ display: flex; height: 100vh; }}

572 .sidebar {{ width: 280px; background: #252542; padding: 20px; border-right: 1px solid #3d3d5c; overflow-y: auto; flex-shrink: 0; }}

573 .main {{ flex: 1; padding: 20px; overflow-y: auto; }}

574 h1 {{ margin: 0 0 10px 0; font-size: 18px; }}

575 h2 {{ margin: 20px 0 10px 0; font-size: 14px; color: #888; text-transform: uppercase; }}

576 .stat {{ display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #3d3d5c; }}

577 .stat-value {{ font-weight: bold; }}

578 .bar-row {{ display: flex; align-items: center; margin: 6px 0; }}

579 .bar-label {{ width: 55px; font-size: 12px; color: #aaa; }}

580 .bar {{ height: 18px; border-radius: 3px; }}

581 .bar-pct {{ margin-left: 8px; font-size: 12px; color: #666; }}

582 .tree {{ list-style: none; padding-left: 20px; }}

583 details {{ cursor: pointer; }}

584 summary {{ padding: 4px 8px; border-radius: 4px; }}

585 summary:hover {{ background: #2d2d44; }}

586 .folder {{ color: #ffd700; }}

587 .file {{ display: flex; align-items: center; padding: 4px 8px; border-radius: 4px; }}

588 .file:hover {{ background: #2d2d44; }}

589 .size {{ color: #888; margin-left: auto; font-size: 12px; }}

590 .dot {{ width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; }}

591 </style>

592</head><body>

593 <div class="container">

594 <div class="sidebar">

595 <h1>📊 Summary</h1>

596 <div class="stat"><span>Files</span><span class="stat-value">{stats["files"]:,}</span></div>

597 <div class="stat"><span>Directories</span><span class="stat-value">{stats["dirs"]:,}</span></div>

598 <div class="stat"><span>Total size</span><span class="stat-value">{fmt(data["size"])}</span></div>

599 <div class="stat"><span>File types</span><span class="stat-value">{len(stats["extensions"])}</span></div>

600 <h2>By file type</h2>

601 {lang_bars}

602 </div>

603 <div class="main">

604 <h1>📁 {data["name"]}</h1>

605 <ul class="tree" id="root"></ul>

606 </div>

607 </div>

608 <script>

609 const data = {json.dumps(data)};

610 const colors = {json.dumps(colors)};

611 function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }}

612 function render(node, parent) {{

613 if (node.children) {{

614 const det = document.createElement('details');

615 det.open = parent === document.getElementById('root');

616 det.innerHTML = `<summary><span class="folder">📁 ${{node.name}}</span><span class="size">${{fmt(node.size)}}</span></summary>`;

617 const ul = document.createElement('ul'); ul.className = 'tree';

618 node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name));

619 node.children.forEach(c => render(c, ul));

620 det.appendChild(ul);

621 const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li);

622 }} else {{

623 const li = document.createElement('li'); li.className = 'file';

624 li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{node.name}}<span class="size">${{fmt(node.size)}}</span>`;

625 parent.appendChild(li);

626 }}

627 }}

628 data.children.forEach(c => render(c, document.getElementById('root')));

629 </script>

630</body></html>'''

631 output.write_text(html)

632 

633if __name__ == '__main__':

634 target = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()

635 stats = {"files": 0, "dirs": 0, "extensions": Counter(), "ext_sizes": Counter()}

636 data = scan(target, stats)

637 out = Path('codebase-map.html')

638 generate_html(data, stats, out)

639 print(f'Generated {out.absolute()}')

640 webbrowser.open(f'file://{out.absolute()}')

641```

642 

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

644 

645This 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 646 

555## Quick start647## Troubleshooting

556 648 

557Extract text:649### Skill not triggering

558```python

559import pdfplumber

560with pdfplumber.open("doc.pdf") as pdf:

561 text = pdf.pages[0].extract_text()

562```

563 650 

564For form filling, see [FORMS.md](FORMS.md).651If Claude doesn't use your skill when expected:

565For detailed API reference, see [REFERENCE.md](REFERENCE.md).

566 652 

567## Requirements6531. Check the description includes keywords users would naturally say

6542. Verify the skill appears in `What skills are available?`

6553. Try rephrasing your request to match the description more closely

6564. Invoke it directly with `/skill-name` if the skill is user-invocable

568 657 

569Packages must be installed in your environment:658### Skill triggers too often

570```bash

571pip install pypdf pdfplumber

572```

573````

574 659 

575<Note>660If 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 661 

579Claude loads additional files only when needed.6621. Make the description more specific

6632. Add `disable-model-invocation: true` if you only want manual invocation

580 664 

581## Next steps665### Claude doesn't see all my skills

582 666 

583<CardGroup cols={2}>667Skill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget. The budget scales dynamically at 2% of the context window, with a fallback of 16,000 characters. Run `/context` to check for a warning about excluded skills.

584 <Card title="Authoring best practices" icon="lightbulb" href="https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices">

585 Write Skills that Claude can use effectively

586 </Card>

587 668 

588 <Card title="Agent Skills overview" icon="book" href="https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview">669To override the limit, set the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.

589 Learn how Skills work across Claude products

590 </Card>

591 670 

592 <Card title="Use Skills in the Agent SDK" icon="cube" href="https://docs.claude.com/en/docs/agent-sdk/skills">671## Related resources

593 Use Skills programmatically with TypeScript and Python

594 </Card>

595 672 

596 <Card title="Get started with Agent Skills" icon="rocket" href="https://docs.claude.com/en/docs/agents-and-tools/agent-skills/quickstart">673* **[Subagents](/en/sub-agents)**: delegate tasks to specialized agents

597 Create your first Skill674* **[Plugins](/en/plugins)**: package and distribute skills with other extensions

598 </Card>675* **[Hooks](/en/hooks)**: automate workflows around tool events

599</CardGroup>676* **[Memory](/en/memory)**: manage CLAUDE.md files for persistent context

677* **[Interactive mode](/en/interactive-mode#built-in-commands)**: built-in commands and shortcuts

678* **[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 Teams accounts, sessions created from Claude in Slack are

162automatically visible to the organization. See [Claude Code on the Web sharing](/en/claude-code-on-the-web#sharing-sessions)

163for more details.

164 

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 −491 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| `/bashes` | List and manage background tasks |

12| `/bug` | Report bugs (sends conversation to Anthropic) |

13| `/clear` | Clear conversation history |

14| `/compact [instructions]` | Compact conversation with optional focus instructions |

15| `/config` | Open the Settings interface (Config tab) |

16| `/context` | Visualize current context usage as a colored grid |

17| `/cost` | Show token usage statistics (see [cost tracking guide](/en/costs#using-the-cost-command) for subscription-specific details) |

18| `/doctor` | Checks the health of your Claude Code installation |

19| `/exit` | Exit the REPL |

20| `/export [filename]` | Export the current conversation to a file or clipboard |

21| `/help` | Get usage help |

22| `/hooks` | Manage hook configurations for tool events |

23| `/init` | Initialize project with CLAUDE.md guide |

24| `/login` | Switch Anthropic accounts |

25| `/logout` | Sign out from your Anthropic account |

26| `/mcp` | Manage MCP server connections and OAuth authentication |

27| `/memory` | Edit CLAUDE.md memory files |

28| `/model` | Select or change the AI model |

29| `/output-style [style]` | Set the output style directly or from a selection menu |

30| `/permissions` | View or update [permissions](/en/iam#configuring-permissions) |

31| `/pr_comments` | View pull request comments |

32| `/privacy-settings` | View and update your privacy settings |

33| `/review` | Request code review |

34| `/sandbox` | Enable sandboxed bash tool with filesystem and network isolation for safer, more autonomous execution |

35| `/rewind` | Rewind the conversation and/or code |

36| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |

37| `/statusline` | Set up Claude Code's status line UI |

38| `/terminal-setup` | Install Shift+Enter key binding for newlines (iTerm2 and VSCode only) |

39| `/todos` | List current todo items |

40| `/usage` | Show plan usage limits and rate limit status (subscription plans only) |

41| `/vim` | Enter vim mode for alternating insert and command modes |

42 

43## Custom slash commands

44 

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

46 

47### Syntax

48 

49```

50/<command-name> [arguments]

51```

52 

53#### Parameters

54 

55| Parameter | Description |

56| :--------------- | :---------------------------------------------------------------- |

57| `<command-name>` | Name derived from the Markdown filename (without `.md` extension) |

58| `[arguments]` | Optional arguments passed to the command |

59 

60### Command types

61 

62#### Project commands

63 

64Commands stored in your repository and shared with your team. When listed in `/help`, these commands show "(project)" after their description.

65 

66**Location**: `.claude/commands/`

67 

68In the following example, we create the `/optimize` command:

69 

70```bash theme={null}

71# Create a project command

72mkdir -p .claude/commands

73echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md

74```

75 

76#### Personal commands

77 

78Commands available across all your projects. When listed in `/help`, these commands show "(user)" after their description.

79 

80**Location**: `~/.claude/commands/`

81 

82In the following example, we create the `/security-review` command:

83 

84```bash theme={null}

85# Create a personal command

86mkdir -p ~/.claude/commands

87echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md

88```

89 

90### Features

91 

92#### Namespacing

93 

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

95 

96Conflicts between user and project level commands are not supported. Otherwise, multiple commands with the same base file name can coexist.

97 

98For example, a file at `.claude/commands/frontend/component.md` creates the command `/component` with description showing "(project:frontend)".

99Meanwhile, a file at `~/.claude/commands/component.md` creates the command `/component` with description showing "(user)".

100 

101#### Arguments

102 

103Pass dynamic values to commands using argument placeholders:

104 

105##### All arguments with `$ARGUMENTS`

106 

107The `$ARGUMENTS` placeholder captures all arguments passed to the command:

108 

109```bash theme={null}

110# Command definition

111echo 'Fix issue #$ARGUMENTS following our coding standards' > .claude/commands/fix-issue.md

112 

113# Usage

114> /fix-issue 123 high-priority

115# $ARGUMENTS becomes: "123 high-priority"

116```

117 

118##### Individual arguments with `$1`, `$2`, etc.

119 

120Access specific arguments individually using positional parameters (similar to shell scripts):

121 

122```bash theme={null}

123# Command definition

124echo 'Review PR #$1 with priority $2 and assign to $3' > .claude/commands/review-pr.md

125 

126# Usage

127> /review-pr 456 high alice

128# $1 becomes "456", $2 becomes "high", $3 becomes "alice"

129```

130 

131Use positional arguments when you need to:

132 

133* Access arguments individually in different parts of your command

134* Provide defaults for missing arguments

135* Build more structured commands with specific parameter roles

136 

137#### Bash command execution

138 

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

140 

141For example:

142 

143```markdown theme={null}

144allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)

145description: Create a git commit

146 

147## Context

148 

149- Current git status: !`git status`

150- Current git diff (staged and unstaged changes): !`git diff HEAD`

151- Current branch: !`git branch --show-current`

152- Recent commits: !`git log --oneline -10`

153 

154## Your task

155 

156Based on the above changes, create a single git commit.

157```

158 

159#### File references

160 

161Include file contents in commands using the `@` prefix to [reference files](/en/common-workflows#reference-files-and-directories).

162 

163For example:

164 

165```markdown theme={null}

166# Reference a specific file

167 

168Review the implementation in @src/utils/helpers.js

169 

170# Reference multiple files

171 

172Compare @src/old-version.js with @src/new-version.js

173```

174 

175#### Thinking mode

176 

177Slash commands can trigger extended thinking by including [extended thinking keywords](/en/common-workflows#use-extended-thinking).

178 

179### Frontmatter

180 

181Command files support frontmatter, useful for specifying metadata about the command:

182 

183| Frontmatter | Purpose | Default |

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

185| `allowed-tools` | List of tools the command can use | Inherits from the conversation |

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

187| `description` | Brief description of the command | Uses the first line from the prompt |

188| `model` | Specific model string (see [Models overview](https://docs.claude.com/en/docs/about-claude/models/overview)) | Inherits from the conversation |

189| `disable-model-invocation` | Whether to prevent `SlashCommand` tool from calling this command | false |

190 

191For example:

192 

193```markdown theme={null}

194allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)

195argument-hint: [message]

196description: Create a git commit

197model: claude-3-5-haiku-20241022

198 

199Create a git commit with message: $ARGUMENTS

200```

201 

202Example using positional arguments:

203 

204```markdown theme={null}

205argument-hint: [pr-number] [priority] [assignee]

206description: Review pull request

207 

208Review PR #$1 with priority $2 and assign to $3.

209Focus on security, performance, and code style.

210```

211 

212## Plugin commands

213 

214[Plugins](/en/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/plugin-marketplaces).

215 

216### How plugin commands work

217 

218Plugin commands are:

219 

220* **Namespaced**: Commands can use the format `/plugin-name:command-name` to avoid conflicts (plugin prefix is optional unless there are name collisions)

221* **Automatically available**: Once a plugin is installed and enabled, its commands appear in `/help`

222* **Fully integrated**: Support all command features (arguments, frontmatter, bash execution, file references)

223 

224### Plugin command structure

225 

226**Location**: `commands/` directory in plugin root

227 

228**File format**: Markdown files with frontmatter

229 

230**Basic command structure**:

231 

232```markdown theme={null}

233description: Brief description of what the command does

234 

235# Command Name

236 

237Detailed instructions for Claude on how to execute this command.

238Include specific guidance on parameters, expected outcomes, and any special considerations.

239```

240 

241**Advanced command features**:

242 

243* **Arguments**: Use placeholders like `{arg1}` in command descriptions

244* **Subdirectories**: Organize commands in subdirectories for namespacing

245* **Bash integration**: Commands can execute shell scripts and programs

246* **File references**: Commands can reference and modify project files

247 

248### Invocation patterns

249 

250```shell Direct command (when no conflicts) theme={null}

251/command-name

252```

253 

254```shell Plugin-prefixed (when needed for disambiguation) theme={null}

255/plugin-name:command-name

256```

257 

258```shell With arguments (if command supports them) theme={null}

259/command-name arg1 arg2

260```

261 

262## MCP slash commands

263 

264MCP servers can expose prompts as slash commands that become available in Claude Code. These commands are dynamically discovered from connected MCP servers.

265 

266### Command format

267 

268MCP commands follow the pattern:

269 

270```

271/mcp__<server-name>__<prompt-name> [arguments]

272```

273 

274### Features

275 

276#### Dynamic discovery

277 

278MCP commands are automatically available when:

279 

280* An MCP server is connected and active

281* The server exposes prompts through the MCP protocol

282* The prompts are successfully retrieved during connection

283 

284#### Arguments

285 

286MCP prompts can accept arguments defined by the server:

287 

288```

289# Without arguments

290> /mcp__github__list_prs

291 

292# With arguments

293> /mcp__github__pr_review 456

294> /mcp__jira__create_issue "Bug title" high

295```

296 

297#### Naming conventions

298 

299* Server and prompt names are normalized

300* Spaces and special characters become underscores

301* Names are lowercased for consistency

302 

303### Managing MCP connections

304 

305Use the `/mcp` command to:

306 

307* View all configured MCP servers

308* Check connection status

309* Authenticate with OAuth-enabled servers

310* Clear authentication tokens

311* View available tools and prompts from each server

312 

313### MCP permissions and wildcards

314 

315When configuring [permissions for MCP tools](/en/iam#tool-specific-permission-rules), note that **wildcards are not supported**:

316 

317* ✅ **Correct**: `mcp__github` (approves ALL tools from the github server)

318* ✅ **Correct**: `mcp__github__get_issue` (approves specific tool)

319* ❌ **Incorrect**: `mcp__github__*` (wildcards not supported)

320 

321To approve all tools from an MCP server, use just the server name: `mcp__servername`. To approve specific tools only, list each tool individually.

322 

323## `SlashCommand` tool

324 

325The `SlashCommand` tool allows Claude to execute [custom slash commands](/en/slash-commands#custom-slash-commands) programmatically

326during a conversation. This gives Claude the ability to invoke custom commands

327on your behalf when appropriate.

328 

329To encourage Claude to trigger `SlashCommand` tool, your instructions (prompts,

330CLAUDE.md, etc.) generally need to reference the command by name with its slash.

331 

332Example:

333 

334```

335> Run /write-unit-test when you are about to start writing tests.

336```

337 

338This tool puts each available custom slash command's metadata into context up to the

339character budget limit. You can use `/context` to monitor token usage and follow

340the operations below to manage context.

341 

342### `SlashCommand` tool supported commands

343 

344`SlashCommand` tool only supports custom slash commands that:

345 

346* Are user-defined. Built-in commands like `/compact` and `/init` are *not* supported.

347* Have the `description` frontmatter field populated. We use the `description` in the context.

348 

349For Claude Code versions >= 1.0.124, you can see which custom slash commands

350`SlashCommand` tool can invoke by running `claude --debug` and triggering a query.

351 

352### Disable `SlashCommand` tool

353 

354To prevent Claude from executing any slash commands via the tool:

355 

356```bash theme={null}

357/permissions

358# Add to deny rules: SlashCommand

359```

360 

361This will also remove SlashCommand tool (and the slash command descriptions) from context.

362 

363### Disable specific commands only

364 

365To prevent a specific slash command from becoming available, add

366`disable-model-invocation: true` to the slash command's frontmatter.

367 

368This will also remove the command's metadata from context.

369 

370### `SlashCommand` permission rules

371 

372The permission rules support:

373 

374* **Exact match**: `SlashCommand:/commit` (allows only `/commit` with no arguments)

375* **Prefix match**: `SlashCommand:/review-pr:*` (allows `/review-pr` with any arguments)

376 

377### Character budget limit

378 

379The `SlashCommand` tool includes a character budget to limit the size of command

380descriptions shown to Claude. This prevents token overflow when many commands

381are available.

382 

383The budget includes each custom slash command's name, args, and description.

384 

385* **Default limit**: 15,000 characters

386* **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable

387 

388When the character budget is exceeded, Claude will see only a subset of the

389available commands. In `/context`, a warning will show with "M of N commands".

390 

391## Skills vs slash commands

392 

393**Slash commands** and **Agent Skills** serve different purposes in Claude Code:

394 

395### Use slash commands for

396 

397**Quick, frequently-used prompts**:

398 

399* Simple prompt snippets you use often

400* Quick reminders or templates

401* Frequently-used instructions that fit in one file

402 

403**Examples**:

404 

405* `/review` → "Review this code for bugs and suggest improvements"

406* `/explain` → "Explain this code in simple terms"

407* `/optimize` → "Analyze this code for performance issues"

408 

409### Use Skills for

410 

411**Comprehensive capabilities with structure**:

412 

413* Complex workflows with multiple steps

414* Capabilities requiring scripts or utilities

415* Knowledge organized across multiple files

416* Team workflows you want to standardize

417 

418**Examples**:

419 

420* PDF processing Skill with form-filling scripts and validation

421* Data analysis Skill with reference docs for different data types

422* Documentation Skill with style guides and templates

423 

424### Key differences

425 

426| Aspect | Slash Commands | Agent Skills |

427| -------------- | -------------------------------- | ----------------------------------- |

428| **Complexity** | Simple prompts | Complex capabilities |

429| **Structure** | Single .md file | Directory with SKILL.md + resources |

430| **Discovery** | Explicit invocation (`/command`) | Automatic (based on context) |

431| **Files** | One file only | Multiple files, scripts, templates |

432| **Scope** | Project or personal | Project or personal |

433| **Sharing** | Via git | Via git |

434 

435### Example comparison

436 

437**As a slash command**:

438 

439```markdown theme={null}

440# .claude/commands/review.md

441Review this code for:

442- Security vulnerabilities

443- Performance issues

444- Code style violations

445```

446 

447Usage: `/review` (manual invocation)

448 

449**As a Skill**:

450 

451```

452.claude/skills/code-review/

453├── SKILL.md (overview and workflows)

454├── SECURITY.md (security checklist)

455├── PERFORMANCE.md (performance patterns)

456├── STYLE.md (style guide reference)

457└── scripts/

458 └── run-linters.sh

459```

460 

461Usage: "Can you review this code?" (automatic discovery)

462 

463The Skill provides richer context, validation scripts, and organized reference material.

464 

465### When to use each

466 

467**Use slash commands**:

468 

469* You invoke the same prompt repeatedly

470* The prompt fits in a single file

471* You want explicit control over when it runs

472 

473**Use Skills**:

474 

475* Claude should discover the capability automatically

476* Multiple files or scripts are needed

477* Complex workflows with validation steps

478* Team needs standardized, detailed guidance

479 

480Both slash commands and Skills can coexist. Use the approach that fits your needs.

481 

482Learn more about [Agent Skills](/en/skills).

483 

484## See also

485 

486* [Plugins](/en/plugins) - Extend Claude Code with custom commands through plugins

487* [Identity and Access Management](/en/iam) - Complete guide to permissions, including MCP tool permissions

488* [Interactive mode](/en/interactive-mode) - Shortcuts, input modes, and interactive features

489* [CLI reference](/en/cli-reference) - Command-line flags and options

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

491* [Memory management](/en/memory) - Managing Claude's memory across sessions

statusline.md +772 −124

Details

1# Status line configuration1> ## Documentation Index

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

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

2 4 

3> Create a custom status line for Claude Code to display contextual information5# Customize your status line

4 6 

5Make Claude Code your own with a custom status line that displays at the bottom of the Claude Code interface, similar to how terminal prompts (PS1) work in shells like Oh-my-zsh.7> Configure a custom status bar to monitor context window usage, costs, and git status in Claude Code

6 8 

7## Create a custom status line9The status line is a customizable bar at the bottom of Claude Code that runs any shell script you configure. It receives JSON session data on stdin and displays whatever your script prints, giving you a persistent, at-a-glance view of context usage, costs, git status, or anything else you want to track.

8 10 

9You can either:11Status lines are useful when you:

10 12 

11* Run `/statusline` to ask Claude Code to help you set up a custom status line. By default, it will try to reproduce your terminal's prompt, but you can provide additional instructions about the behavior you want to Claude Code, such as `/statusline show the model name in orange`13* Want to monitor context window usage as you work

14* Need to track session costs

15* Work across multiple sessions and need to distinguish them

16* Want git branch and status always visible

12 17 

13* Directly add a `statusLine` command to your `.claude/settings.json`:18Here's an example of a [multi-line status line](#display-multiple-lines) that displays git info on the first line and a color-coded context bar on the second.

19 

20<Frame>

21 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="A multi-line status line showing model name, directory, git branch on the first line, and a context usage progress bar with cost and duration on the second line" data-og-width="776" width="776" data-og-height="212" height="212" data-path="images/statusline-multiline.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=2e448b44c332620e6c9c2be4ded992e5 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f796af2db9c68ab2ddbc5136840b9551 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d29c13d6164773198a0b2c47b31f6c09 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d7720e5f51310185c0c02152f6c10d8b 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=b4e008cde27990a8d5783e41e5b93246 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=40ab24813303dc2e4c09f2675f3faf6e 2500w" />

22</Frame>

23 

24This page walks through [setting up a basic status line](#set-up-a-status-line), explains [how the data flows](#how-status-lines-work) from Claude Code to your script, lists [all the fields you can display](#available-data), and provides [ready-to-use examples](#examples) for common patterns like git status, cost tracking, and progress bars.

25 

26## Set up a status line

27 

28Use the [`/statusline` command](#use-the-statusline-command) to have Claude Code generate a script for you, or [manually create a script](#manually-configure-a-status-line) and add it to your settings.

29 

30### Use the /statusline command

31 

32The `/statusline` command accepts natural language instructions describing what you want displayed. Claude Code generates a script file in `~/.claude/` and updates your settings automatically:

33 

34```

35/statusline show model name and context percentage with a progress bar

36```

37 

38### Manually configure a status line

39 

40Add a `statusLine` field to your user settings (`~/.claude/settings.json`, where `~` is your home directory) or [project settings](/en/settings#settings-files). Set `type` to `"command"` and point `command` to a script path or an inline shell command. For a full walkthrough of creating a script, see [Build a status line step by step](#build-a-status-line-step-by-step).

14 41 

15```json theme={null}42```json theme={null}

16{43{

17 "statusLine": {44 "statusLine": {

18 "type": "command",45 "type": "command",

19 "command": "~/.claude/statusline.sh",46 "command": "~/.claude/statusline.sh",

20 "padding": 0 // Optional: set to 0 to let status line go to edge47 "padding": 2

21 }48 }

22}49}

23```50```

24 51 

25## How it Works52The `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:

26 53 

27* The status line is updated when the conversation messages update54```json theme={null}

28* Updates run at most every 300ms55{

29* The first line of stdout from your command becomes the status line text56 "statusLine": {

30* ANSI color codes are supported for styling your status line57 "type": "command",

31* Claude Code passes contextual information about the current session (model, directories, etc.) as JSON to your script via stdin58 "command": "jq -r '\"[\\(.model.display_name)] \\(.context_window.used_percentage // 0)% context\"'"

59 }

60}

61```

32 62 

33## JSON Input Structure63The 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.

34 64 

35Your status line command receives structured data via stdin in JSON format:65### Disable the status line

36 66 

37```json theme={null}67Run `/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.

38{68 

39 "hook_event_name": "Status",69## Build a status line step by step

40 "session_id": "abc123...",70 

41 "transcript_path": "/path/to/transcript.json",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.

72 

73<Note>Running [`/statusline`](#use-the-statusline-command) with a description of what you want configures all of this for you automatically.</Note>

74 

75These examples use Bash scripts, which work on macOS and Linux. On Windows, you can run Bash scripts through [WSL (Windows Subsystem for Linux)](https://learn.microsoft.com/en-us/windows/wsl/install) or rewrite them in PowerShell.

76 

77<Frame>

78 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=696445e59ca0059213250651ad23db6b" alt="A status line showing model name, directory, and context percentage" data-og-width="726" width="726" data-og-height="164" height="164" data-path="images/statusline-quickstart.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=728c4bd06c8559cb46ddffffad983373 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f9d28e0f8f48f695167dd1d632a6cf4f 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=57a2803a18cafe8cf1aa05619444f20c 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=52cdd52865842f0cda24489dd5310d3b 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f8876ea1f72bf40bd0aeec483ee20164 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-quickstart.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=6b1524305c7c71122cde65d0c3822374 2500w" />

79</Frame>

80 

81<Steps>

82 <Step title="Create a script that reads JSON and prints output">

83 Claude Code sends JSON data to your script via stdin. This script uses [`jq`](https://jqlang.github.io/jq/), a command-line JSON parser you may need to install, to extract the model name, directory, and context percentage, then prints a formatted line.

84 

85 Save this to `~/.claude/statusline.sh` (where `~` is your home directory, such as `/Users/username` on macOS or `/home/username` on Linux):

86 

87 ```bash theme={null}

88 #!/bin/bash

89 # Read JSON data that Claude Code sends to stdin

90 input=$(cat)

91 

92 # Extract fields using jq

93 MODEL=$(echo "$input" | jq -r '.model.display_name')

94 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

95 # The "// 0" provides a fallback if the field is null

96 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

97 

98 # Output the status line - ${DIR##*/} extracts just the folder name

99 echo "[$MODEL] 📁 ${DIR##*/} | ${PCT}% context"

100 ```

101 </Step>

102 

103 <Step title="Make it executable">

104 Mark the script as executable so your shell can run it:

105 

106 ```bash theme={null}

107 chmod +x ~/.claude/statusline.sh

108 ```

109 </Step>

110 

111 <Step title="Add to settings">

112 Tell Claude Code to run your script as the status line. Add this configuration to `~/.claude/settings.json`, which sets `type` to `"command"` (meaning "run this shell command") and points `command` to your script:

113 

114 ```json theme={null}

115 {

116 "statusLine": {

117 "type": "command",

118 "command": "~/.claude/statusline.sh"

119 }

120 }

121 ```

122 

123 Your status line appears at the bottom of the interface. Settings reload automatically, but changes won't appear until your next interaction with Claude Code.

124 </Step>

125</Steps>

126 

127## How status lines work

128 

129Claude Code runs your script and pipes [JSON session data](#available-data) to it via stdin. Your script reads the JSON, extracts what it needs, and prints text to stdout. Claude Code displays whatever your script prints.

130 

131**When it updates**

132 

133Your script runs after each new assistant message, when the permission mode changes, or when vim mode toggles. Updates are debounced at 300ms, meaning rapid changes batch together and your script runs once things settle. If a new update triggers while your script is still running, the in-flight execution is cancelled. If you edit your script, the changes won't appear until your next interaction with Claude Code triggers an update.

134 

135**What your script can output**

136 

137* **Multiple lines**: each `echo` or `print` statement displays as a separate row. See the [multi-line example](#display-multiple-lines).

138* **Colors**: use [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) like `\033[32m` for green (terminal must support them). See the [git status example](#git-status-with-colors).

139* **Links**: use [OSC 8 escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code#OSC) to make text clickable (Cmd+click on macOS, Ctrl+click on Windows/Linux). Requires a terminal that supports hyperlinks like iTerm2, Kitty, or WezTerm. See the [clickable links example](#clickable-links).

140 

141<Note>The status line runs locally and does not consume API tokens. It temporarily hides during certain UI interactions, including autocomplete suggestions, the help menu, and permission prompts.</Note>

142 

143## Available data

144 

145Claude Code sends the following JSON fields to your script via stdin:

146 

147| Field | Description |

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

149| `model.id`, `model.display_name` | Current model identifier and display name |

150| `cwd`, `workspace.current_dir` | Current working directory. Both fields contain the same value; `workspace.current_dir` is preferred for consistency with `workspace.project_dir`. |

151| `workspace.project_dir` | Directory where Claude Code was launched, which may differ from `cwd` if the working directory changes during a session |

152| `cost.total_cost_usd` | Total session cost in USD |

153| `cost.total_duration_ms` | Total wall-clock time since the session started, in milliseconds |

154| `cost.total_api_duration_ms` | Total time spent waiting for API responses in milliseconds |

155| `cost.total_lines_added`, `cost.total_lines_removed` | Lines of code changed |

156| `context_window.total_input_tokens`, `context_window.total_output_tokens` | Cumulative token counts across the session |

157| `context_window.context_window_size` | Maximum context window size in tokens. 200000 by default, or 1000000 for models with extended context. |

158| `context_window.used_percentage` | Pre-calculated percentage of context window used |

159| `context_window.remaining_percentage` | Pre-calculated percentage of context window remaining |

160| `context_window.current_usage` | Token counts from the last API call, described in [context window fields](#context-window-fields) |

161| `exceeds_200k_tokens` | Whether the total token count (input, cache, and output tokens combined) from the most recent API response exceeds 200k. This is a fixed threshold regardless of actual context window size. |

162| `session_id` | Unique session identifier |

163| `transcript_path` | Path to conversation transcript file |

164| `version` | Claude Code version |

165| `output_style.name` | Name of the current output style |

166| `vim.mode` | Current vim mode (`NORMAL` or `INSERT`) when [vim mode](/en/interactive-mode#vim-editor-mode) is enabled |

167| `agent.name` | Agent name when running with the `--agent` flag or agent settings configured |

168 

169<Accordion title="Full JSON schema">

170 Your status line command receives this JSON structure via stdin:

171 

172 ```json theme={null}

173 {

42 "cwd": "/current/working/directory",174 "cwd": "/current/working/directory",

175 "session_id": "abc123...",

176 "transcript_path": "/path/to/transcript.jsonl",

43 "model": {177 "model": {

44 "id": "claude-opus-4-1",178 "id": "claude-opus-4-6",

45 "display_name": "Opus"179 "display_name": "Opus"

46 },180 },

47 "workspace": {181 "workspace": {


58 "total_api_duration_ms": 2300,192 "total_api_duration_ms": 2300,

59 "total_lines_added": 156,193 "total_lines_added": 156,

60 "total_lines_removed": 23194 "total_lines_removed": 23

195 },

196 "context_window": {

197 "total_input_tokens": 15234,

198 "total_output_tokens": 4521,

199 "context_window_size": 200000,

200 "used_percentage": 8,

201 "remaining_percentage": 92,

202 "current_usage": {

203 "input_tokens": 8500,

204 "output_tokens": 1200,

205 "cache_creation_input_tokens": 5000,

206 "cache_read_input_tokens": 2000

61 }207 }

62}208 },

63```209 "exceeds_200k_tokens": false,

210 "vim": {

211 "mode": "NORMAL"

212 },

213 "agent": {

214 "name": "security-reviewer"

215 }

216 }

217 ```

64 218 

65## Example Scripts219 **Fields that may be absent** (not present in JSON):

66 220 

67### Simple Status Line221 * `vim`: appears only when vim mode is enabled

222 * `agent`: appears only when running with the `--agent` flag or agent settings configured

68 223 

69```bash theme={null}224 **Fields that may be `null`**:

70#!/bin/bash

71# Read JSON input from stdin

72input=$(cat)

73 225 

74# Extract values using jq226 * `context_window.current_usage`: `null` before the first API call in a session

75MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')227 * `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 228 

78echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}"229 Handle missing fields with conditional access and null values with fallback defaults in your scripts.

79```230</Accordion>

231 

232### Context window fields

233 

234The `context_window` object provides two ways to track context usage:

235 

236* **Cumulative totals** (`total_input_tokens`, `total_output_tokens`): sum of all tokens across the entire session, useful for tracking total consumption

237* **Current usage** (`current_usage`): token counts from the most recent API call, use this for accurate context percentage since it reflects the actual context state

238 

239The `current_usage` object contains:

240 

241* `input_tokens`: input tokens in current context

242* `output_tokens`: output tokens generated

243* `cache_creation_input_tokens`: tokens written to cache

244* `cache_read_input_tokens`: tokens read from cache

245 

246The `used_percentage` field is calculated from input tokens only: `input_tokens + cache_creation_input_tokens + cache_read_input_tokens`. It does not include `output_tokens`.

247 

248If you calculate context percentage manually from `current_usage`, use the same input-only formula to match `used_percentage`.

249 

250The `current_usage` object is `null` before the first API call in a session.

251 

252## Examples

253 

254These examples show common status line patterns. To use any example:

255 

2561. Save the script to a file like `~/.claude/statusline.sh` (or `.py`/`.js`)

2572. Make it executable: `chmod +x ~/.claude/statusline.sh`

2583. Add the path to your [settings](#manually-configure-a-status-line)

259 

260The Bash examples use [`jq`](https://jqlang.github.io/jq/) to parse JSON. Python and Node.js have built-in JSON parsing.

261 

262### Context window usage

263 

264Display the current model and context window usage with a visual progress bar. Each script reads JSON from stdin, extracts the `used_percentage` field, and builds a 10-character bar where filled blocks (▓) represent usage:

265 

266<Frame>

267 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=15b58ab3602f036939145dde3165c6f7" alt="A status line showing model name and a progress bar with percentage" data-og-width="448" width="448" data-og-height="152" height="152" data-path="images/statusline-context-window-usage.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=a18fecd31f06b16e984b1ab3310acbc0 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=2f4b3caff156efede2ded995dbaf167f 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=8f6b8c7e7d3a999c570e96ad2ea13d5a 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d9334e6a08e6f11a253733c8592774a9 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e79490da8f62952e4d92837c408e63dc 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-context-window-usage.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=6f7c9ef8e629a794969c54b24163f92d 2500w" />

268</Frame>

269 

270<CodeGroup>

271 ```bash Bash theme={null}

272 #!/bin/bash

273 # Read all of stdin into a variable

274 input=$(cat)

275 

276 # Extract fields with jq, "// 0" provides fallback for null

277 MODEL=$(echo "$input" | jq -r '.model.display_name')

278 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

279 

280 # Build progress bar: printf creates spaces, tr replaces with blocks

281 BAR_WIDTH=10

282 FILLED=$((PCT * BAR_WIDTH / 100))

283 EMPTY=$((BAR_WIDTH - FILLED))

284 BAR=""

285 [ "$FILLED" -gt 0 ] && BAR=$(printf "%${FILLED}s" | tr ' ' '▓')

286 [ "$EMPTY" -gt 0 ] && BAR="${BAR}$(printf "%${EMPTY}s" | tr ' ' '░')"

287 

288 echo "[$MODEL] $BAR $PCT%"

289 ```

290 

291 ```python Python theme={null}

292 #!/usr/bin/env python3

293 import json, sys

80 294 

81### Git-Aware Status Line295 # json.load reads and parses stdin in one step

296 data = json.load(sys.stdin)

297 model = data['model']['display_name']

298 # "or 0" handles null values

299 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

82 300 

83```bash theme={null}301 # String multiplication builds the bar

84#!/bin/bash302 filled = pct * 10 // 100

85# Read JSON input from stdin303 bar = '▓' * filled + '░' * (10 - filled)

86input=$(cat)

87 304 

88# Extract values using jq305 print(f"[{model}] {bar} {pct}%")

89MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')306 ```

90CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

91 307 

92# Show git branch if in a git repo308 ```javascript Node.js theme={null}

93GIT_BRANCH=""309 #!/usr/bin/env node

94if git rev-parse --git-dir > /dev/null 2>&1; then310 // Node.js reads stdin asynchronously with events

311 let input = '';

312 process.stdin.on('data', chunk => input += chunk);

313 process.stdin.on('end', () => {

314 const data = JSON.parse(input);

315 const model = data.model.display_name;

316 // Optional chaining (?.) safely handles null fields

317 const pct = Math.floor(data.context_window?.used_percentage || 0);

318 

319 // String.repeat() builds the bar

320 const filled = Math.floor(pct * 10 / 100);

321 const bar = '▓'.repeat(filled) + '░'.repeat(10 - filled);

322 

323 console.log(`[${model}] ${bar} ${pct}%`);

324 });

325 ```

326</CodeGroup>

327 

328### Git status with colors

329 

330Show git branch with color-coded indicators for staged and modified files. This script uses [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) for terminal colors: `\033[32m` is green, `\033[33m` is yellow, and `\033[0m` resets to default.

331 

332<Frame>

333 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e656f34f90d1d9a1d0e220988914345f" alt="A status line showing model, directory, git branch, and colored indicators for staged and modified files" data-og-width="742" width="742" data-og-height="178" height="178" data-path="images/statusline-git-context.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=c1bced5f46afdc9aae549702591f8457 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=debe46a7a888234ec692751243bba492 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=3a069d5c8b0395908e42f0e295fd4854 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=26aff0978865756d5ea299a22e5e9afd 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d5ac1d59881e6f2032af053557dc4590 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-git-context.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=46febbf34b0ee646502d095433132709 2500w" />

334</Frame>

335 

336Each script checks if the current directory is a git repository, counts staged and modified files, and displays color-coded indicators:

337 

338<CodeGroup>

339 ```bash Bash theme={null}

340 #!/bin/bash

341 input=$(cat)

342 

343 MODEL=$(echo "$input" | jq -r '.model.display_name')

344 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

345 

346 GREEN='\033[32m'

347 YELLOW='\033[33m'

348 RESET='\033[0m'

349 

350 if git rev-parse --git-dir > /dev/null 2>&1; then

95 BRANCH=$(git branch --show-current 2>/dev/null)351 BRANCH=$(git branch --show-current 2>/dev/null)

96 if [ -n "$BRANCH" ]; then352 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

97 GIT_BRANCH=" | 🌿 $BRANCH"353 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

354 

355 GIT_STATUS=""

356 [ "$STAGED" -gt 0 ] && GIT_STATUS="${GREEN}+${STAGED}${RESET}"

357 [ "$MODIFIED" -gt 0 ] && GIT_STATUS="${GIT_STATUS}${YELLOW}~${MODIFIED}${RESET}"

358 

359 echo -e "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH $GIT_STATUS"

360 else

361 echo "[$MODEL] 📁 ${DIR##*/}"

98 fi362 fi

99fi363 ```

100 364 

101echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}$GIT_BRANCH"365 ```python Python theme={null}

102```366 #!/usr/bin/env python3

367 import json, sys, subprocess, os

368 

369 data = json.load(sys.stdin)

370 model = data['model']['display_name']

371 directory = os.path.basename(data['workspace']['current_dir'])

372 

373 GREEN, YELLOW, RESET = '\033[32m', '\033[33m', '\033[0m'

374 

375 try:

376 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

377 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

378 staged_output = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

379 modified_output = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

380 staged = len(staged_output.split('\n')) if staged_output else 0

381 modified = len(modified_output.split('\n')) if modified_output else 0

382 

383 git_status = f"{GREEN}+{staged}{RESET}" if staged else ""

384 git_status += f"{YELLOW}~{modified}{RESET}" if modified else ""

385 

386 print(f"[{model}] 📁 {directory} | 🌿 {branch} {git_status}")

387 except:

388 print(f"[{model}] 📁 {directory}")

389 ```

390 

391 ```javascript Node.js theme={null}

392 #!/usr/bin/env node

393 const { execSync } = require('child_process');

394 const path = require('path');

395 

396 let input = '';

397 process.stdin.on('data', chunk => input += chunk);

398 process.stdin.on('end', () => {

399 const data = JSON.parse(input);

400 const model = data.model.display_name;

401 const dir = path.basename(data.workspace.current_dir);

402 

403 const GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RESET = '\x1b[0m';

404 

405 try {

406 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

407 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

408 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

409 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

410 

411 let gitStatus = staged ? `${GREEN}+${staged}${RESET}` : '';

412 gitStatus += modified ? `${YELLOW}~${modified}${RESET}` : '';

413 

414 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} ${gitStatus}`);

415 } catch {

416 console.log(`[${model}] 📁 ${dir}`);

417 }

418 });

419 ```

420</CodeGroup>

421 

422### Cost and duration tracking

423 

424Track your session's API costs and elapsed time. The `cost.total_cost_usd` field accumulates the cost of all API calls in the current session. The `cost.total_duration_ms` field measures total elapsed time since the session started, while `cost.total_api_duration_ms` tracks only the time spent waiting for API responses.

425 

426Each script formats cost as currency and converts milliseconds to minutes and seconds:

427 

428<Frame>

429 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=e3444a51fe6f3440c134bd5f1f08ad29" alt="A status line showing model name, session cost, and duration" data-og-width="588" width="588" data-og-height="180" height="180" data-path="images/statusline-cost-tracking.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=b1d35fa8acd792f559b6b1662ed10204 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=a3ed4330c3645fc28b87a6cab55be0b7 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=386ee2ed68a7d520eba20eac54f7fe52 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=479c2515e53f46d5d1da3b87a6dd993a 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=1340c7589a4cb89ec071234aba3571d1 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-cost-tracking.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=69056cf4fe3271770cac4dc1704bcd0a 2500w" />

430</Frame>

431 

432<CodeGroup>

433 ```bash Bash theme={null}

434 #!/bin/bash

435 input=$(cat)

436 

437 MODEL=$(echo "$input" | jq -r '.model.display_name')

438 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

439 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

440 

441 COST_FMT=$(printf '$%.2f' "$COST")

442 DURATION_SEC=$((DURATION_MS / 1000))

443 MINS=$((DURATION_SEC / 60))

444 SECS=$((DURATION_SEC % 60))

445 

446 echo "[$MODEL] 💰 $COST_FMT | ⏱️ ${MINS}m ${SECS}s"

447 ```

448 

449 ```python Python theme={null}

450 #!/usr/bin/env python3

451 import json, sys

452 

453 data = json.load(sys.stdin)

454 model = data['model']['display_name']

455 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

456 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

457 

458 duration_sec = duration_ms // 1000

459 mins, secs = duration_sec // 60, duration_sec % 60

460 

461 print(f"[{model}] 💰 ${cost:.2f} | ⏱️ {mins}m {secs}s")

462 ```

463 

464 ```javascript Node.js theme={null}

465 #!/usr/bin/env node

466 let input = '';

467 process.stdin.on('data', chunk => input += chunk);

468 process.stdin.on('end', () => {

469 const data = JSON.parse(input);

470 const model = data.model.display_name;

471 const cost = data.cost?.total_cost_usd || 0;

472 const durationMs = data.cost?.total_duration_ms || 0;

473 

474 const durationSec = Math.floor(durationMs / 1000);

475 const mins = Math.floor(durationSec / 60);

476 const secs = durationSec % 60;

477 

478 console.log(`[${model}] 💰 $${cost.toFixed(2)} | ⏱️ ${mins}m ${secs}s`);

479 });

480 ```

481</CodeGroup>

482 

483### Display multiple lines

484 

485Your script can output multiple lines to create a richer display. Each `echo` statement produces a separate row in the status area.

486 

487<Frame>

488 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=60f11387658acc9ff75158ae85f2ac87" alt="A multi-line status line showing model name, directory, git branch on the first line, and a context usage progress bar with cost and duration on the second line" data-og-width="776" width="776" data-og-height="212" height="212" data-path="images/statusline-multiline.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=2e448b44c332620e6c9c2be4ded992e5 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=f796af2db9c68ab2ddbc5136840b9551 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d29c13d6164773198a0b2c47b31f6c09 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d7720e5f51310185c0c02152f6c10d8b 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=b4e008cde27990a8d5783e41e5b93246 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-multiline.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=40ab24813303dc2e4c09f2675f3faf6e 2500w" />

489</Frame>

103 490 

104### Python Example491This 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:

105 492 

106```python theme={null}493<CodeGroup>

107#!/usr/bin/env python3494 ```bash Bash theme={null}

108import json495 #!/bin/bash

109import sys496 input=$(cat)

110import os

111 497 

112# Read JSON from stdin498 MODEL=$(echo "$input" | jq -r '.model.display_name')

113data = json.load(sys.stdin)499 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

500 COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')

501 PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

502 DURATION_MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')

114 503 

115# Extract values504 CYAN='\033[36m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; RESET='\033[0m'

116model = data['model']['display_name']505 

117current_dir = os.path.basename(data['workspace']['current_dir'])506 # Pick bar color based on context usage

507 if [ "$PCT" -ge 90 ]; then BAR_COLOR="$RED"

508 elif [ "$PCT" -ge 70 ]; then BAR_COLOR="$YELLOW"

509 else BAR_COLOR="$GREEN"; fi

510 

511 FILLED=$((PCT / 10)); EMPTY=$((10 - FILLED))

512 BAR=$(printf "%${FILLED}s" | tr ' ' '█')$(printf "%${EMPTY}s" | tr ' ' '░')

513 

514 MINS=$((DURATION_MS / 60000)); SECS=$(((DURATION_MS % 60000) / 1000))

515 

516 BRANCH=""

517 git rev-parse --git-dir > /dev/null 2>&1 && BRANCH=" | 🌿 $(git branch --show-current 2>/dev/null)"

518 

519 echo -e "${CYAN}[$MODEL]${RESET} 📁 ${DIR##*/}$BRANCH"

520 COST_FMT=$(printf '$%.2f' "$COST")

521 echo -e "${BAR_COLOR}${BAR}${RESET} ${PCT}% | ${YELLOW}${COST_FMT}${RESET} | ⏱️ ${MINS}m ${SECS}s"

522 ```

523 

524 ```python Python theme={null}

525 #!/usr/bin/env python3

526 import json, sys, subprocess, os

527 

528 data = json.load(sys.stdin)

529 model = data['model']['display_name']

530 directory = os.path.basename(data['workspace']['current_dir'])

531 cost = data.get('cost', {}).get('total_cost_usd', 0) or 0

532 pct = int(data.get('context_window', {}).get('used_percentage', 0) or 0)

533 duration_ms = data.get('cost', {}).get('total_duration_ms', 0) or 0

534 

535 CYAN, GREEN, YELLOW, RED, RESET = '\033[36m', '\033[32m', '\033[33m', '\033[31m', '\033[0m'

536 

537 bar_color = RED if pct >= 90 else YELLOW if pct >= 70 else GREEN

538 filled = pct // 10

539 bar = '█' * filled + '░' * (10 - filled)

540 

541 mins, secs = duration_ms // 60000, (duration_ms % 60000) // 1000

118 542 

119# Check for git branch

120git_branch = ""

121if os.path.exists('.git'):

122 try:543 try:

123 with open('.git/HEAD', 'r') as f:544 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True, stderr=subprocess.DEVNULL).strip()

124 ref = f.read().strip()545 branch = f" | 🌿 {branch}" if branch else ""

125 if ref.startswith('ref: refs/heads/'):

126 git_branch = f" | 🌿 {ref.replace('ref: refs/heads/', '')}"

127 except:546 except:

128 pass547 branch = ""

129 548 

130print(f"[{model}] 📁 {current_dir}{git_branch}")549 print(f"{CYAN}[{model}]{RESET} 📁 {directory}{branch}")

131```550 print(f"{bar_color}{bar}{RESET} {pct}% | {YELLOW}${cost:.2f}{RESET} | ⏱️ {mins}m {secs}s")

551 ```

132 552 

133### Node.js Example553 ```javascript Node.js theme={null}

554 #!/usr/bin/env node

555 const { execSync } = require('child_process');

556 const path = require('path');

557 

558 let input = '';

559 process.stdin.on('data', chunk => input += chunk);

560 process.stdin.on('end', () => {

561 const data = JSON.parse(input);

562 const model = data.model.display_name;

563 const dir = path.basename(data.workspace.current_dir);

564 const cost = data.cost?.total_cost_usd || 0;

565 const pct = Math.floor(data.context_window?.used_percentage || 0);

566 const durationMs = data.cost?.total_duration_ms || 0;

134 567 

135```javascript theme={null}568 const CYAN = '\x1b[36m', GREEN = '\x1b[32m', YELLOW = '\x1b[33m', RED = '\x1b[31m', RESET = '\x1b[0m';

136#!/usr/bin/env node

137 569 

138const fs = require('fs');570 const barColor = pct >= 90 ? RED : pct >= 70 ? YELLOW : GREEN;

139const path = require('path');571 const filled = Math.floor(pct / 10);

572 const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);

573 

574 const mins = Math.floor(durationMs / 60000);

575 const secs = Math.floor((durationMs % 60000) / 1000);

576 

577 let branch = '';

578 try {

579 branch = execSync('git branch --show-current', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

580 branch = branch ? ` | 🌿 ${branch}` : '';

581 } catch {}

582 

583 console.log(`${CYAN}[${model}]${RESET} 📁 ${dir}${branch}`);

584 console.log(`${barColor}${bar}${RESET} ${pct}% | ${YELLOW}$${cost.toFixed(2)}${RESET} | ⏱️ ${mins}m ${secs}s`);

585 });

586 ```

587</CodeGroup>

588 

589### Clickable links

590 

591This example creates a clickable link to your GitHub repository. It reads the git remote URL, converts SSH format to HTTPS with `sed`, and wraps the repo name in OSC 8 escape codes. Hold Cmd (macOS) or Ctrl (Windows/Linux) and click to open the link in your browser.

592 

593<Frame>

594 <img src="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=4bcc6e7deb7cf52f41ab85a219b52661" alt="A status line showing a clickable link to a GitHub repository" data-og-width="726" width="726" data-og-height="198" height="198" data-path="images/statusline-links.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=280&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=9386f78056f7be99599bcefe9e838180 280w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=560&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=d748012a0866c37dddc6babd4b7a88c4 560w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=840&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=bade8fbfcde957c1033c376c58b89131 840w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=1100&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=9f7e0c729ea093c3b39682619fd3f201 1100w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=1650&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=ccec17e90a89d82381888a4a9a8fa40e 1650w, https://mintcdn.com/claude-code/nibzesLaJVh4ydOq/images/statusline-links.png?w=2500&fit=max&auto=format&n=nibzesLaJVh4ydOq&q=85&s=4d2e34a4d2f24e174cae1256c84f9a52 2500w" />

595</Frame>

596 

597Each script gets the git remote URL, converts SSH format to HTTPS, and wraps the repo name in OSC 8 escape codes. The Bash version uses `printf '%b'` which interprets backslash escapes more reliably than `echo -e` across different shells:

598 

599<CodeGroup>

600 ```bash Bash theme={null}

601 #!/bin/bash

602 input=$(cat)

603 

604 MODEL=$(echo "$input" | jq -r '.model.display_name')

605 

606 # Convert git SSH URL to HTTPS

607 REMOTE=$(git remote get-url origin 2>/dev/null | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//')

608 

609 if [ -n "$REMOTE" ]; then

610 REPO_NAME=$(basename "$REMOTE")

611 # OSC 8 format: \e]8;;URL\a then TEXT then \e]8;;\a

612 # printf %b interprets escape sequences reliably across shells

613 printf '%b' "[$MODEL] 🔗 \e]8;;${REMOTE}\a${REPO_NAME}\e]8;;\a\n"

614 else

615 echo "[$MODEL]"

616 fi

617 ```

140 618 

141// Read JSON from stdin619 ```python Python theme={null}

142let input = '';620 #!/usr/bin/env python3

143process.stdin.on('data', chunk => input += chunk);621 import json, sys, subprocess, re, os

144process.stdin.on('end', () => {622 

623 data = json.load(sys.stdin)

624 model = data['model']['display_name']

625 

626 # Get git remote URL

627 try:

628 remote = subprocess.check_output(

629 ['git', 'remote', 'get-url', 'origin'],

630 stderr=subprocess.DEVNULL, text=True

631 ).strip()

632 # Convert SSH to HTTPS format

633 remote = re.sub(r'^git@github\.com:', 'https://github.com/', remote)

634 remote = re.sub(r'\.git$', '', remote)

635 repo_name = os.path.basename(remote)

636 # OSC 8 escape sequences

637 link = f"\033]8;;{remote}\a{repo_name}\033]8;;\a"

638 print(f"[{model}] 🔗 {link}")

639 except:

640 print(f"[{model}]")

641 ```

642 

643 ```javascript Node.js theme={null}

644 #!/usr/bin/env node

645 const { execSync } = require('child_process');

646 const path = require('path');

647 

648 let input = '';

649 process.stdin.on('data', chunk => input += chunk);

650 process.stdin.on('end', () => {

145 const data = JSON.parse(input);651 const data = JSON.parse(input);

652 const model = data.model.display_name;

653 

654 try {

655 let remote = execSync('git remote get-url origin', { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();

656 // Convert SSH to HTTPS format

657 remote = remote.replace(/^git@github\.com:/, 'https://github.com/').replace(/\.git$/, '');

658 const repoName = path.basename(remote);

659 // OSC 8 escape sequences

660 const link = `\x1b]8;;${remote}\x07${repoName}\x1b]8;;\x07`;

661 console.log(`[${model}] 🔗 ${link}`);

662 } catch {

663 console.log(`[${model}]`);

664 }

665 });

666 ```

667</CodeGroup>

668 

669### Cache expensive operations

670 

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

672 

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

674 

675Each script checks if the cache file is missing or older than 5 seconds before running git commands:

676 

677<CodeGroup>

678 ```bash Bash theme={null}

679 #!/bin/bash

680 input=$(cat)

681 

682 MODEL=$(echo "$input" | jq -r '.model.display_name')

683 DIR=$(echo "$input" | jq -r '.workspace.current_dir')

684 

685 CACHE_FILE="/tmp/statusline-git-cache"

686 CACHE_MAX_AGE=5 # seconds

687 

688 cache_is_stale() {

689 [ ! -f "$CACHE_FILE" ] || \

690 # stat -f %m is macOS, stat -c %Y is Linux

691 [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0))) -gt $CACHE_MAX_AGE ]

692 }

693 

694 if cache_is_stale; then

695 if git rev-parse --git-dir > /dev/null 2>&1; then

696 BRANCH=$(git branch --show-current 2>/dev/null)

697 STAGED=$(git diff --cached --numstat 2>/dev/null | wc -l | tr -d ' ')

698 MODIFIED=$(git diff --numstat 2>/dev/null | wc -l | tr -d ' ')

699 echo "$BRANCH|$STAGED|$MODIFIED" > "$CACHE_FILE"

700 else

701 echo "||" > "$CACHE_FILE"

702 fi

703 fi

704 

705 IFS='|' read -r BRANCH STAGED MODIFIED < "$CACHE_FILE"

706 

707 if [ -n "$BRANCH" ]; then

708 echo "[$MODEL] 📁 ${DIR##*/} | 🌿 $BRANCH +$STAGED ~$MODIFIED"

709 else

710 echo "[$MODEL] 📁 ${DIR##*/}"

711 fi

712 ```

146 713 

147 // Extract values714 ```python Python theme={null}

715 #!/usr/bin/env python3

716 import json, sys, subprocess, os, time

717 

718 data = json.load(sys.stdin)

719 model = data['model']['display_name']

720 directory = os.path.basename(data['workspace']['current_dir'])

721 

722 CACHE_FILE = "/tmp/statusline-git-cache"

723 CACHE_MAX_AGE = 5 # seconds

724 

725 def cache_is_stale():

726 if not os.path.exists(CACHE_FILE):

727 return True

728 return time.time() - os.path.getmtime(CACHE_FILE) > CACHE_MAX_AGE

729 

730 if cache_is_stale():

731 try:

732 subprocess.check_output(['git', 'rev-parse', '--git-dir'], stderr=subprocess.DEVNULL)

733 branch = subprocess.check_output(['git', 'branch', '--show-current'], text=True).strip()

734 staged = subprocess.check_output(['git', 'diff', '--cached', '--numstat'], text=True).strip()

735 modified = subprocess.check_output(['git', 'diff', '--numstat'], text=True).strip()

736 staged_count = len(staged.split('\n')) if staged else 0

737 modified_count = len(modified.split('\n')) if modified else 0

738 with open(CACHE_FILE, 'w') as f:

739 f.write(f"{branch}|{staged_count}|{modified_count}")

740 except:

741 with open(CACHE_FILE, 'w') as f:

742 f.write("||")

743 

744 with open(CACHE_FILE) as f:

745 branch, staged, modified = f.read().strip().split('|')

746 

747 if branch:

748 print(f"[{model}] 📁 {directory} | 🌿 {branch} +{staged} ~{modified}")

749 else:

750 print(f"[{model}] 📁 {directory}")

751 ```

752 

753 ```javascript Node.js theme={null}

754 #!/usr/bin/env node

755 const { execSync } = require('child_process');

756 const fs = require('fs');

757 const path = require('path');

758 

759 let input = '';

760 process.stdin.on('data', chunk => input += chunk);

761 process.stdin.on('end', () => {

762 const data = JSON.parse(input);

148 const model = data.model.display_name;763 const model = data.model.display_name;

149 const currentDir = path.basename(data.workspace.current_dir);764 const dir = path.basename(data.workspace.current_dir);

150 765 

151 // Check for git branch766 const CACHE_FILE = '/tmp/statusline-git-cache';

152 let gitBranch = '';767 const CACHE_MAX_AGE = 5; // seconds

768 

769 const cacheIsStale = () => {

770 if (!fs.existsSync(CACHE_FILE)) return true;

771 return (Date.now() / 1000) - fs.statSync(CACHE_FILE).mtimeMs / 1000 > CACHE_MAX_AGE;

772 };

773 

774 if (cacheIsStale()) {

153 try {775 try {

154 const headContent = fs.readFileSync('.git/HEAD', 'utf8').trim();776 execSync('git rev-parse --git-dir', { stdio: 'ignore' });

155 if (headContent.startsWith('ref: refs/heads/')) {777 const branch = execSync('git branch --show-current', { encoding: 'utf8' }).trim();

156 gitBranch = ` | 🌿 ${headContent.replace('ref: refs/heads/', '')}`;778 const staged = execSync('git diff --cached --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

779 const modified = execSync('git diff --numstat', { encoding: 'utf8' }).trim().split('\n').filter(Boolean).length;

780 fs.writeFileSync(CACHE_FILE, `${branch}|${staged}|${modified}`);

781 } catch {

782 fs.writeFileSync(CACHE_FILE, '||');

157 }783 }

158 } catch (e) {

159 // Not a git repo or can't read HEAD

160 }784 }

161 785 

162 console.log(`[${model}] 📁 ${currentDir}${gitBranch}`);786 const [branch, staged, modified] = fs.readFileSync(CACHE_FILE, 'utf8').trim().split('|');

163});

164```

165 787 

166### Helper Function Approach788 if (branch) {

167 789 console.log(`[${model}] 📁 ${dir} | 🌿 ${branch} +${staged} ~${modified}`);

168For more complex bash scripts, you can create helper functions:790 } else {

169 791 console.log(`[${model}] 📁 ${dir}`);

170```bash theme={null}792 }

171#!/bin/bash793 });

172# Read JSON input once794 ```

173input=$(cat)795</CodeGroup>

174 

175# Helper functions for common extractions

176get_model_name() { echo "$input" | jq -r '.model.display_name'; }

177get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; }

178get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; }

179get_version() { echo "$input" | jq -r '.version'; }

180get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; }

181get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; }

182get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; }

183get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; }

184 

185# Use the helpers

186MODEL=$(get_model_name)

187DIR=$(get_current_dir)

188echo "[$MODEL] 📁 ${DIR##*/}"

189```

190 796 

191## Tips797## Tips

192 798 

193* Keep your status line concise - it should fit on one line799* **Test with mock input**: `echo '{"model":{"display_name":"Opus"},"context_window":{"used_percentage":25}}' | ./statusline.sh`

194* Use emojis (if your terminal supports them) and colors to make information scannable800* **Keep output short**: the status bar has limited width, so long output may get truncated or wrap awkwardly

195* Use `jq` for JSON parsing in Bash (see examples above)801* **Cache slow operations**: your script runs frequently during active sessions, so commands like `git status` can cause lag. See the [caching example](#cache-expensive-operations) for how to handle this.

196* Test your script by running it manually with mock JSON input: `echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/test"}}' | ./statusline.sh`802 

197* Consider caching expensive operations (like git status) if needed803Community projects like [ccstatusline](https://github.com/sirmalloc/ccstatusline) and [starship-claude](https://github.com/martinemde/starship-claude) provide pre-built configurations with themes and additional features.

198 804 

199## Troubleshooting805## Troubleshooting

200 806 

201* If your status line doesn't appear, check that your script is executable (`chmod +x`)807**Status line not appearing**

202* Ensure your script outputs to stdout (not stderr)808 

809* Verify your script is executable: `chmod +x ~/.claude/statusline.sh`

810* Check that your script outputs to stdout, not stderr

811* Run your script manually to verify it produces output

812* If `disableAllHooks` is set to `true` in your settings, the status line is also disabled. Remove this setting or set it to `false` to re-enable.

813 

814**Status line shows `--` or empty values**

815 

816* Fields may be `null` before the first API response completes

817* Handle null values in your script with fallbacks such as `// 0` in jq

818* Restart Claude Code if values remain empty after multiple messages

819 

820**Context percentage shows unexpected values**

821 

822* Use `used_percentage` for accurate context state rather than cumulative totals

823* The `total_input_tokens` and `total_output_tokens` are cumulative across the session and may exceed the context window size

824* Context percentage may differ from `/context` output due to when each is calculated

825 

826**OSC 8 links not clickable**

827 

828* Verify your terminal supports OSC 8 hyperlinks (iTerm2, Kitty, WezTerm)

829* Terminal.app does not support clickable links

830* SSH and tmux sessions may strip OSC sequences depending on configuration

831* If escape sequences appear as literal text like `\e]8;;`, use `printf '%b'` instead of `echo -e` for more reliable escape handling

832 

833**Display glitches with escape sequences**

834 

835* Complex escape sequences (ANSI colors, OSC 8 links) can occasionally cause garbled output if they overlap with other UI updates

836* If you see corrupted text, try simplifying your script to plain text output

837* Multi-line status lines with escape codes are more prone to rendering issues than single-line plain text

838 

839**Script errors or hangs**

840 

841* Scripts that exit with non-zero codes or produce no output cause the status line to go blank

842* Slow scripts block the status line from updating until they complete. Keep scripts fast to avoid stale output.

843* If a new update triggers while a slow script is running, the in-flight script is cancelled

844* Test your script independently with mock input before configuring it

845 

846**Notifications share the status line row**

847 

848* System notifications like MCP server errors, auto-updates, and token warnings display on the right side of the same row as your status line

849* Enabling verbose mode adds a token counter to this area

850* On narrow terminals, these notifications may truncate your status line output

sub-agents.md +560 −232

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.

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

6 38 

7## What are subagents?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.

8 40 

9Subagents are pre-configured AI personalities that Claude Code can delegate tasks to. Each subagent: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>

10 43 

11* Has a specific purpose and expertise area44 <Tab title="Plan">

12* Uses its own context window separate from the main conversation45 A research agent used during [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan.

13* Can be configured with specific tools it's allowed to use

14* Includes a custom system prompt that guides its behavior

15 46 

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.47 * **Model**: Inherits from main conversation

48 * **Tools**: Read-only tools (denied access to Write and Edit tools)

49 * **Purpose**: Codebase research for planning

17 50 

18## Key benefits51 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>

19 53 

20<CardGroup cols={2}>54 <Tab title="General-purpose">

21 <Card title="Context preservation" icon="layer-group">55 A capable agent for complex, multi-step tasks that require both exploration and action.

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 56 

25 <Card title="Specialized expertise" icon="brain">57 * **Model**: Inherits from main conversation

26 Subagents can be fine-tuned with detailed instructions for specific domains, leading to higher success rates on designated tasks.58 * **Tools**: All tools

27 </Card>59 * **Purpose**: Complex research, multi-step operations, code modifications

28 60 

29 <Card title="Reusability" icon="rotate">61 Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps.

30 Once created, subagents can be used across different projects and shared with your team for consistent workflows.62 </Tab>

31 </Card>

32 63 

33 <Card title="Flexible permissions" icon="shield-check">64 <Tab title="Other">

34 Each subagent can have different tool access levels, allowing you to limit powerful tools to specific subagent types.65 Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly.

35 </Card>

36</CardGroup>

37 66 

38## Quick start67 | Agent | Model | When Claude uses it |

68 | :---------------- | :------- | :------------------------------------------------------- |

69 | Bash | Inherits | Running terminal commands in a separate context |

70 | statusline-setup | Sonnet | When you run `/statusline` to configure your status line |

71 | Claude Code Guide | Haiku | When you ask questions about Claude Code features |

72 </Tab>

73</Tabs>

39 74 

40To create your first subagent:75Beyond 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.

76 

77## Quickstart: create your first subagent

78 

79Subagents are defined in Markdown files with YAML frontmatter. You can [create them manually](#write-subagent-files) or use the `/agents` command.

80 

81This walkthrough guides you through creating a user-level subagent with the `/agent` command. The subagent reviews code and suggests improvements for the codebase.

41 82 

42<Steps>83<Steps>

43 <Step title="Open the subagents interface">84 <Step title="Open the subagents interface">

44 Run the following command:85 In Claude Code, run:

45 86 

46 ```87 ```

47 /agents88 /agents

48 ```89 ```

49 </Step>90 </Step>

50 91 

51 <Step title="Select 'Create New Agent'">92 <Step title="Create a new user-level agent">

52 Choose whether to create a project-level or user-level subagent93 Select **Create new agent**, then choose **User-level**. This saves the subagent to `~/.claude/agents/` so it's available in all your projects.

94 </Step>

95 

96 <Step title="Generate with Claude">

97 Select **Generate with Claude**. When prompted, describe the subagent:

98 

99 ```

100 A code improvement agent that scans files and suggests improvements

101 for readability, performance, and best practices. It should explain

102 each issue, show the current code, and provide an improved version.

103 ```

104 

105 Claude generates the system prompt and configuration. Press `e` to open it in your editor if you want to customize it.

106 </Step>

107 

108 <Step title="Select tools">

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

110 </Step>

111 

112 <Step title="Select model">

113 Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns.

53 </Step>114 </Step>

54 115 

55 <Step title="Define the subagent">116 <Step title="Choose a color">

56 * **Recommended**: Generate with Claude first, then customize to make it yours117 Pick a background color for the subagent. This helps you identify which subagent is running in the UI.

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>118 </Step>

62 119 

63 <Step title="Save and use">120 <Step title="Save and try it out">

64 Your subagent is now available! Claude will use it automatically when appropriate, or you can invoke it explicitly:121 Save the subagent. It's available immediately (no restart needed). Try it:

65 122 

66 ```123 ```

67 > Use the code-reviewer subagent to check my recent changes124 Use the code-improver agent to suggest improvements in this project

68 ```125 ```

126 

127 Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.

69 </Step>128 </Step>

70</Steps>129</Steps>

71 130 

72## Subagent configuration131You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements.

73 132 

74### File locations133You 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 134 

76Subagents are stored as Markdown files with YAML frontmatter in two possible locations:135## Configure subagents

77 136 

78| Type | Location | Scope | Priority |137### 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 138 

83When subagent names conflict, project-level subagents take precedence over user-level subagents.139The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to:

84 140 

85### Plugin agents141* View all available subagents (built-in, user, project, and plugin)

142* Create new subagents with guided setup or Claude generation

143* Edit existing subagent configuration and tool access

144* Delete custom subagents

145* See which subagents are active when duplicates exist

86 146 

87[Plugins](/en/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.147This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.

88 148 

89**Plugin agent locations**: Plugins include agents in their `agents/` directory (or custom paths specified in the plugin manifest).149### Choose the subagent scope

90 150 

91**Using plugin agents**:151Subagents 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 152 

93* Plugin agents appear in `/agents` alongside your custom agents153| Location | Scope | Priority | How to create |

94* Can be invoked explicitly: "Use the code-reviewer agent from the security-plugin"154| :--------------------------- | :---------------------- | :---------- | :------------------------------------ |

95* Can be invoked automatically by Claude when appropriate155| `--agents` CLI flag | Current session | 1 (highest) | Pass JSON when launching Claude Code |

96* Can be managed (viewed, inspected) through `/agents` interface156| `.claude/agents/` | Current project | 2 | Interactive or manual |

157| `~/.claude/agents/` | All your projects | 3 | Interactive or manual |

158| Plugin's `agents/` directory | Where plugin is enabled | 4 (lowest) | Installed with [plugins](/en/plugins) |

97 159 

98See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin agents.160**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 161 

100### CLI-based configuration162**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.

101 163 

102You can also define subagents dynamically using the `--agents` CLI flag, which accepts a JSON object:164**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:

103 165 

104```bash theme={null}166```bash theme={null}

105claude --agents '{167claude --agents '{


112}'174}'

113```175```

114 176 

115**Priority**: CLI-defined subagents have lower priority than project-level subagents but higher priority than user-level subagents.177The `--agents` flag accepts JSON with the same [frontmatter](#supported-frontmatter-fields) fields as file-based subagents: `description`, `prompt`, `tools`, `disallowedTools`, `model`, `permissionMode`, `mcpServers`, `hooks`, `maxTurns`, `skills`, and `memory`. Use `prompt` for the system prompt, equivalent to the markdown body in file-based subagents. See the [CLI reference](/en/cli-reference#agents-flag-format) for the full JSON format.

116 

117**Use case**: This approach is useful for:

118 178 

119* Quick testing of subagent configurations179**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.

120* Session-specific subagents that don't need to be saved

121* Automation scripts that need custom subagents

122* Sharing subagent definitions in documentation or scripts

123 180 

124For detailed information about the JSON format and all available options, see the [CLI reference documentation](/en/cli-reference#agents-flag-format).181### Write subagent files

125 182 

126### File format183Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:

127 184 

128Each subagent is defined in a Markdown file with this structure:185<Note>

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

187</Note>

129 188 

130```markdown theme={null}189```markdown theme={null}

131---190---

132name: your-sub-agent-name191name: code-reviewer

133description: Description of when this subagent should be invoked192description: Reviews code for quality and best practices

134tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted193tools: Read, Glob, Grep

135model: sonnet # Optional - specify model alias or 'inherit'194model: sonnet

136permissionMode: default # Optional - permission mode for the subagent

137skills: skill1, skill2 # Optional - skills to auto-load

138---195---

139 196 

140Your subagent's system prompt goes here. This can be multiple paragraphs197You are a code reviewer. When invoked, analyze the code and provide

141and should clearly define the subagent's role, capabilities, and approach198specific, actionable feedback on quality, security, and best practices.

142to solving problems.

143 

144Include specific instructions, best practices, and any constraints

145the subagent should follow.

146```199```

147 200 

148#### Configuration fields201The 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.

202 

203#### Supported frontmatter fields

204 

205The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.

149 206 

150| Field | Required | Description |207| Field | Required | Description |

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

152| `name` | Yes | Unique identifier using lowercase letters and hyphens |209| `name` | Yes | Unique identifier using lowercase letters and hyphens |

153| `description` | Yes | Natural language description of the subagent's purpose |210| `description` | Yes | When Claude should delegate to this subagent |

154| `tools` | No | Comma-separated list of specific tools. If omitted, inherits all tools from the main thread |211| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |

155| `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/model-config) |212| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |

156| `permissionMode` | No | Permission mode for the subagent. Valid values: `default`, `acceptEdits`, `bypassPermissions`, `plan`, `ignore`. Controls how the subagent handles permission requests |213| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `inherit` |

157| `skills` | No | Comma-separated list of skill names to auto-load when the subagent starts. Skills are loaded into the subagent's context automatically |214| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `delegate`, `dontAsk`, `bypassPermissions`, or `plan` |

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

216| `skills` | No | [Skills](/en/skills) to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation |

217| `mcpServers` | No | [MCP servers](/en/mcp) available to this subagent. Each entry is either a server name referencing an already-configured server (e.g., `"slack"`) or an inline definition with the server name as key and a full [MCP server config](/en/mcp#configure-mcp-servers) as value |

218| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |

219| `memory` | No | [Persistent memory scope](#enable-persistent-memory): `user`, `project`, or `local`. Enables cross-session learning |

158 220 

159### Model selection221### Choose a model

160 222 

161The `model` field allows you to control which [AI model](/en/model-config) the subagent uses:223The `model` field controls which [AI model](/en/model-config) the subagent uses:

162 224 

163* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`225* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`

164* **`'inherit'`**: Use the same model as the main conversation (useful for consistency)226* **inherit**: Use the same model as the main conversation

165* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)227* **Omitted**: If not specified, defaults to `inherit` (uses the same model as the main conversation)

228 

229### Control subagent capabilities

230 

231You can control what subagents can do through tool access, permission modes, and conditional rules.

232 

233#### Available tools

234 

235Subagents can use any of Claude Code's [internal tools](/en/settings#tools-available-to-claude). By default, subagents inherit all tools from the main conversation, including MCP tools.

236 

237To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist):

238 

239```yaml theme={null}

240---

241name: safe-researcher

242description: Research agent with restricted capabilities

243tools: Read, Grep, Glob, Bash

244disallowedTools: Write, Edit

245---

246```

247 

248#### Restrict which subagents can be spawned

249 

250When an agent runs as the main thread with `claude --agent`, it can spawn subagents using the Task tool. To restrict which subagent types it can spawn, use `Task(agent_type)` syntax in the `tools` field:

251 

252```yaml theme={null}

253---

254name: coordinator

255description: Coordinates work across specialized agents

256tools: Task(worker, researcher), Read, Bash

257---

258```

259 

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

261 

262To allow spawning any subagent without restrictions, use `Task` without parentheses:

263 

264```yaml theme={null}

265tools: Task, Read, Bash

266```

267 

268If `Task` is omitted from the `tools` list entirely, the agent cannot spawn any subagents. This restriction only applies to agents running as the main thread with `claude --agent`. Subagents cannot spawn other subagents, so `Task(agent_type)` has no effect in subagent definitions.

269 

270#### Permission modes

271 

272The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.

273 

274| Mode | Behavior |

275| :------------------ | :------------------------------------------------------------------------------------------------------------------- |

276| `default` | Standard permission checking with prompts |

277| `acceptEdits` | Auto-accept file edits |

278| `dontAsk` | Auto-deny permission prompts (explicitly allowed tools still work) |

279| `delegate` | Coordination-only mode for [agent team](/en/agent-teams#use-delegate-mode) leads. Restricts to team management tools |

280| `bypassPermissions` | Skip all permission checks |

281| `plan` | Plan mode (read-only exploration) |

282 

283<Warning>

284 Use `bypassPermissions` with caution. It skips all permission checks, allowing the subagent to execute any operation without approval.

285</Warning>

286 

287If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden.

288 

289#### Preload skills into subagents

290 

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

292 

293```yaml theme={null}

294---

295name: api-developer

296description: Implement API endpoints following team conventions

297skills:

298 - api-conventions

299 - error-handling-patterns

300---

301 

302Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

303```

304 

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

166 306 

167<Note>307<Note>

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

169</Note>309</Note>

170 310 

171### Available tools311#### Enable persistent memory

172 312 

173Subagents can be granted access to any of Claude Code's internal tools. See the [tools documentation](/en/settings#tools-available-to-claude) for a complete list of available tools.313The `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.

174 314 

175<Tip>315```yaml theme={null}

176 **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.316---

177</Tip>317name: code-reviewer

318description: Reviews code for quality and best practices

319memory: user

320---

178 321 

179You have two options for configuring tools:322You are a code reviewer. As you review code, update your agent memory with

323patterns, conventions, and recurring issues you discover.

324```

180 325 

181* **Omit the `tools` field** to inherit all tools from the main thread (default), including MCP tools326Choose a scope based on how broadly the memory should apply:

182* **Specify individual tools** as a comma-separated list for more granular control (can be edited manually or via `/agents`)

183 327 

184**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.328| Scope | Location | Use when |

329| :-------- | :-------------------------------------------- | :------------------------------------------------------------------------------------------ |

330| `user` | `~/.claude/agent-memory/<name-of-agent>/` | the subagent should remember learnings across all projects |

331| `project` | `.claude/agent-memory/<name-of-agent>/` | the subagent's knowledge is project-specific and shareable via version control |

332| `local` | `.claude/agent-memory-local/<name-of-agent>/` | the subagent's knowledge is project-specific but should not be checked into version control |

185 333 

186## Managing subagents334When memory is enabled:

187 335 

188### Using the /agents command (Recommended)336* The subagent's system prompt includes instructions for reading and writing to the memory directory.

337* The subagent's system prompt also includes the first 200 lines of `MEMORY.md` in the memory directory, with instructions to curate `MEMORY.md` if it exceeds 200 lines.

338* Read, Write, and Edit tools are automatically enabled so the subagent can manage its memory files.

189 339 

190The `/agents` command provides a comprehensive interface for subagent management:340##### Persistent memory tips

191 341 

342* `user` is the recommended default scope. Use `project` or `local` when the subagent's knowledge is only relevant to a specific codebase.

343* Ask the subagent to consult its memory before starting work: "Review this PR, and check your memory for patterns you've seen before."

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

345* Include memory instructions directly in the subagent's markdown file so it proactively maintains its own knowledge base:

346 

347 ```markdown theme={null}

348 Update your agent memory as you discover codepaths, patterns, library

349 locations, and key architectural decisions. This builds up institutional

350 knowledge across conversations. Write concise notes about what you found

351 and where.

352 ```

353 

354#### Conditional rules with hooks

355 

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

357 

358This 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:

359 

360```yaml theme={null}

361---

362name: db-reader

363description: Execute read-only database queries

364tools: Bash

365hooks:

366 PreToolUse:

367 - matcher: "Bash"

368 hooks:

369 - type: command

370 command: "./scripts/validate-readonly-query.sh"

371---

192```372```

193/agents373 

374Claude 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:

375 

376```bash theme={null}

377#!/bin/bash

378# ./scripts/validate-readonly-query.sh

379 

380INPUT=$(cat)

381COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

382 

383# Block SQL write operations (case-insensitive)

384if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then

385 echo "Blocked: Only SELECT queries are allowed" >&2

386 exit 2

387fi

388 

389exit 0

194```390```

195 391 

196This opens an interactive menu where you can:392See [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.

197 393 

198* View all available subagents (built-in, user, and project)394#### Disable specific subagents

199* Create new subagents with guided setup

200* Edit existing custom subagents, including their tool access

201* Delete custom subagents

202* See which subagents are active when duplicates exist

203* **Easily manage tool permissions** with a complete list of available tools

204 395 

205### Direct file management396You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Task(subagent-name)` where `subagent-name` matches the subagent's name field.

397 

398```json theme={null}

399{

400 "permissions": {

401 "deny": ["Task(Explore)", "Task(my-custom-agent)"]

402 }

403}

404```

206 405 

207You can also manage subagents by working directly with their files:406This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:

208 407 

209```bash theme={null}408```bash theme={null}

210# Create a project subagent409claude --disallowedTools "Task(Explore)"

211mkdir -p .claude/agents410```

212echo '---411 

213name: test-runner412See [Permissions documentation](/en/permissions#tool-specific-permission-rules) for more details on permission rules.

214description: Use proactively to run tests and fix failures413 

414### Define hooks for subagents

415 

416Subagents can define [hooks](/en/hooks) that run during the subagent's lifecycle. There are two ways to configure hooks:

417 

4181. **In the subagent's frontmatter**: Define hooks that run only while that subagent is active

4192. **In `settings.json`**: Define hooks that run in the main session when subagents start or stop

420 

421#### Hooks in subagent frontmatter

422 

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

424 

425All [hook events](/en/hooks#hook-events) are supported. The most common events for subagents are:

426 

427| Event | Matcher input | When it fires |

428| :------------ | :------------ | :------------------------------------------------------------------ |

429| `PreToolUse` | Tool name | Before the subagent uses a tool |

430| `PostToolUse` | Tool name | After the subagent uses a tool |

431| `Stop` | (none) | When the subagent finishes (converted to `SubagentStop` at runtime) |

432 

433This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:

434 

435```yaml theme={null}

215---436---

437name: code-reviewer

438description: Review code changes with automatic linting

439hooks:

440 PreToolUse:

441 - matcher: "Bash"

442 hooks:

443 - type: command

444 command: "./scripts/validate-command.sh $TOOL_INPUT"

445 PostToolUse:

446 - matcher: "Edit|Write"

447 hooks:

448 - type: command

449 command: "./scripts/run-linter.sh"

450---

451```

452 

453`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.

454 

455#### Project-level hooks for subagent events

456 

457Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session.

216 458 

217You 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.md459| Event | Matcher input | When it fires |

460| :-------------- | :-------------- | :------------------------------- |

461| `SubagentStart` | Agent type name | When a subagent begins execution |

462| `SubagentStop` | Agent type name | When a subagent completes |

218 463 

219# Create a user subagent464Both 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:

220mkdir -p ~/.claude/agents465 

221# ... create subagent file466```json theme={null}

467{

468 "hooks": {

469 "SubagentStart": [

470 {

471 "matcher": "db-agent",

472 "hooks": [

473 { "type": "command", "command": "./scripts/setup-db-connection.sh" }

474 ]

475 }

476 ],

477 "SubagentStop": [

478 {

479 "hooks": [

480 { "type": "command", "command": "./scripts/cleanup-db-connection.sh" }

481 ]

482 }

483 ]

484 }

485}

222```486```

223 487 

224## Using subagents effectively488See [Hooks](/en/hooks) for the complete hook configuration format.

225 489 

226### Automatic delegation490## Work with subagents

227 491 

228Claude Code proactively delegates tasks based on:492### Understand automatic delegation

229 493 

230* The task description in your request494Claude 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.

231* The `description` field in subagent configurations

232* Current context and available tools

233 495 

234<Tip>496You can also request a specific subagent explicitly:

235 To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your `description` field.497 

236</Tip>498```

499Use the test-runner subagent to fix failing tests

500Have the code-reviewer subagent look at my recent changes

501```

502 

503### Run subagents in foreground or background

504 

505Subagents can run in the foreground (blocking) or background (concurrent):

237 506 

238### Explicit invocation507* **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/settings#tools-available-to-claude)) are passed through to you.

508* **Background subagents** run concurrently while you continue working. Before launching, Claude Code prompts for any tool permissions the subagent will need, ensuring it has the necessary approvals upfront. Once running, the subagent inherits these permissions and auto-denies anything not pre-approved. If a background subagent needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents.

239 509 

240Request a specific subagent by mentioning it in your command:510If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.

511 

512Claude decides whether to run subagents in the foreground or background based on the task. You can also:

513 

514* Ask Claude to "run this in the background"

515* Press **Ctrl+B** to background a running task

516 

517To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables).

518 

519### Common patterns

520 

521#### Isolate high-volume operations

522 

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

241 524 

242```525```

243> Use the test-runner subagent to fix failing tests526Use a subagent to run the test suite and report only the failing tests with their error messages

244> Have the code-reviewer subagent look at my recent changes

245> Ask the debugger subagent to investigate this error

246```527```

247 528 

248## Built-in subagents529#### Run parallel research

249 530 

250Claude Code includes built-in subagents that are available out of the box:531For independent investigations, spawn multiple subagents to work simultaneously:

251 532 

252### Plan subagent533```

534Research the authentication, database, and API modules in parallel using separate subagents

535```

253 536 

254The Plan subagent is a specialized built-in agent designed for use during plan mode. When Claude is operating in plan mode (non-execution mode), it uses the Plan subagent to conduct research and gather information about your codebase before presenting a plan.537Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other.

255 538 

256**Key characteristics:**539<Warning>

540 When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.

541</Warning>

257 542 

258* **Model**: Uses Sonnet for more capable analysis543For tasks that need sustained parallelism or exceed your context window, [agent teams](/en/agent-teams) give each worker its own independent context.

259* **Tools**: Has access to Read, Glob, Grep, and Bash tools for codebase exploration

260* **Purpose**: Searches files, analyzes code structure, and gathers context

261* **Automatic invocation**: Claude automatically uses this agent when in plan mode and needs to research the codebase

262 544 

263**How it works:**545#### Chain subagents

264When you're in plan mode and Claude needs to understand your codebase to create a plan, it delegates research tasks to the Plan subagent. This prevents infinite nesting of agents (subagents cannot spawn other subagents) while still allowing Claude to gather the necessary context.

265 546 

266**Example scenario:**547For 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.

267 548 

268```549```

269User: [In plan mode] Help me refactor the authentication module550Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

551```

552 

553### Choose between subagents and main conversation

554 

555Use the **main conversation** when:

556 

557* The task needs frequent back-and-forth or iterative refinement

558* Multiple phases share significant context (planning → implementation → testing)

559* You're making a quick, targeted change

560* Latency matters. Subagents start fresh and may need time to gather context

561 

562Use **subagents** when:

563 

564* The task produces verbose output you don't need in your main context

565* You want to enforce specific tool restrictions or permissions

566* The work is self-contained and can return a summary

567 

568Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.

569 

570<Note>

571 Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.

572</Note>

573 

574### Manage subagent context

575 

576#### Resume subagents

577 

578Each 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.

579 

580Resumed 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.

581 

582When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:

270 583 

271Claude: Let me research your authentication implementation first...

272[Internally invokes Plan subagent to explore auth-related files]

273[Plan subagent searches codebase and returns findings]

274Claude: Based on my research, here's my proposed plan...

275```584```

585Use the code-reviewer subagent to review the authentication module

586[Agent completes]

276 587 

277<Tip>588Continue that code review and now analyze the authorization logic

278 The Plan subagent is only used in plan mode. In normal execution mode, Claude uses the general-purpose agent or other custom subagents you've created.589[Claude resumes the subagent with full context from previous conversation]

279</Tip>590```

591 

592You 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`.

593 

594Subagent transcripts persist independently of the main conversation:

595 

596* **Main conversation compaction**: When the main conversation compacts, subagent transcripts are unaffected. They're stored in separate files.

597* **Session persistence**: Subagent transcripts persist within their session. You can [resume a subagent](#resume-subagents) after restarting Claude Code by resuming the same session.

598* **Automatic cleanup**: Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).

599 

600#### Auto-compaction

601 

602Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` to a lower percentage (for example, `50`). See [environment variables](/en/settings#environment-variables) for details.

603 

604Compaction events are logged in subagent transcript files:

605 

606```json theme={null}

607{

608 "type": "system",

609 "subtype": "compact_boundary",

610 "compactMetadata": {

611 "trigger": "auto",

612 "preTokens": 167189

613 }

614}

615```

616 

617The `preTokens` value shows how many tokens were used before compaction occurred.

280 618 

281## Example subagents619## Example subagents

282 620 

621These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.

622 

623<Tip>

624 **Best practices:**

625 

626 * **Design focused subagents:** each subagent should excel at one specific task

627 * **Write detailed descriptions:** Claude uses the description to decide when to delegate

628 * **Limit tool access:** grant only necessary permissions for security and focus

629 * **Check into version control:** share project subagents with your team

630</Tip>

631 

283### Code reviewer632### Code reviewer

284 633 

634A 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.

635 

285```markdown theme={null}636```markdown theme={null}

286---637---

287name: code-reviewer638name: code-reviewer


2983. Begin review immediately6493. Begin review immediately

299 650 

300Review checklist:651Review checklist:

301- Code is simple and readable652- Code is clear and readable

302- Functions and variables are well-named653- Functions and variables are well-named

303- No duplicated code654- No duplicated code

304- Proper error handling655- Proper error handling


317 668 

318### Debugger669### Debugger

319 670 

671A 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.

672 

320```markdown theme={null}673```markdown theme={null}

321---674---

322name: debugger675name: debugger


347- Testing approach700- Testing approach

348- Prevention recommendations701- Prevention recommendations

349 702 

350Focus on fixing the underlying issue, not just symptoms.703Focus on fixing the underlying issue, not the symptoms.

351```704```

352 705 

353### Data scientist706### Data scientist

354 707 

708A 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.

709 

355```markdown theme={null}710```markdown theme={null}

356---711---

357name: data-scientist712name: data-scientist


385Always ensure queries are efficient and cost-effective.740Always ensure queries are efficient and cost-effective.

386```741```

387 742 

388## Best practices743### Database query validator

389 

390* **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.

391 

392* **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.

393 

394* **Write detailed prompts**: Include specific instructions, examples, and constraints in your system prompts. The more guidance you provide, the better the subagent will perform.

395 744 

396* **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.745A 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.

397 746 

398* **Version control**: Check project subagents into version control so your team can benefit from and improve them collaboratively.747```markdown theme={null}

399 748---

400## Advanced usage749name: db-reader

750description: Execute read-only database queries. Use when analyzing data or generating reports.

751tools: Bash

752hooks:

753 PreToolUse:

754 - matcher: "Bash"

755 hooks:

756 - type: command

757 command: "./scripts/validate-readonly-query.sh"

758---

401 759 

402### Chaining subagents760You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.

403 761 

404For complex workflows, you can chain multiple subagents:762When asked to analyze data:

7631. Identify which tables contain the relevant data

7642. Write efficient SELECT queries with appropriate filters

7653. Present results clearly with context

405 766 

767You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.

406```768```

407> First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them

408```

409 

410### Dynamic subagent selection

411 

412Claude Code intelligently selects subagents based on context. Make your `description` fields specific and action-oriented for best results.

413 769 

414### Resumable subagents770Claude 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.

415 771 

416Subagents can be resumed to continue previous conversations, which is particularly useful for long-running research or analysis tasks that need to be continued across multiple invocations.772Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:

417 773 

418**How it works:**774```bash theme={null}

419 775#!/bin/bash

420* Each subagent execution is assigned a unique `agentId`776# Blocks SQL write operations, allows SELECT queries

421* The agent's conversation is stored in a separate transcript file: `agent-{agentId}.jsonl`

422* You can resume a previous agent by providing its `agentId` via the `resume` parameter

423* When resumed, the agent continues with full context from its previous conversation

424 

425**Example workflow:**

426 777 

427Initial invocation:778# Read JSON input from stdin

779INPUT=$(cat)

428 780 

429```781# Extract the command field from tool_input using jq

430> Use the code-analyzer agent to start reviewing the authentication module782COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

431 783 

432[Agent completes initial analysis and returns agentId: "abc123"]784if [ -z "$COMMAND" ]; then

433```785 exit 0

786fi

434 787 

435Resume the agent:788# Block write operations (case-insensitive)

789if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then

790 echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2

791 exit 2

792fi

436 793 

794exit 0

437```795```

438> Resume agent abc123 and now analyze the authorization logic as well

439 796 

440[Agent continues with full context from previous conversation]797Make the script executable:

441```

442 798 

443**Use cases:**799```bash theme={null}

444 800chmod +x ./scripts/validate-readonly-query.sh

445* **Long-running research**: Break down large codebase analysis into multiple sessions

446* **Iterative refinement**: Continue refining a subagent's work without losing context

447* **Multi-step workflows**: Have a subagent work on related tasks sequentially while maintaining context

448 

449**Technical details:**

450 

451* Agent transcripts are stored in your project directory

452* Recording is disabled during resume to avoid duplicating messages

453* Both synchronous and asynchronous agents can be resumed

454* The `resume` parameter accepts the agent ID from a previous execution

455 

456**Programmatic usage:**

457 

458If you're using the Agent SDK or interacting with the AgentTool directly, you can pass the `resume` parameter:

459 

460```typescript theme={null}

461{

462 "description": "Continue analysis",

463 "prompt": "Now examine the error handling patterns",

464 "subagent_type": "code-analyzer",

465 "resume": "abc123" // Agent ID from previous execution

466}

467```801```

468 802 

469<Tip>803The 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.

470 Keep track of agent IDs for tasks you may want to resume later. Claude Code displays the agent ID when a subagent completes its work.

471</Tip>

472 

473## Performance considerations

474 804 

475* **Context efficiency**: Agents help preserve main context, enabling longer overall sessions805## Next steps

476* **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.

477 806 

478## Related documentation807Now that you understand subagents, explore these related features:

479 808 

480* [Plugins](/en/plugins) - Extend Claude Code with custom agents through plugins809* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects

481* [Slash commands](/en/slash-commands) - Learn about other built-in commands810* [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation

482* [Settings](/en/settings) - Configure Claude Code behavior811* [Use MCP servers](/en/mcp) to give subagents access to external tools and data

483* [Hooks](/en/hooks) - Automate workflows with event handlers

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.


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* **Shift+Enter**: Works out of the box in iTerm2, WezTerm, Ghostty, and Kitty

21* **Keyboard shortcut**: Set up a keybinding to insert a newline in other terminals

22 

23**Set up Shift+Enter for other terminals**

17 24 

18#### Set up Shift+Enter (VS Code or iTerm2):25Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter for VS Code, Alacritty, Zed, and Warp.

19 26 

20Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter.27<Note>

28 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.

29</Note>

21 30 

22#### Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app):31**Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app)**

23 32 

24**For Mac Terminal.app:**33**For Mac Terminal.app:**

25 34 


65The supported subset includes:74The supported subset includes:

66 75 

67* Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT)76* 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`77* 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)78* Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat)

79* Yank/paste: `yy`/`Y`, `yw`/`ye`/`yb`, `p`/`P`

80* Text objects: `iw`/`aw`, `iW`/`aW`, `i"`/`a"`, `i'`/`a'`, `i(`/`a(`, `i[`/`a[`, `i{`/`a{`

81* Indentation: `>>`/`<<`

82* Line operations: `J` (join lines)

83 

84See [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.

6 16 

7## Provider comparison17**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.

18 

19Learn 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>Azure AI Foundry</th>

16 <th>Google Vertex AI</th>30 <th>Google Vertex AI</th>

31 <th>Microsoft Foundry</th>

17 </tr>32 </tr>

18 </thead>33 </thead>

19 34 

20 <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">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 

21 <tr>54 <tr>

22 <td>Regions</td>55 <td>Regions</td>

23 <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>

24 <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>

25 <td>Multiple Azure [regions](https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/)</td>

26 <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>

27 </tr>61 </tr>

28 62 

29 <tr>63 <tr>


32 <td>Enabled by default</td>66 <td>Enabled by default</td>

33 <td>Enabled by default</td>67 <td>Enabled by default</td>

34 <td>Enabled by default</td>68 <td>Enabled by default</td>

69 <td>Enabled by default</td>

35 </tr>70 </tr>

36 71 

37 <tr>72 <tr>

38 <td>Authentication</td>73 <td>Authentication</td>

74 <td>Claude.ai SSO or email</td>

39 <td>API key</td>75 <td>API key</td>

40 <td>API key or AWS credentials</td>76 <td>API key or AWS credentials</td>

41 <td>API key or Microsoft Entra ID</td>

42 <td>GCP credentials</td>77 <td>GCP credentials</td>

78 <td>API key or Microsoft Entra ID</td>

43 </tr>79 </tr>

44 80 

45 <tr>81 <tr>

46 <td>Cost tracking</td>82 <td>Cost tracking</td>

47 <td>Dashboard</td>83 <td>Usage dashboard</td>

84 <td>Usage dashboard</td>

48 <td>AWS Cost Explorer</td>85 <td>AWS Cost Explorer</td>

49 <td>Azure Cost Management</td>

50 <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>

51 </tr>97 </tr>

52 98 

53 <tr>99 <tr>

54 <td>Enterprise features</td>100 <td>Enterprise features</td>

55 <td>Teams, usage monitoring</td>101 <td>Team management, SSO, usage monitoring</td>

102 <td>None</td>

56 <td>IAM policies, CloudTrail</td>103 <td>IAM policies, CloudTrail</td>

57 <td>RBAC policies, Azure Monitor</td>

58 <td>IAM roles, Cloud Audit Logs</td>104 <td>IAM roles, Cloud Audit Logs</td>

105 <td>RBAC policies, Azure Monitor</td>

59 </tr>106 </tr>

60 </tbody>107 </tbody>

61</table>108</table>

62 109 

63## Cloud providers110Select a deployment option to view setup instructions:

64 111 

65<CardGroup cols={3}>112* [Claude for Teams or Enterprise](/en/authentication#claude-for-teams-or-enterprise)

66 <Card title="Amazon Bedrock" icon="aws" href="/en/amazon-bedrock">113* [Anthropic Console](/en/authentication#claude-console-authentication)

67 Use Claude models through AWS infrastructure with API key or IAM-based authentication and AWS-native monitoring114* [Amazon Bedrock](/en/amazon-bedrock)

68 </Card>115* [Google Vertex AI](/en/google-vertex-ai)

116* [Microsoft Foundry](/en/microsoft-foundry)

69 117 

70 <Card title="Azure AI Foundry" icon="microsoft" href="/en/azure-ai-foundry">118## Configure proxies and gateways

71 Access Claude through Azure with API key or Microsoft Entra ID authentication and Azure billing

72 </Card>

73 119 

74 <Card title="Google Vertex AI" icon="google" href="/en/google-vertex-ai">120Most 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:

75 Access Claude models via Google Cloud Platform with enterprise-grade security and compliance

76 </Card>

77</CardGroup>

78 121 

79## Corporate infrastructure122* **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).

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).

80 124 

81<CardGroup cols={2}>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.

82 <Card title="Enterprise Network" icon="shield" href="/en/network-config">

83 Configure Claude Code to work with your organization's proxy servers and SSL/TLS requirements

84 </Card>

85 126 

86 <Card title="LLM Gateway" icon="server" href="/en/llm-gateway">127### Amazon Bedrock

87 Deploy centralized model access with usage tracking, budgeting, and audit logging

88 </Card>

89</CardGroup>

90 128 

91## Configuration overview129<Tabs>

130 <Tab title="Corporate proxy">

131 Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables):

92 132 

93Claude Code supports flexible configuration options that allow you to combine different providers and infrastructure:133 ```bash theme={null}

134 # Enable Bedrock

135 export CLAUDE_CODE_USE_BEDROCK=1

136 export AWS_REGION=us-east-1

94 137 

95<Note>138 # Configure corporate proxy

96 Understand the difference between:139 export HTTPS_PROXY='https://proxy.example.com:8080'

140 ```

141 </Tab>

97 142 

98 * **Corporate proxy**: An HTTP/HTTPS proxy for routing traffic (set via `HTTPS_PROXY` or `HTTP_PROXY`)143 <Tab title="LLM Gateway">

99 * **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`)144 Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables):

100 145 

101 Both configurations can be used in tandem.146 ```bash theme={null}

102</Note>147 # Enable Bedrock

148 export CLAUDE_CODE_USE_BEDROCK=1

103 149 

104### Using Bedrock with corporate proxy150 # 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>

105 156 

106Route Bedrock traffic through a corporate HTTP/HTTPS proxy:157### Microsoft Foundry

107 158 

108```bash theme={null}159<Tabs>

109# Enable Bedrock160 <Tab title="Corporate proxy">

110export CLAUDE_CODE_USE_BEDROCK=1161 Route Foundry traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables):

111export AWS_REGION=us-east-1

112 162 

113# Configure corporate proxy163 ```bash theme={null}

114export HTTPS_PROXY='https://proxy.example.com:8080'164 # Enable Microsoft Foundry

115```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

116 168 

117### Using Bedrock with LLM Gateway169 # Configure corporate proxy

170 export HTTPS_PROXY='https://proxy.example.com:8080'

171 ```

172 </Tab>

118 173 

119Use a gateway service that provides Bedrock-compatible endpoints:174 <Tab title="LLM Gateway">

175 Route Foundry traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables):

120 176 

121```bash theme={null}177 ```bash theme={null}

122# Enable Bedrock178 # Enable Microsoft Foundry

123export CLAUDE_CODE_USE_BEDROCK=1179 export CLAUDE_CODE_USE_FOUNDRY=1

124 180 

125# Configure LLM gateway181 # Configure LLM gateway

126export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'182 export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com'

127export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth183 export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 # If gateway handles Azure auth

128```184 ```

185 </Tab>

186</Tabs>

129 187 

130### Using Azure AI Foundry with corporate proxy188### Google Vertex AI

131 189 

132Route Azure traffic through a corporate HTTP/HTTPS proxy:190<Tabs>

191 <Tab title="Corporate proxy">

192 Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/en/settings#environment-variables):

133 193 

134```bash theme={null}194 ```bash theme={null}

135# Enable Azure AI Foundry195 # Enable Vertex

136export CLAUDE_CODE_USE_FOUNDRY=1196 export CLAUDE_CODE_USE_VERTEX=1

137export ANTHROPIC_FOUNDRY_RESOURCE=your-resource197 export CLOUD_ML_REGION=us-east5

138export ANTHROPIC_FOUNDRY_API_KEY=your-api-key # Or omit for Entra ID auth198 export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

139 199 

140# Configure corporate proxy200 # Configure corporate proxy

141export HTTPS_PROXY='https://proxy.example.com:8080'201 export HTTPS_PROXY='https://proxy.example.com:8080'

142```202 ```

203 </Tab>

143 204 

144### Using Azure AI Foundry with LLM Gateway205 <Tab title="LLM Gateway">

206 Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/en/settings#environment-variables):

145 207 

146Use a gateway service that provides Azure-compatible endpoints:208 ```bash theme={null}

209 # Enable Vertex

210 export CLAUDE_CODE_USE_VERTEX=1

147 211 

148```bash theme={null}212 # Configure LLM gateway

149# Enable Azure AI Foundry213 export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'

150export CLAUDE_CODE_USE_FOUNDRY=1214 export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth

215 ```

216 </Tab>

217</Tabs>

151 218 

152# Configure LLM gateway219<Tip>

153export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com'220 Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly.

154export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 # If gateway handles Azure auth221</Tip>

155```

156 

157### Using Vertex AI with corporate proxy

158 

159Route Vertex AI traffic through a corporate HTTP/HTTPS proxy:

160 

161```bash theme={null}

162# Enable Vertex

163export CLAUDE_CODE_USE_VERTEX=1

164export CLOUD_ML_REGION=us-east5

165export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id

166 

167# Configure corporate proxy

168export HTTPS_PROXY='https://proxy.example.com:8080'

169```

170 

171### Using Vertex AI with LLM Gateway

172 

173Combine Google Vertex AI models with an LLM gateway for centralized management:

174 

175```bash theme={null}

176# Enable Vertex

177export CLAUDE_CODE_USE_VERTEX=1

178 

179# Configure LLM gateway

180export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'

181export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth

182```

183 

184### Authentication configuration

185 

186Claude 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.

187 

188## Choosing the right deployment configuration

189 

190Consider these factors when selecting your deployment approach:

191 

192### Direct provider access

193 

194Best for organizations that:

195 

196* Want the simplest setup

197* Have existing AWS or GCP infrastructure

198* Need provider-native monitoring and compliance

199 

200### Corporate proxy

201 

202Best for organizations that:

203 

204* Have existing corporate proxy requirements

205* Need traffic monitoring and compliance

206* Must route all traffic through specific network paths

207 

208### LLM Gateway

209 

210Best for organizations that:

211 

212* Need usage tracking across teams

213* Want to dynamically switch between models

214* Require custom rate limiting or budgets

215* Need centralized authentication management

216 

217## Debugging

218 

219When debugging your deployment:

220 

221* Use the `claude /status` [slash command](/en/slash-commands). This command provides observability into any applied authentication, proxy, and URL settings.

222* Set environment variable `export ANTHROPIC_LOG=debug` to log requests.

223 222 

224## Best practices for organizations223## Best practices for organizations

225 224 

226### 1. Invest in documentation and memory225### Invest in documentation and memory

227 226 

228We 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:

229 228 

230* **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

231* **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

232 231 

233 [Learn more](/en/memory).232Learn more in [Memory and CLAUDE.md files](/en/memory).

234 233 

235### 2. Simplify deployment234### Simplify deployment

236 235 

237If 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.

238 237 

239### 3. Start with guided usage238### Start with guided usage

240 239 

241Encourage 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.

242 241 

243### 4. Configure security policies242### Configure security policies

244 243 

245Security 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).244Security 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).

246 245 

247### 5. Leverage MCP for integrations246### Leverage MCP for integrations

248 247 

249MCP 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).248MCP 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).

250 249 

251At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do!250At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do.

252 251 

253## Next steps252## Next steps

254 253 

255* [Set up Amazon Bedrock](/en/amazon-bedrock) for AWS-native deployment254Once you've chosen a deployment option and configured access for your team:

256* [Set up Azure AI Foundry](/en/azure-ai-foundry) for Azure deployment255 

257* [Configure Google Vertex AI](/en/google-vertex-ai) for GCP deployment2561. **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/en/setup) and authenticate with their credentials.

258* [Configure Enterprise Network](/en/network-config) for network requirements2572. **Set up shared configuration**: Create a [CLAUDE.md file](/en/memory) in your repositories to help Claude Code understand your codebase and coding standards.

259* [Deploy LLM Gateway](/en/llm-gateway) for enterprise management2583. **Configure permissions**: Review [security settings](/en/security) to define what Claude Code can and cannot do in your environment.

260* [Settings](/en/settings) for configuration options and environment variables

troubleshooting.md +121 −33

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

1# 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.


50```54```

51 55 

52<Warning>56<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.57 Avoid disabling Windows PATH importing (`appendWindowsPath = false`) as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.

54</Warning>58</Warning>

55 59 

60### WSL2 sandbox setup

61 

62[Sandboxing](/en/sandboxing) is supported on WSL2 but requires installing additional packages. If you see an error like "Sandbox requires socat and bubblewrap" when running `/sandbox`, install the dependencies:

63 

64<Tabs>

65 <Tab title="Ubuntu/Debian">

66 ```bash theme={null}

67 sudo apt-get install bubblewrap socat

68 ```

69 </Tab>

70 

71 <Tab title="Fedora">

72 ```bash theme={null}

73 sudo dnf install bubblewrap socat

74 ```

75 </Tab>

76</Tabs>

77 

78WSL1 does not support sandboxing. If you see "Sandboxing requires WSL2", you need to upgrade to WSL2 or run Claude Code without sandboxing.

79 

56### Linux and Mac installation issues: permission or command not found errors80### Linux and Mac installation issues: permission or command not found errors

57 81 

58When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.82When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.

59You may also encounter permission errors if your npm global prefix is not user writable (eg. `/usr`, or `/usr/local`).83You may also encounter permission errors if your npm global prefix is not user writable (for example, `/usr`, or `/usr/local`).

60 84 

61#### Recommended solution: Native Claude Code installation85#### Recommended solution: Native Claude Code installation

62 86 

63Claude Code has a native installation that doesn't depend on npm or Node.js.87Claude Code has a native installation that doesn't depend on npm or Node.js.

64 88 

65<Note>

66 The native Claude Code installer is currently in beta.

67</Note>

68 

69Use the following command to run the native installer.89Use the following command to run the native installer.

70 90 

71**macOS, Linux, WSL:**91**macOS, Linux, WSL:**


95 115 

96```116```

97 117 

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`.118This command installs the appropriate build of Claude Code for your operating system and architecture and adds a symlink to the installation at `~/.local/bin/claude` (or `%USERPROFILE%\.local\bin\claude.exe` on Windows).

99 119 

100<Tip>120<Tip>

101 Make sure that you have the installation directory in your system PATH.121 Make sure that you have the installation directory in your system PATH.

102</Tip>122</Tip>

103 123 

104#### Alternative solution: Migrate to local installation124### Windows: "Claude Code on Windows requires git-bash"

105 125 

106Alternatively, if Claude Code will run, you can migrate to a local installation:126Claude Code on native Windows requires [Git for Windows](https://git-scm.com/downloads/win) which includes Git Bash. If Git is installed but not detected:

107 127 

108```bash theme={null}1281. Set the path explicitly in PowerShell before running Claude:

109claude migrate-installer129 ```powershell theme={null}

110```130 $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"

131 ```

111 132 

112This moves Claude Code to `~/.claude/local/` and sets up an alias in your shell configuration. No `sudo` is required for future updates.1332. Or add it to your system environment variables permanently through System Properties Environment Variables.

113 134 

114After migration, restart your shell, and then verify your installation:135If Git is installed in a non-standard location, adjust the path accordingly.

115 136 

116On macOS/Linux/WSL:137### Windows: "installMethod is native, but claude command not found"

117 138 

118```bash theme={null}139If you see this error after installation, the `claude` command isn't in your PATH. Add it manually:

119which claude # Should show an alias to ~/.claude/local/claude

120```

121 140 

122On Windows:141<Steps>

142 <Step title="Open Environment Variables">

143 Press `Win + R`, type `sysdm.cpl`, and press Enter. Click **Advanced** → **Environment Variables**.

144 </Step>

123 145 

124```powershell theme={null}146 <Step title="Edit User PATH">

125where claude # Should show path to claude executable147 Under "User variables", select **Path** and click **Edit**. Click **New** and add:

126```148 

149 ```

150 %USERPROFILE%\.local\bin

151 ```

152 </Step>

153 

154 <Step title="Restart your terminal">

155 Close and reopen PowerShell or CMD for changes to take effect.

156 </Step>

157</Steps>

127 158 

128Verify installation:159Verify installation:

129 160 


136### Repeated permission prompts167### Repeated permission prompts

137 168 

138If you find yourself repeatedly approving the same commands, you can allow specific tools169If you find yourself repeatedly approving the same commands, you can allow specific tools

139to run without approval using the `/permissions` command. See [Permissions docs](/en/iam#configuring-permissions).170to run without approval using the `/permissions` command. See [Permissions docs](/en/permissions#manage-permissions).

140 171 

141### Authentication issues172### Authentication issues

142 173 


1462. Close Claude Code1772. Close Claude Code

1473. Restart with `claude` and complete the authentication process again1783. Restart with `claude` and complete the authentication process again

148 179 

180If 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.

181 

149If problems persist, try:182If problems persist, try:

150 183 

151```bash theme={null}184```bash theme={null}


155 188 

156This removes your stored authentication information and forces a clean login.189This removes your stored authentication information and forces a clean login.

157 190 

191## Configuration file locations

192 

193Claude Code stores configuration in several locations:

194 

195| File | Purpose |

196| :---------------------------- | :------------------------------------------------------- |

197| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |

198| `.claude/settings.json` | Project settings (checked into source control) |

199| `.claude/settings.local.json` | Local project settings (not committed) |

200| `~/.claude.json` | Global state (theme, OAuth, MCP servers) |

201| `.mcp.json` | Project MCP servers (checked into source control) |

202| `managed-settings.json` | [Managed settings](/en/settings#settings-files) |

203| `managed-mcp.json` | [Managed MCP servers](/en/mcp#managed-mcp-configuration) |

204 

205On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`.

206 

207**Managed file locations:**

208 

209* macOS: `/Library/Application Support/ClaudeCode/`

210* Linux/WSL: `/etc/claude-code/`

211* Windows: `C:\Program Files\ClaudeCode\`

212 

213For details on configuring these files, see [Settings](/en/settings) and [MCP](/en/mcp).

214 

215### Resetting configuration

216 

217To reset Claude Code to default settings, you can remove the configuration files:

218 

219```bash theme={null}

220# Reset all user settings and state

221rm ~/.claude.json

222rm -rf ~/.claude/

223 

224# Reset project-specific settings

225rm -rf .claude/

226rm .mcp.json

227```

228 

229<Warning>

230 This will remove all your settings, MCP server configurations, and session history.

231</Warning>

232 

158## Performance and stability233## Performance and stability

159 234 

160### High CPU or memory usage235### High CPU or memory usage


174 249 

175### Search and discovery issues250### Search and discovery issues

176 251 

177If Search tool, `@file` mentions, custom agents, and custom slash commands aren't working, install system `ripgrep`:252If Search tool, `@file` mentions, custom agents, and custom skills aren't working, install system `ripgrep`:

178 253 

179```bash theme={null}254```bash theme={null}

180# macOS (Homebrew) 255# macOS (Homebrew)


252 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.327 These networking issues only affect WSL2. WSL1 uses the host's network directly and doesn't require these configurations.

253</Note>328</Note>

254 329 

255For additional JetBrains configuration tips, see our [IDE integration guide](/en/vs-code#jetbrains-plugin-settings).330For additional JetBrains configuration tips, see our [JetBrains IDE guide](/en/jetbrains#plugin-settings).

256 331 

257### Reporting Windows IDE integration issues (both native and WSL)332### Reporting Windows IDE integration issues (both native and WSL)

258 333 

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)334If you're experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information:

335 

336* Environment type: native Windows (Git Bash) or WSL1/WSL2

337* WSL networking mode (if applicable): NAT or mirrored

338* IDE name and version

339* Claude Code extension/plugin version

340* Shell type: Bash, Zsh, PowerShell, etc.

260 341 

261### ESC key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals342### Escape key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals

262 343 

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.344If 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 345 

265To fix this issue:346To fix this issue:

266 347 


270 * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut351 * Click "Configure terminal keybindings" and delete the "Switch focus to Editor" shortcut

2713. Apply the changes3523. Apply the changes

272 353 

273This allows the ESC key to properly interrupt Claude Code operations.354This allows the `Esc` key to properly interrupt Claude Code operations.

274 355 

275## Markdown formatting issues356## Markdown formatting issues

276 357 


300 381 

301**Solutions:**382**Solutions:**

302 383 

3031. **Ask Claude to add language tags**: Simply request "Please add appropriate language tags to all code blocks in this markdown file."3841. **Ask Claude to add language tags**: Request "Add appropriate language tags to all code blocks in this markdown file."

304 385 

3052. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See the [markdown formatting hook example](/en/hooks-guide#markdown-formatting-hook) for implementation details.3862. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See [Auto-format code after edits](/en/hooks-guide#auto-format-code-after-edits) for an example of a PostToolUse formatting hook.

306 387 

3073. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.3883. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.

308 389 


323To minimize formatting issues:404To minimize formatting issues:

324 405 

325* **Be explicit in requests**: Ask for "properly formatted markdown with language-tagged code blocks"406* **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/memory)407* **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 issues408* **Set up validation hooks**: Use post-processing hooks to automatically verify and fix common formatting issues

328 409 

329## Getting more help410## Getting more help


332 413 

3331. Use the `/bug` command within Claude Code to report problems directly to Anthropic4141. Use the `/bug` command within Claude Code to report problems directly to Anthropic

3342. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues4152. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues

3353. Run `/doctor` to check the health of your Claude Code installation4163. Run `/doctor` to diagnose issues. It checks:

417 * Installation type, version, and search functionality

418 * Auto-update status and available versions

419 * Invalid settings files (malformed JSON, incorrect types)

420 * MCP server configuration errors

421 * Keybinding configuration problems

422 * Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)

423 * Plugin and agent loading errors

3364. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation4244. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation

vs-code.md +384 −91

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/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=300652d5678c63905e6b0ea9e50835f8" 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/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=280&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=87630c671517a3d52e9aee627041696e 280w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=560&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=716b093879204beec8d952649ef75292 560w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=840&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=c1525d1a01513acd9d83d8b5a8fe2fc8 840w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=1100&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=1d90021d58bbb51f871efec13af955c3 1100w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=1650&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=7babdd25440099886f193cfa99af88ae 1650w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=2500&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=08c92eedfb56fe61a61e480fb63784b6 2500w" />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" data-og-width="2500" width="2500" data-og-height="1155" height="1155" data-path="images/vs-code-extension-interface.jpg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=280&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=87630c671517a3d52e9aee627041696e 280w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=560&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=716b093879204beec8d952649ef75292 560w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=840&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=c1525d1a01513acd9d83d8b5a8fe2fc8 840w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=1100&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=1d90021d58bbb51f871efec13af955c3 1100w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=1650&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=7babdd25440099886f193cfa99af88ae 1650w, https://mintcdn.com/claude-code/-YhHHmtSxwr7W8gy/images/vs-code-extension-interface.jpg?w=2500&fit=max&auto=format&n=-YhHHmtSxwr7W8gy&q=85&s=08c92eedfb56fe61a61e480fb63784b6 2500w" />

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 icon17* VS Code 1.98.0 or higher

16* **Plan mode with editing**: Review and edit Claude's plans before accepting them18* 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.

17* **Auto-accept edits mode**: Automatically apply Claude's changes as they're made

18* **Extended thinking**: Toggle extended thinking on/off using the Extended Thinking button in the bottom-right corner of the prompt input

19* **File management**: @-mention files or attach files and images using the system file picker

20* **MCP server usage**: Use Model Context Protocol servers configured through the CLI

21* **Conversation history**: Easy access to past conversations

22* **Multiple sessions**: Run multiple Claude Code sessions simultaneously

23* **Keyboard shortcuts**: Support for most shortcuts from the CLI

24* **Slash commands**: Access most CLI slash commands directly in the extension

25 19 

26### Requirements20<Tip>

21 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.

22</Tip>

27 23 

28* VS Code 1.98.0 or higher24## Install the extension

25 

26Click the link for your IDE to install directly:

27 

28* [Install for VS Code](vscode:extension/anthropic.claude-code)

29* [Install for Cursor](cursor:extension/anthropic.claude-code)

29 30 

30### Installation31Or 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**.

31 32 

32Download and install the extension from the [Visual Studio Code Extension Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code).33<Note>If the extension doesn't appear after installation, restart VS Code or run "Developer: Reload Window" from the Command Palette.</Note>

33 34 

34### How It Works35## Get started

35 36 

36Once installed, you can start using Claude Code through the VS Code interface:37Once installed, you can start using Claude Code through the VS Code interface:

37 38 

381. Click the Spark icon in your editor's sidebar to open the Claude Code panel39<Steps>

392. Prompt Claude Code in the same way you would in the terminal40 <Step title="Open the Claude Code panel">

403. Watch as Claude analyzes your code and suggests changes41 Throughout VS Code, the Spark icon indicates Claude Code: <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=a734d84e785140016672f08e0abb236c" alt="Spark icon" style={{display: "inline", height: "0.85em", verticalAlign: "middle"}} data-og-width="16" width="16" data-og-height="16" height="16" data-path="images/vs-code-spark-icon.svg" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=280&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=9a45aad9a84b9fa1701ac99a1f9aa4e9 280w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=560&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=3f4cb9254c4d4e93989c4b6bf9292f4b 560w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=840&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=e75ccc9faa3e572db8f291ceb65bb264 840w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=1100&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=f147bd81a381a62539a4ce361fac41c7 1100w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=1650&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=78fe68efaee5d6e844bbacab1b442ed5 1650w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-spark-icon.svg?w=2500&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=efb8dbe1dfa722d094edc6ad2ad4bedb 2500w" />

414. Review and accept edits directly in the interface42 

42 * **Tip**: Drag the sidebar wider to see inline diffs, then click on them to expand for full details43 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.

44 

45 <img src="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=eb4540325d94664c51776dbbfec4cf02" alt="VS Code editor showing the Spark icon in the Editor Toolbar" data-og-width="2796" width="2796" data-og-height="734" height="734" data-path="images/vs-code-editor-icon.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=280&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=56f218d5464359d6480cfe23f70a923e 280w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=560&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=344a8db024b196c795a80dc85cacb8d1 560w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=840&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=f30bf834ee0625b2a4a635d552d87163 840w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=1100&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=81fdf984840e43a9f08ae42729d1484d 1100w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=1650&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=8b60fb32de54717093d512afaa99785c 1650w, https://mintcdn.com/claude-code/mfM-EyoZGnQv8JTc/images/vs-code-editor-icon.png?w=2500&fit=max&auto=format&n=mfM-EyoZGnQv8JTc&q=85&s=893e6bda8f2e9d42c8a294d394f0b736 2500w" />

46 

47 Other ways to open Claude Code:

48 

49 * **Command Palette**: `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux), type "Claude Code", and select an option like "Open in New Tab"

50 * **Status Bar**: Click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open.

51 

52 When you first open the panel, a **Learn Claude Code** checklist appears. Work through each item by clicking **Show me**, or dismiss it with the X. To reopen it later, uncheck **Hide Onboarding** in VS Code settings under Extensions → Claude Code.

53 

54 You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.

55 </Step>

56 

57 <Step title="Send a prompt">

58 Ask Claude to help with your code or files, whether that's explaining how something works, debugging an issue, or making changes.

59 

60 <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>

61 

62 Here's an example of asking about a particular line in a file:

63 

64 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ede3ed8d8d5f940e01c5de636d009cfd" alt="VS Code editor with lines 2-3 selected in a Python file, and the Claude Code panel showing a question about those lines with an @-mention reference" data-og-width="3288" width="3288" data-og-height="1876" height="1876" data-path="images/vs-code-send-prompt.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=280&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=f40bde7b2c245fe8f0f5b784e8106492 280w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=560&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=fad66a27a9a6faa23b05370aa4f398b2 560w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=840&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=4539c8a3823ca80a5c8771f6c088ce9e 840w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=1100&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=fae8ebf300c7853409a562ffa46d9c71 1100w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=1650&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=22e4462bb8cf0c0ca20f8102bc4c971a 1650w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-send-prompt.png?w=2500&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=739bfd045f70fe7be1a109a53494590e 2500w" />

65 </Step>

66 

67 <Step title="Review changes">

68 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.

69 

70 <img src="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=e005f9b41c541c5c7c59c082f7c4841c" alt="VS Code showing a diff of Claude's proposed changes with a permission prompt asking whether to make the edit" data-og-width="3292" width="3292" data-og-height="1876" height="1876" data-path="images/vs-code-edits.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=280&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=cb5d41b81087f79b842a56b5a3304660 280w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=560&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=90bb691960decdc06393c3c21cd62c75 560w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=840&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=9a11bf878ba619e850380904ff4f38e8 840w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=1100&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=6dddbf596b4f69ec6245bdc5eb6dd487 1100w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=1650&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=ef2713b8cbfd2cee97af817d813d64c7 1650w, https://mintcdn.com/claude-code/FVYz38sRY-VuoGHA/images/vs-code-edits.png?w=2500&fit=max&auto=format&n=FVYz38sRY-VuoGHA&q=85&s=1f7e1c52919cdfddf295f32a2ec7ae59 2500w" />

71 </Step>

72</Steps>

73 

74For more ideas on what you can do with Claude Code, see [Common workflows](/en/common-workflows).

75 

76<Tip>

77 Run "Claude Code: Open Walkthrough" from the Command Palette for a guided tour of the basics.

78</Tip>

79 

80## Use the prompt box

81 

82The prompt box supports several features:

83 

84* **Permission modes**: Click the mode indicator at the bottom of the prompt box to switch modes. In normal mode, Claude asks permission before each action. In Plan mode, Claude describes what it will do and waits for approval before making changes. In auto-accept mode, Claude makes edits without asking. Set the default in VS Code settings under `claudeCode.initialPermissionMode`.

85* **Command menu**: Click `/` or type `/` to open the command menu. Options include attaching files, switching models, toggling extended thinking, and viewing plan usage (`/usage`). The Customize section provides access to MCP servers, hooks, memory, permissions, and plugins. Items with a terminal icon open in the integrated terminal.

86* **Context indicator**: The prompt box shows how much of Claude's context window you're using. Claude automatically compacts when needed, or you can run `/compact` manually.

87* **Extended thinking**: Lets Claude spend more time reasoning through complex problems. Toggle it on via the command menu (`/`). See [Extended thinking](/en/common-workflows#use-extended-thinking-thinking-mode) for details.

88* **Multi-line input**: Press `Shift+Enter` to add a new line without sending. This also works in the "Other" free-text input of question dialogs.

89 

90### Reference files and folders

91 

92Use @-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:

93 

94```

95> Explain the logic in @auth (fuzzy matches auth.js, AuthService.ts, etc.)

96> What's in @src/components/ (include a trailing slash for folders)

97```

98 

99For large PDFs, you can ask Claude to read specific pages instead of the whole file: a single page, a range like pages 1-10, or an open-ended range like page 3 onward.

100 

101When you select text in the editor, Claude can see your highlighted code automatically. The prompt box footer shows how many lines are selected. Press `Option+K` (Mac) / `Alt+K` (Windows/Linux) to insert an @-mention with the file path and line numbers (e.g., `@app.ts#5-10`). Click the selection indicator to toggle whether Claude can see your highlighted text - the eye-slash icon means the selection is hidden from Claude.

102 

103You can also hold `Shift` while dragging files into the prompt box to add them as attachments. Click the X on any attachment to remove it from context.

104 

105### Resume past conversations

106 

107Click the dropdown at the top of the Claude Code panel to access your conversation history. You can search by keyword or browse by time (Today, Yesterday, Last 7 days, etc.). Click any conversation to resume it with the full message history. For more on resuming sessions, see [Common workflows](/en/common-workflows#resume-previous-conversations).

108 

109### Resume remote sessions from Claude.ai

110 

111If you use [Claude Code on the web](/en/claude-code-on-the-web), you can resume those remote sessions directly in VS Code. This requires signing in with **Claude.ai Subscription**, not Anthropic Console.

112 

113<Steps>

114 <Step title="Open Past Conversations">

115 Click the **Past Conversations** dropdown at the top of the Claude Code panel.

116 </Step>

117 

118 <Step title="Select the Remote tab">

119 The dialog shows two tabs: Local and Remote. Click **Remote** to see sessions from claude.ai.

120 </Step>

121 

122 <Step title="Select a session to resume">

123 Browse or search your remote sessions. Click any session to download it and continue the conversation locally.

124 </Step>

125</Steps>

126 

127<Note>

128 Only web sessions started with a GitHub repository appear in the Remote tab. Resuming loads the conversation history locally; changes are not synced back to claude.ai.

129</Note>

130 

131## Customize your workflow

132 

133Once you're up and running, you can reposition the Claude panel, run multiple sessions, or switch to terminal mode.

134 

135### Choose where Claude lives

136 

137You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel's tab or title bar and drag it to:

138 

139* **Secondary sidebar**: The right side of the window. Keeps Claude visible while you code.

140* **Primary sidebar**: The left sidebar with icons for Explorer, Search, etc.

141* **Editor area**: Opens Claude as a tab alongside your files. Useful for side tasks.

142 

143<Tip>

144 Use the sidebar for your main Claude session and open additional tabs for side tasks. Claude remembers your preferred location. Note that the Spark icon only appears in the Activity Bar when the Claude panel is docked to the left. Since Claude defaults to the right side, use the Editor Toolbar icon to open Claude.

145</Tip>

146 

147### Run multiple conversations

148 

149Use **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.

150 

151When 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.

152 

153### Switch to terminal mode

154 

155By 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.

156 

157You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), go to Extensions → Claude Code, and check **Use Terminal**.

158 

159## Manage plugins

160 

161The VS Code extension includes a graphical interface for installing and managing [plugins](/en/plugins). Type `/plugins` in the prompt box to open the **Manage plugins** interface.

162 

163### Install plugins

164 

165The plugin dialog shows two tabs: **Plugins** and **Marketplaces**.

166 

167In the Plugins tab:

168 

169* **Installed plugins** appear at the top with toggle switches to enable or disable them

170* **Available plugins** from your configured marketplaces appear below

171* Search to filter plugins by name or description

172* Click **Install** on any available plugin

173 

174When you install a plugin, choose the installation scope:

175 

176* **Install for you**: Available in all your projects (user scope)

177* **Install for this project**: Shared with project collaborators (project scope)

178* **Install locally**: Only for you, only in this repository (local scope)

179 

180### Manage marketplaces

181 

182Switch to the **Marketplaces** tab to add or remove plugin sources:

183 

184* Enter a GitHub repo, URL, or local path to add a new marketplace

185* Click the refresh icon to update a marketplace's plugin list

186* Click the trash icon to remove a marketplace

43 187 

44### Using Third-Party Providers188After making changes, a banner prompts you to restart Claude Code to apply the updates.

45 189 

46The VS Code extension supports using Claude Code with third-party providers like Amazon Bedrock, Azure AI Foundry, 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:190<Note>

191 Plugin management in VS Code uses the same CLI commands under the hood. Plugins and marketplaces you configure in the extension are also available in the CLI, and vice versa.

192</Note>

47 193 

481. Open VS Code settings194For more about the plugin system, see [Plugins](/en/plugins) and [Plugin marketplaces](/en/plugin-marketplaces).

492. Search for "Claude Code: Environment Variables"

503. Add the required environment variables

51 195 

52#### Environment Variables196## Automate browser tasks with Chrome

53 197 

54| Variable | Description | Required | Example |198Connect Claude to your Chrome browser to test web apps, debug with console logs, and automate browser workflows without leaving VS Code. This requires the [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher.

55| :---------------------------- | :------------------------------------- | :---------------------- | :----------------------------------------------- |

56| `CLAUDE_CODE_USE_BEDROCK` | Enable Amazon Bedrock integration | Required for Bedrock | `"1"` or `"true"` |

57| `CLAUDE_CODE_USE_FOUNDRY` | Enable Azure AI Foundry integration | Required for Foundry | `"1"` or `"true"` |

58| `CLAUDE_CODE_USE_VERTEX` | Enable Google Vertex AI integration | Required for Vertex AI | `"1"` or `"true"` |

59| `AWS_REGION` | AWS region for Bedrock | | `"us-east-2"` |

60| `AWS_PROFILE` | AWS profile for Bedrock authentication | | `"your-profile"` |

61| `CLOUD_ML_REGION` | Region for Vertex AI | | `"global"` or `"us-east5"` |

62| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI | | `"your-project-id"` |

63| `ANTHROPIC_FOUNDRY_RESOURCE` | Azure resource name for Foundry | Required for AI Foundry | `"your-resource"` |

64| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Azure AI Foundry | Optional for AI Foundry | `"your-api-key"` |

65| `ANTHROPIC_MODEL` | Override primary model | Override model ID | `"us.anthropic.claude-sonnet-4-5-20250929-v1:0"` |

66| `ANTHROPIC_SMALL_FAST_MODEL` | Override small/fast model | Optional | `"us.anthropic.claude-3-5-haiku-20241022-v1:0"` |

67| `CLAUDE_CODE_SKIP_AUTH_LOGIN` | Disable all prompts to login | Optional | `"1"` or `"true"` |

68 199 

69For detailed setup instructions and additional configuration options, see:200Type `@browser` in the prompt box followed by what you want Claude to do:

70 201 

71* [Claude Code on Amazon Bedrock](/en/amazon-bedrock)202```text theme={null}

72* [Claude Code on Azure AI Foundry](/en/azure-ai-foundry)203@browser go to localhost:3000 and check the console for errors

73* [Claude Code on Google Vertex AI](/en/google-vertex-ai)204```

74 205 

75### Not Yet Implemented206You can also open the attachment menu to select specific browser tools like opening a new tab or reading page content.

76 207 

77The following features are not yet available in the VS Code extension:208Claude opens new tabs for browser tasks and shares your browser's login state, so it can access any site you're already signed into.

78 209 

79* **MCP server and Plugin configuration UI**: Type `/mcp` to open the terminal-based MCP server configuration, or `/plugin` for Plugin configuration. Once configured, MCP servers and Plugins will work in the extension. You can also [configure MCP servers through the CLI](/en/mcp) first, then the extension will use them.210For setup instructions, the full list of capabilities, and troubleshooting, see [Use Claude Code with Chrome](/en/chrome).

80* **Subagents configuration**: Configure [subagents through the CLI](/en/sub-agents) to use them in VS Code

81* **Checkpoints**: Save and restore conversation state at specific points

82* **Conversation rewinding**: The `/rewind` command is coming soon

83* **Advanced shortcuts**:

84 * `#` shortcut to add to memory (not supported)

85 * `!` shortcut to run bash commands directly (not supported)

86* **Tab completion**: File path completion with tab key

87* **Model selection UI for older models**: To use older model versions like `claude-sonnet-4-20250514`, open VS Code settings for Claude Code (the `/General Config` command) and insert the model string directly into the 'Selected Model' field

88 211 

89We are working on adding these features in future updates.212## VS Code commands and shortcuts

90 213 

91## Security Considerations214Open 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.

92 215 

93When 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.216Some 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.

94 217 

95When running in VS Code, consider:218<Note>

219 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.

220</Note>

96 221 

97* Enabling [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces222| Command | Shortcut | Description |

98* Using manual approval mode for edits223| -------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------ |

99* Taking extra care to ensure Claude is only used with trusted prompts224| Focus Input | `Cmd+Esc` (Mac) / `Ctrl+Esc` (Windows/Linux) | Toggle focus between editor and Claude |

225| Open in Side Bar | - | Open Claude in the left sidebar |

226| Open in Terminal | - | Open Claude in terminal mode |

227| Open in New Tab | `Cmd+Shift+Esc` (Mac) / `Ctrl+Shift+Esc` (Windows/Linux) | Open a new conversation as an editor tab |

228| Open in New Window | - | Open a new conversation in a separate window |

229| New Conversation | `Cmd+N` (Mac) / `Ctrl+N` (Windows/Linux) | Start a new conversation (requires Claude to be focused) |

230| Insert @-Mention Reference | `Option+K` (Mac) / `Alt+K` (Windows/Linux) | Insert a reference to the current file and selection (requires editor to be focused) |

231| Show Logs | - | View extension debug logs |

232| Logout | - | Sign out of your Anthropic account |

100 233 

101## Legacy CLI Integration234## Configure settings

102 235 

103The 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).236The extension has two types of settings:

104 237 

105The 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.238* **Extension settings** in VS Code: Control the extension's behavior within VS Code. Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions Claude Code. You can also type `/` and select **General Config** to open settings.

239* **Claude Code settings** in `~/.claude/settings.json`: Shared between the extension and CLI. Use for allowed commands, environment variables, hooks, and MCP servers. See [Settings](/en/settings) for details.

106 240 

107Both the extension and CLI integration work with Visual Studio Code, Cursor, Windsurf, and VSCodium.241<Tip>

242 Add `"$schema": "https://json.schemastore.org/claude-code-settings.json"` to your `settings.json` to get autocomplete and inline validation for all available settings directly in VS Code.

243</Tip>

108 244 

109## Troubleshooting245### Extension settings

110 246 

111### Extension Not Installing247| Setting | Default | Description |

248| --------------------------------- | --------- | ----------------------------------------------------------------------------------------------------- |

249| `selectedModel` | `default` | Model for new conversations. Change per-session with `/model`. |

250| `useTerminal` | `false` | Launch Claude in terminal mode instead of graphical panel |

251| `initialPermissionMode` | `default` | Controls approval prompts: `default` (ask each time), `plan`, `acceptEdits`, or `bypassPermissions` |

252| `preferredLocation` | `panel` | Where Claude opens: `sidebar` (right) or `panel` (new tab) |

253| `autosave` | `true` | Auto-save files before Claude reads or writes them |

254| `useCtrlEnterToSend` | `false` | Use Ctrl/Cmd+Enter instead of Enter to send prompts |

255| `enableNewConversationShortcut` | `true` | Enable Cmd/Ctrl+N to start a new conversation |

256| `hideOnboarding` | `false` | Hide the onboarding checklist (graduation cap icon) |

257| `respectGitIgnore` | `true` | Exclude .gitignore patterns from file searches |

258| `environmentVariables` | `[]` | Set environment variables for the Claude process. Use Claude Code settings instead for shared config. |

259| `disableLoginPrompt` | `false` | Skip authentication prompts (for third-party provider setups) |

260| `allowDangerouslySkipPermissions` | `false` | Bypass all permission prompts. **Use with extreme caution.** |

261| `claudeProcessWrapper` | - | Executable path used to launch the Claude process |

112 262 

113* Ensure you have a compatible version of VS Code (1.85.0 or later)263## VS Code extension vs. Claude Code CLI

264 

265Claude 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.

266 

267| Feature | CLI | VS Code Extension |

268| ------------------- | --------------------------------------------- | ---------------------------------------- |

269| Commands and skills | [All](/en/interactive-mode#built-in-commands) | Subset (type `/` to see available) |

270| MCP server config | Yes | No (configure via CLI, use in extension) |

271| Checkpoints | Yes | Yes |

272| `!` bash shortcut | Yes | No |

273| Tab completion | Yes | No |

274 

275### Rewind with checkpoints

276 

277The VS Code extension supports checkpoints, which track Claude's file edits and let you rewind to a previous state. Hover over any message to reveal the rewind button, then choose from three options:

278 

279* **Fork conversation from here**: start a new conversation branch from this message while keeping all code changes intact

280* **Rewind code to here**: revert file changes back to this point in the conversation while keeping the full conversation history

281* **Fork conversation and rewind code**: start a new conversation branch and revert file changes to this point

282 

283For full details on how checkpoints work and their limitations, see [Checkpointing](/en/checkpointing).

284 

285### Run CLI in VS Code

286 

287To use the CLI while staying in VS Code, open the integrated terminal (`` Ctrl+` `` on Windows/Linux or `` Cmd+` `` on Mac) and run `claude`. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing.

288 

289If using an external terminal, run `/ide` inside Claude Code to connect it to VS Code.

290 

291### Switch between extension and CLI

292 

293The 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.

294 

295### Include terminal output in prompts

296 

297Reference 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.

298 

299### Monitor background processes

300 

301When 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.

302 

303### Connect to external tools with MCP

304 

305MCP (Model Context Protocol) servers give Claude access to external tools, databases, and APIs. Configure them via CLI, then use them in both extension and CLI.

306 

307To add an MCP server, open the integrated terminal (`` Ctrl+` `` or `` Cmd+` ``) and run:

308 

309```bash theme={null}

310claude mcp add --transport http github https://api.githubcopilot.com/mcp/

311```

312 

313Once configured, ask Claude to use the tools (e.g., "Review PR #456"). Some servers require authentication: run `claude` in the terminal, then type `/mcp` to authenticate. See the [MCP documentation](/en/mcp) for available servers.

314 

315## Work with git

316 

317Claude 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.

318 

319### Create commits and pull requests

320 

321Claude can stage changes, write commit messages, and create pull requests based on your work:

322 

323```

324> commit my changes with a descriptive message

325> create a pr for this feature

326> summarize the changes I've made to the auth module

327```

328 

329When creating pull requests, Claude generates descriptions based on the actual code changes and can add context about testing or implementation decisions.

330 

331### Use git worktrees for parallel tasks

332 

333Git worktrees allow multiple Claude Code sessions to work on separate branches simultaneously, each with isolated files:

334 

335```bash theme={null}

336# Create a worktree for a new feature

337git worktree add ../project-feature-a -b feature-a

338 

339# Run Claude Code in each worktree

340cd ../project-feature-a && claude

341```

342 

343Each worktree maintains independent file state while sharing git history. This prevents Claude instances from interfering with each other when working on different tasks.

344 

345For detailed git workflows including PR reviews and branch management, see [Common workflows](/en/common-workflows#create-pull-requests).

346 

347## Use third-party providers

348 

349By 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:

350 

351<Steps>

352 <Step title="Disable login prompt">

353 Open the [Disable Login Prompt setting](vscode://settings/claudeCode.disableLoginPrompt) and check the box.

354 

355 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**.

356 </Step>

357 

358 <Step title="Configure your provider">

359 Follow the setup guide for your provider:

360 

361 * [Claude Code on Amazon Bedrock](/en/amazon-bedrock)

362 * [Claude Code on Google Vertex AI](/en/google-vertex-ai)

363 * [Claude Code on Microsoft Foundry](/en/microsoft-foundry)

364 

365 These guides cover configuring your provider in `~/.claude/settings.json`, which ensures your settings are shared between the VS Code extension and the CLI.

366 </Step>

367</Steps>

368 

369## Security and privacy

370 

371Your 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).

372 

373With 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:

374 

375* Enable [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces

376* Use manual approval mode instead of auto-accept for edits

377* Review changes carefully before accepting them

378 

379## Fix common issues

380 

381### Extension won't install

382 

383* Ensure you have a compatible version of VS Code (1.98.0 or later)

114* Check that VS Code has permission to install extensions384* Check that VS Code has permission to install extensions

115* Try installing directly from the Marketplace website385* Try installing directly from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code)

386 

387### Spark icon not visible

388 

389The Spark icon appears in the **Editor Toolbar** (top-right of editor) when you have a file open. If you don't see it:

390 

3911. **Open a file**: The icon requires a file to be open. Having just a folder open isn't enough.

3922. **Check VS Code version**: Requires 1.98.0 or higher (Help → About)

3933. **Restart VS Code**: Run "Developer: Reload Window" from the Command Palette

3944. **Disable conflicting extensions**: Temporarily disable other AI extensions (Cline, Continue, etc.)

3955. **Check workspace trust**: The extension doesn't work in Restricted Mode

396 

397Alternatively, 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".

116 398 

117### Claude Code Never Responds399### Claude Code never responds

118 400 

119If Claude Code is not responding to your prompts:401If Claude Code isn't responding to your prompts:

120 402 

1211. **Check your internet connection**: Ensure you have a stable internet connection4031. **Check your internet connection**: Ensure you have a stable internet connection

1222. **Start a new conversation**: Try starting a fresh conversation to see if the issue persists4042. **Start a new conversation**: Try starting a fresh conversation to see if the issue persists

1233. **Try the CLI**: Run `claude` from the terminal to see if you get more detailed error messages4053. **Try the CLI**: Run `claude` from the terminal to see if you get more detailed error messages

1244. **File a bug report**: If the problem continues, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error

125 406 

126### Legacy Integration Not Working407If problems persist, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error.

408 

409## Uninstall the extension

410 

411To uninstall the Claude Code extension:

412 

4131. Open the Extensions view (`Cmd+Shift+X` on Mac or `Ctrl+Shift+X` on Windows/Linux)

4142. Search for "Claude Code"

4153. Click **Uninstall**

416 

417To also remove extension data and reset all settings:

418 

419```bash theme={null}

420rm -rf ~/.vscode/globalStorage/anthropic.claude-code

421```

422 

423For additional help, see the [troubleshooting guide](/en/troubleshooting).

424 

425## Next steps

127 426 

128* Ensure you're running Claude Code from VS Code's integrated terminal427Now that you have Claude Code set up in VS Code:

129* Ensure the CLI for your IDE variant is installed:

130 * VS Code: `code` command should be available

131 * Cursor: `cursor` command should be available

132 * Windsurf: `windsurf` command should be available

133 * VSCodium: `codium` command should be available

134* If the command isn't installed:

135 1. Open command palette with `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux)

136 2. Search for "Shell Command: Install 'code' command in PATH" (or equivalent for your IDE)

137 428 

138For additional help, see our [troubleshooting guide](/en/troubleshooting).429* [Explore common workflows](/en/common-workflows) to get the most out of Claude Code

430* [Set up MCP servers](/en/mcp) to extend Claude's capabilities with external tools. Configure servers using the CLI, then use them in the extension.

431* [Configure Claude Code settings](/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.