Skip to main content

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