claude_code_settings/lib.rs
1//! Claude Code's `settings.json` as Rust types.
2//!
3//! [Claude Code](https://code.claude.com/docs) reads its configuration from
4//! layered JSON settings files and from the `--settings` command-line
5//! argument. This crate types every key those documents accept, so a
6//! program can build one, write it for `claude --settings`, read settings
7//! files, and layer them the way Claude Code does, without hand-built JSON.
8//!
9//! - [`Settings`]: the whole document. Every key Claude Code's published
10//! JSON schema and its [settings reference] list is a field, with the
11//! nested objects typed: [`Permissions`], [`Hooks`], [`Sandbox`],
12//! marketplaces, plugin configuration, model settings and the rest. Each
13//! field's docs say what Claude Code does with it, the values it accepts,
14//! its default and where it may be set, with a link to its entry in the
15//! settings reference.
16//! - [`Settings::to_json_string`]: the document for `--settings`;
17//! [`Settings::to_json_string_pretty`] for a file.
18//! - [`Settings::merge`] and [`merge_values`]: Claude Code's layer merge.
19//! - [`Settings::unknown_keys`]: the keys a document holds that this crate
20//! doesn't model.
21//!
22//! The crate depends on serde and serde_json only, does no I/O, and is
23//! `#![no_std]` (it needs only `alloc`). It is
24//! not affiliated with or endorsed by Anthropic.
25//!
26//! [settings reference]: https://code.claude.com/docs/en/settings-reference
27//!
28//! # Build a `--settings` document
29//!
30//! Every type is `#[non_exhaustive]`, so that Claude Code's new keys can be
31//! added without a breaking release: start from `Default::default()` and
32//! set fields. Only what is set is written.
33//!
34//! ```
35//! use claude_code_settings::{Hook, HookEvent, HookMatcher, PermissionMode, Permissions, Settings};
36//!
37//! let mut permissions = Permissions::default();
38//! permissions.allow = Some(vec!["Bash(git diff *)".into(), "Read".into()]);
39//! permissions.deny = Some(vec!["Bash(rm *)".into()]);
40//! permissions.default_mode = Some(PermissionMode::DontAsk);
41//!
42//! let mut settings = Settings::default();
43//! settings.permissions = Some(permissions);
44//! settings.include_git_instructions = Some(false);
45//! settings.hooks.get_or_insert_default().insert(
46//! HookEvent::PreToolUse,
47//! vec![HookMatcher::matching("Bash", [Hook::command("./scripts/check-command")])],
48//! );
49//!
50//! let arg = settings.to_json_string()?;
51//! assert!(arg.contains(r#""defaultMode":"dontAsk""#));
52//! // std::process::Command::new("claude").args(["--settings", &arg, "-p", "..."]);
53//! # Ok::<(), serde_json::Error>(())
54//! ```
55//!
56//! # Read a settings file, keeping what this crate doesn't know
57//!
58//! A key, an enum value, a hook type or a hook event this crate doesn't
59//! model is kept as written (in an `extra` map, an `Other` variant or
60//! [`Hook::Other`]) and written back unchanged, so a file from a newer
61//! Claude Code survives a parse, a change and a write.
62//!
63//! ```
64//! use claude_code_settings::{PermissionMode, Settings};
65//!
66//! let file = r#"{
67//! "model": "opus",
68//! "permissions": {"defaultMode": "someFutureMode", "allow": ["Read"]},
69//! "aKeyFromANewerVersion": {"enabled": true}
70//! }"#;
71//! let mut settings = Settings::from_json_str(file)?;
72//! assert_eq!(
73//! settings.permissions.as_ref().and_then(|p| p.default_mode.clone()),
74//! Some(PermissionMode::Other("someFutureMode".into())),
75//! );
76//! assert_eq!(settings.unknown_keys(), ["aKeyFromANewerVersion"]);
77//!
78//! settings.model = Some("sonnet".into());
79//! let written = settings.to_json_string_pretty()?;
80//! assert!(written.contains("aKeyFromANewerVersion"));
81//! assert!(written.contains("someFutureMode"));
82//! # Ok::<(), serde_json::Error>(())
83//! ```
84//!
85//! # Layer settings
86//!
87//! Claude Code reads settings from several sources. Highest precedence
88//! first:
89//!
90//! 1. **Managed settings**: what an organization deploys
91//! (`managed-settings.json`, MDM, or server-managed settings). Nothing
92//! below overrides a managed key.
93//! 2. **Command line**: `--settings <file-or-json>`, for one session.
94//! 3. **Local project settings**: `.claude/settings.local.json`.
95//! 4. **Shared project settings**: `.claude/settings.json`.
96//! 5. **User settings**: `~/.claude/settings.json`.
97//!
98//! Claude Code merges them rather than picking one:
99//!
100//! - a scalar (a string, number or Boolean) comes from the highest source
101//! that sets it;
102//! - objects merge key by key, so `env`, `permissions` and `sandbox`
103//! combine across sources;
104//! - lists concatenate, so `permissions.allow`, `ask` and `deny`, and each
105//! hook event's matcher groups, add up; `fallbackModel` and
106//! `modelPicker` are exceptions, taken whole from the highest source.
107//!
108//! Merging decides what each key holds, not how rules are applied: a
109//! `deny` rule from any source beats an `allow` rule from any other
110//! (Claude Code evaluates `deny`, then `ask`, then `allow`). Some keys are
111//! honored only from some sources (managed-only keys, keys project settings
112//! can't set), which each field's **Scope** line says and the merge does
113//! not enforce. Claude Code also watches its settings files and reloads
114//! most keys in a running session when a file changes; a few, such as
115//! `model`, are read only at session start.
116//!
117//! [`Settings::merge`] applies one layer over another; call it on the
118//! lowest layer with each higher one in turn:
119//!
120//! ```
121//! use claude_code_settings::Settings;
122//!
123//! let user = Settings::from_json_str(r#"{
124//! "model": "opus",
125//! "env": {"EDITOR": "vim"},
126//! "permissions": {"allow": ["Read"]}
127//! }"#)?;
128//! let project = Settings::from_json_str(r#"{
129//! "model": "sonnet",
130//! "env": {"RUST_LOG": "info"},
131//! "permissions": {"allow": ["Bash(cargo test *)"], "deny": ["Bash(rm *)"]}
132//! }"#)?;
133//!
134//! let mut effective = user;
135//! effective.merge(project)?;
136//! assert_eq!(effective.model.as_deref(), Some("sonnet"));
137//! assert_eq!(effective.env.as_ref().map(|e| e.len()), Some(2));
138//! let permissions = effective.permissions.unwrap_or_default();
139//! assert_eq!(permissions.allow.unwrap_or_default(), ["Read", "Bash(cargo test *)"]);
140//! assert_eq!(permissions.deny.unwrap_or_default(), ["Bash(rm *)"]);
141//! # Ok::<(), serde_json::Error>(())
142//! ```
143//!
144//! # Compatibility
145//!
146//! The types track [`CLAUDE_CODE_VERSION`] and the JSON schema fetched on
147//! [`SCHEMA_FETCHED`]. A fully populated document is checked against that
148//! Claude Code release: it loads with no key rejected. New keys and values
149//! are additive: the types are `#[non_exhaustive]`, and an older release of
150//! this crate keeps a newer key in `extra` rather than dropping it.
151//!
152//! # Keeping up with Claude Code
153//!
154//! The repository keeps a copy of the published schema
155//! (<https://json.schemastore.org/claude-code-settings.json>) next to the
156//! crate. `scripts/refresh-settings-schema` fetches it again, and the
157//! crate's `schema` test then lists, by JSON path, every property and every
158//! enum value the new schema has that the types don't. An opt-in test hands
159//! a fully populated document to a real `claude --settings` and fails on any
160//! key it rejects.
161//!
162//! # License
163//!
164//! Licensed under the Apache License, Version 2.0.
165
166#![deny(missing_docs)]
167#![allow(
168 clippy::doc_markdown,
169 reason = "the docs quote Claude Code's settings reference, product names and all"
170)]
171#![deny(rustdoc::broken_intra_doc_links)]
172#![no_std]
173
174extern crate alloc;
175
176mod enums;
177mod hooks;
178mod merge;
179mod models;
180mod permissions;
181mod plugins;
182mod sandbox;
183mod settings;
184mod types;
185mod walk;
186
187pub use enums::{
188 BgIsolation, CacheTtl, CredentialMode, CustomizationKind, DialogTimeout, DiffTool, DisableFlag,
189 DisabledFlag, EditorMode, EffortLevel, ExtractNoMatch, FeedbackDrafts, HookEvent,
190 HookOnFailure, InboundMode, KeybindingFlavor, LoginMethod, ModelMatch, NotifChannel,
191 PermissionMode, Platform, Provider, Shell, Sigv4Action, SkillOverride, SourceKind,
192 SourcesBehavior, SpellChecker, SpinnerVerbsMode, TeammateMode, Theme, TimeFormat, TokenDecode,
193 Tui, UpdatesChannel, ViewMode, VoiceMode, WorkflowSize, WorktreeBaseRef,
194};
195pub use hooks::{
196 AgentHook, CommandHook, Hook, HookMatcher, Hooks, HttpHook, McpToolHook, PromptHook,
197};
198pub use merge::merge_values;
199pub use models::{
200 CompactWindow, ModelPicker, ModelPickerOption, ModelPricing, ModelRates, ModelSettings,
201};
202pub use permissions::{AutoMode, McpServerRule, Permissions};
203pub use plugins::{
204 ChannelPlugin, ChannelPluginEntry, InlinePlugin, Marketplace, OptionValue, PluginConfig,
205 PluginEnabled, Source, StrictCustomization,
206};
207pub use sandbox::{
208 AwsPair, CredentialEnvVar, CredentialFile, Ripgrep, Sandbox, SandboxCredentials,
209 SandboxFilesystem, SandboxNetwork, Sigv4, TlsTerminate,
210};
211pub use settings::Settings;
212pub use types::{
213 Attribution, AttributionSetting, CommandSetting, FooterLink, ManagedMcpServers, OneOrMany,
214 PolicyHelper, Remote, Spellcheck, SpinnerTip, SpinnerTips, SpinnerVerbs, SshConfig,
215 SshHostCommand, StatusLine, TipEntry, Voice, Worktree,
216};
217
218/// The README's examples, compiled as doctests.
219#[cfg(doctest)]
220#[doc = include_str!("../README.md")]
221struct ReadmeDoctests;
222
223/// The Claude Code release these types were last checked against.
224pub const CLAUDE_CODE_VERSION: &str = "2.1.322";
225
226/// The date (UTC) the copy of the settings JSON schema these types follow
227/// was fetched.
228pub const SCHEMA_FETCHED: &str = "2026-11-13";
229
230/// The keys an object holds that this crate doesn't model, by name.
231pub type Extra = serde_json::Map<alloc::string::String, serde_json::Value>;