Expand description
Claude Code’s settings.json as Rust types.
Claude Code reads its configuration from
layered JSON settings files and from the --settings command-line
argument. This crate types every key those documents accept, so a
program can build one, write it for claude --settings, read settings
files, and layer them the way Claude Code does, without hand-built JSON.
Settings: the whole document. Every key Claude Code’s published JSON schema and its settings reference list is a field, with the nested objects typed:Permissions,Hooks,Sandbox, marketplaces, plugin configuration, model settings and the rest. Each field’s docs say what Claude Code does with it, the values it accepts, its default and where it may be set, with a link to its entry in the settings reference.Settings::to_json_string: the document for--settings;Settings::to_json_string_prettyfor a file.Settings::mergeandmerge_values: Claude Code’s layer merge.Settings::unknown_keys: the keys a document holds that this crate doesn’t model.
The crate depends on serde and serde_json only, and does no I/O. It is not affiliated with or endorsed by Anthropic.
§Build a --settings document
Every type is #[non_exhaustive], so that Claude Code’s new keys can be
added without a breaking release: start from Default::default() and
set fields. Only what is set is written.
use claude_code_settings::{Hook, HookEvent, HookMatcher, PermissionMode, Permissions, Settings};
let mut permissions = Permissions::default();
permissions.allow = Some(vec!["Bash(git diff *)".into(), "Read".into()]);
permissions.deny = Some(vec!["Bash(rm *)".into()]);
permissions.default_mode = Some(PermissionMode::DontAsk);
let mut settings = Settings::default();
settings.permissions = Some(permissions);
settings.include_git_instructions = Some(false);
settings.hooks.get_or_insert_default().insert(
HookEvent::PreToolUse,
vec![HookMatcher::matching("Bash", [Hook::command("./scripts/check-command")])],
);
let arg = settings.to_json_string()?;
assert!(arg.contains(r#""defaultMode":"dontAsk""#));
// std::process::Command::new("claude").args(["--settings", &arg, "-p", "..."]);§Read a settings file, keeping what this crate doesn’t know
A key, an enum value, a hook type or a hook event this crate doesn’t
model is kept as written (in an extra map, an Other variant or
Hook::Other) and written back unchanged, so a file from a newer
Claude Code survives a parse, a change and a write.
use claude_code_settings::{PermissionMode, Settings};
let file = r#"{
"model": "opus",
"permissions": {"defaultMode": "someFutureMode", "allow": ["Read"]},
"aKeyFromANewerVersion": {"enabled": true}
}"#;
let mut settings = Settings::from_json_str(file)?;
assert_eq!(
settings.permissions.as_ref().and_then(|p| p.default_mode.clone()),
Some(PermissionMode::Other("someFutureMode".into())),
);
assert_eq!(settings.unknown_keys(), ["aKeyFromANewerVersion"]);
settings.model = Some("sonnet".into());
let written = settings.to_json_string_pretty()?;
assert!(written.contains("aKeyFromANewerVersion"));
assert!(written.contains("someFutureMode"));§Layer settings
Claude Code reads settings from several sources. Highest precedence first:
- Managed settings: what an organization deploys
(
managed-settings.json, MDM, or server-managed settings). Nothing below overrides a managed key. - Command line:
--settings <file-or-json>, for one session. - Local project settings:
.claude/settings.local.json. - Shared project settings:
.claude/settings.json. - User settings:
~/.claude/settings.json.
Claude Code merges them rather than picking one:
- a scalar (a string, number or Boolean) comes from the highest source that sets it;
- objects merge key by key, so
env,permissionsandsandboxcombine across sources; - lists concatenate, so
permissions.allow,askanddeny, and each hook event’s matcher groups, add up;fallbackModelandmodelPickerare exceptions, taken whole from the highest source.
Merging decides what each key holds, not how rules are applied: a
deny rule from any source beats an allow rule from any other
(Claude Code evaluates deny, then ask, then allow). Some keys are
honored only from some sources (managed-only keys, keys project settings
can’t set), which each field’s Scope line says and the merge does
not enforce. Claude Code also watches its settings files and reloads
most keys in a running session when a file changes; a few, such as
model, are read only at session start.
Settings::merge applies one layer over another; call it on the
lowest layer with each higher one in turn:
use claude_code_settings::Settings;
let user = Settings::from_json_str(r#"{
"model": "opus",
"env": {"EDITOR": "vim"},
"permissions": {"allow": ["Read"]}
}"#)?;
let project = Settings::from_json_str(r#"{
"model": "sonnet",
"env": {"RUST_LOG": "info"},
"permissions": {"allow": ["Bash(cargo test *)"], "deny": ["Bash(rm *)"]}
}"#)?;
let mut effective = user;
effective.merge(project)?;
assert_eq!(effective.model.as_deref(), Some("sonnet"));
assert_eq!(effective.env.as_ref().map(|e| e.len()), Some(2));
let permissions = effective.permissions.unwrap_or_default();
assert_eq!(permissions.allow.unwrap_or_default(), ["Read", "Bash(cargo test *)"]);
assert_eq!(permissions.deny.unwrap_or_default(), ["Bash(rm *)"]);§Compatibility
The types track CLAUDE_CODE_VERSION and the JSON schema fetched on
SCHEMA_FETCHED. A fully populated document is checked against that
Claude Code release: it loads with no key rejected. New keys and values
are additive: the types are #[non_exhaustive], and an older release of
this crate keeps a newer key in extra rather than dropping it.
§Keeping up with Claude Code
The repository keeps a copy of the published schema
(https://json.schemastore.org/claude-code-settings.json) next to the
crate. scripts/refresh-settings-schema fetches it again, and the
crate’s schema test then lists, by JSON path, every property and every
enum value the new schema has that the types don’t. An opt-in test hands
a fully populated document to a real claude --settings and fails on any
key it rejects.
§License
Licensed under the Apache License, Version 2.0.
Structs§
- Agent
Hook - An
agenthook. - Attribution
attribution: what Claude Code adds to commits and pull requests.- Auto
Mode autoMode: the auto-mode classifier’s sections. Each list replaces the built-in one unless it holds the literal$defaults.- AwsPair
- An entry of
sandbox.credentials.awsPairs. - Channel
Plugin - An entry of
allowedChannelPlugins. - Command
Hook - A
commandhook. - Command
Setting fileSuggestionandsubagentStatusLine: acommandhandler.- Credential
EnvVar - An entry of
sandbox.credentials.envVars. - Credential
File - An entry of
sandbox.credentials.files. - Footer
Link - An entry of
footerLinksRegexes. - Hook
Matcher - A matcher group: the hooks to run when
matchermatches the event. - Http
Hook - An
httphook. - Inline
Plugin - A plugin of an inline (
settings) marketplace. - Marketplace
- An entry of
extraKnownMarketplaces. - McpServer
Rule - An entry of
allowedMcpServersordeniedMcpServers: one of the three fields. - McpTool
Hook - An
mcp_toolhook. - Model
Picker modelPicker: the/modelpicker’s rows.- Model
Picker Option - A row of
modelPicker.options. - Model
Pricing modelPricing: contracted rates (managed settings).- Model
Rates - A model’s rates, in USD per million tokens.
- Model
Settings - A value of
modelSettings: one model’s saved settings. - Permissions
permissions: rules and the starting mode.- Plugin
Config - A value of
pluginConfigs: a plugin’s user configuration. - Policy
Helper policyHelper: a program that computes managed settings.- Prompt
Hook - A
prompthook. - Remote
remote: cloud sessions.- Ripgrep
sandbox.ripgrep.- Sandbox
sandbox.- Sandbox
Credentials sandbox.credentials.- Sandbox
Filesystem sandbox.filesystem.- Sandbox
Network sandbox.network.- Settings
- Claude Code’s settings.json: one settings file, a
--settingsdocument, or the merge of several. - Sigv4
sandbox.credentials.sigv4.- Source
- A marketplace or plugin source:
sourcenames the kind, and the other fields are the ones that kind takes (github:repo,ref,path;npm:package; and so on). One struct for every kind, so a kind this crate doesn’t know still parses. - Spellcheck
spellcheck.- Spinner
Tips spinnerTipsOverride.- Spinner
Verbs spinnerVerbs.- SshConfig
- An entry of
sshConfigs. - SshHost
Command - An entry of
sshHostCommands: a desktop SSH connection opened by a command. - Status
Line statusLine: a command that prints the status line from the session JSON on its stdin.- TipEntry
- A tip object.
- TlsTerminate
sandbox.network.tlsTerminate; empty for a generated CA.- Voice
voice.- Worktree
worktree.
Enums§
- Attribution
Setting attribution: the object, orfalseto hide all attribution.- BgIsolation
worktree.bgIsolation.- Cache
Ttl promptCacheTtlandsubagentPromptCacheTtl.- Channel
Plugin Entry - An entry of
allowedChannelPlugins. - Compact
Window modelSettings.*.autoCompactWindow.- Credential
Mode sandbox.credentials.*.mode.- Customization
Kind - An entry of
strictPluginOnlyCustomization. - Dialog
Timeout askUserQuestionTimeoutanddialogExpiry.- Diff
Tool diffTool.- Disable
Flag - The one value of the
disable*keys that turn a feature off (permissions.disableBypassPermissionsMode,disableAutoMode,disableDeepLinkRegistration). - Disabled
Flag browserExternalPageTools.- Editor
Mode editorMode.- Effort
Level effortLevel,maxEffortLevelandmodelSettings.*.effortLevel.maxis valid only as a cap.- Extract
NoMatch - A credential’s
onExtractNoMatch. - Feedback
Drafts feedbackDrafts.- Hook
- A hook, by its
type. - Hook
Event - A hook event: a key of
hooks. - Hook
OnFailure - A hook’s
onFailure. - Inbound
Mode crossSessionInbound.- Keybinding
Flavor keybindingFlavor.- Login
Method forceLoginMethod.- Managed
McpServers managedMcpServers: MCP server configurations, by name or as a list.- Model
Match availableModelsMatch.- Notif
Channel preferredNotifChannel.- OneOr
Many forceLoginOrgUUID: one organization or several.- Option
Value - A plugin option’s value.
- Permission
Mode permissions.defaultMode: the permission mode a session starts in.- Platform
sandbox.enabledPlatforms.- Plugin
Enabled - A value of
enabledPlugins. - Provider
- An entry of
allowedProviders. - Shell
defaultShelland a command hook’sshell.- Sigv4
Action - A value of
sandbox.credentials.sigv4. - Skill
Override - A value of
skillOverrides. - Source
Kind - A marketplace or plugin source’s
source. - Sources
Behavior parentSettingsBehaviorandmanagedSourcesBehavior.- Spell
Checker spellcheck.checker.- Spinner
Tip - An entry of
spinnerTipsOverride.tips. - Spinner
Verbs Mode spinnerVerbs.mode.- Strict
Customization strictPluginOnlyCustomization.- Teammate
Mode teammateMode: how agent-team teammates are shown.- Theme
theme. A custom theme’s name isOther.- Time
Format timeFormat. A strftime pattern (any value with a%) isOther.- Token
Decode - A credential’s
decode. - Tui
tui.- Updates
Channel autoUpdatesChannel.- View
Mode viewMode.- Voice
Mode voice.mode.- Workflow
Size workflowSizeGuideline.- Worktree
Base Ref worktree.baseRef.
Constants§
- CLAUDE_
CODE_ VERSION - The Claude Code release these types were last checked against.
- SCHEMA_
FETCHED - The date (UTC) the copy of the settings JSON schema these types follow was fetched.
Functions§
- merge_
values - Layers the settings document
higheroverlower, in place, the way Claude Code merges settings sources (checked against 2.1.322’s merge, a lodashmergeWith):