Skip to main content

Crate claude_code_settings

Crate claude_code_settings 

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

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:

  1. Managed settings: what an organization deploys (managed-settings.json, MDM, or server-managed settings). Nothing below overrides a managed key.
  2. Command line: --settings <file-or-json>, for one session.
  3. Local project settings: .claude/settings.local.json.
  4. Shared project settings: .claude/settings.json.
  5. 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, permissions and sandbox combine across sources;
  • lists concatenate, so permissions.allow, ask and deny, and each hook event’s matcher groups, add up; fallbackModel and modelPicker are 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§

AgentHook
An agent hook.
Attribution
attribution: what Claude Code adds to commits and pull requests.
AutoMode
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.
ChannelPlugin
An entry of allowedChannelPlugins.
CommandHook
A command hook.
CommandSetting
fileSuggestion and subagentStatusLine: a command handler.
CredentialEnvVar
An entry of sandbox.credentials.envVars.
CredentialFile
An entry of sandbox.credentials.files.
FooterLink
An entry of footerLinksRegexes.
HookMatcher
A matcher group: the hooks to run when matcher matches the event.
HttpHook
An http hook.
InlinePlugin
A plugin of an inline (settings) marketplace.
Marketplace
An entry of extraKnownMarketplaces.
McpServerRule
An entry of allowedMcpServers or deniedMcpServers: one of the three fields.
McpToolHook
An mcp_tool hook.
ModelPicker
modelPicker: the /model picker’s rows.
ModelPickerOption
A row of modelPicker.options.
ModelPricing
modelPricing: contracted rates (managed settings).
ModelRates
A model’s rates, in USD per million tokens.
ModelSettings
A value of modelSettings: one model’s saved settings.
Permissions
permissions: rules and the starting mode.
PluginConfig
A value of pluginConfigs: a plugin’s user configuration.
PolicyHelper
policyHelper: a program that computes managed settings.
PromptHook
A prompt hook.
Remote
remote: cloud sessions.
Ripgrep
sandbox.ripgrep.
Sandbox
sandbox.
SandboxCredentials
sandbox.credentials.
SandboxFilesystem
sandbox.filesystem.
SandboxNetwork
sandbox.network.
Settings
Claude Code’s settings.json: one settings file, a --settings document, or the merge of several.
Sigv4
sandbox.credentials.sigv4.
Source
A marketplace or plugin source: source names 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.
SpinnerTips
spinnerTipsOverride.
SpinnerVerbs
spinnerVerbs.
SshConfig
An entry of sshConfigs.
SshHostCommand
An entry of sshHostCommands: a desktop SSH connection opened by a command.
StatusLine
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§

AttributionSetting
attribution: the object, or false to hide all attribution.
BgIsolation
worktree.bgIsolation.
CacheTtl
promptCacheTtl and subagentPromptCacheTtl.
ChannelPluginEntry
An entry of allowedChannelPlugins.
CompactWindow
modelSettings.*.autoCompactWindow.
CredentialMode
sandbox.credentials.*.mode.
CustomizationKind
An entry of strictPluginOnlyCustomization.
DialogTimeout
askUserQuestionTimeout and dialogExpiry.
DiffTool
diffTool.
DisableFlag
The one value of the disable* keys that turn a feature off (permissions.disableBypassPermissionsMode, disableAutoMode, disableDeepLinkRegistration).
DisabledFlag
browserExternalPageTools.
EditorMode
editorMode.
EffortLevel
effortLevel, maxEffortLevel and modelSettings.*.effortLevel. max is valid only as a cap.
ExtractNoMatch
A credential’s onExtractNoMatch.
FeedbackDrafts
feedbackDrafts.
Hook
A hook, by its type.
HookEvent
A hook event: a key of hooks.
HookOnFailure
A hook’s onFailure.
InboundMode
crossSessionInbound.
KeybindingFlavor
keybindingFlavor.
LoginMethod
forceLoginMethod.
ManagedMcpServers
managedMcpServers: MCP server configurations, by name or as a list.
ModelMatch
availableModelsMatch.
NotifChannel
preferredNotifChannel.
OneOrMany
forceLoginOrgUUID: one organization or several.
OptionValue
A plugin option’s value.
PermissionMode
permissions.defaultMode: the permission mode a session starts in.
Platform
sandbox.enabledPlatforms.
PluginEnabled
A value of enabledPlugins.
Provider
An entry of allowedProviders.
Shell
defaultShell and a command hook’s shell.
Sigv4Action
A value of sandbox.credentials.sigv4.
SkillOverride
A value of skillOverrides.
SourceKind
A marketplace or plugin source’s source.
SourcesBehavior
parentSettingsBehavior and managedSourcesBehavior.
SpellChecker
spellcheck.checker.
SpinnerTip
An entry of spinnerTipsOverride.tips.
SpinnerVerbsMode
spinnerVerbs.mode.
StrictCustomization
strictPluginOnlyCustomization.
TeammateMode
teammateMode: how agent-team teammates are shown.
Theme
theme. A custom theme’s name is Other.
TimeFormat
timeFormat. A strftime pattern (any value with a %) is Other.
TokenDecode
A credential’s decode.
Tui
tui.
UpdatesChannel
autoUpdatesChannel.
ViewMode
viewMode.
VoiceMode
voice.mode.
WorkflowSize
workflowSizeGuideline.
WorktreeBaseRef
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 higher over lower, in place, the way Claude Code merges settings sources (checked against 2.1.322’s merge, a lodash mergeWith):

Type Aliases§

Extra
The keys an object holds that this crate doesn’t model, by name.
Hooks
hooks: for each HookEvent, its matcher groups.