ClaudeCode.Options (ClaudeCode v0.36.3)

View Source

Session option validation, CLI flag conversion, and configuration guide.

This module is the single source of truth for all options passed to ClaudeCode.start_link/1 or ClaudeCode.query/2. It provides validation using NimbleOptions, converts Elixir options to CLI flags, and manages option precedence.

Option Precedence

Options are resolved in this order (highest to lowest priority):

  1. Session-level options — passed to start_link/1 or query/2

  2. Application config — set in config/config.exs

  3. Default values — built-in defaults

    # Application config (lowest priority) config :claude_code, timeout: 300_000

    # Session-level overrides app config {:ok, session} = ClaudeCode.start_link(timeout: 120_000)

Session Options

Options for ClaudeCode.start_link/1 and ClaudeCode.query/2. These are set once when the CLI subprocess is launched and apply to the entire session.

Authentication & Identity

OptionTypeDefaultDescription
api_keystringANTHROPIC_API_KEY envAnthropic API key (passed via env var to CLI, never in arguments)
nameatom-Register the session process with a name for easy reference. See Named Sessions
session_idstringauto-generatedUse a specific UUID instead of auto-generating one

Model & Prompting

OptionTypeDefaultDescription
modelstring"sonnet"Model alias ("sonnet", "opus", "haiku") or full model ID
fallback_modelstring-Automatic fallback model when the primary is overloaded
system_promptstring-Replace the entire default system prompt. See Modifying System Prompts
append_system_promptstring-Append custom text to the end of the default system prompt. See Modifying System Prompts
agentstring-Select a named agent for the session. Must be defined in :agents or settings. See Subagents
agentslist/map-Define custom subagents. See Subagents and ClaudeCode.Agent
thinkingatom/tuple-Extended thinking: :adaptive, :disabled, or {:enabled, budget_tokens: N}
effortatom-Thinking effort: :low, :medium, :high, :max (:max is Opus only)
betaslist-Beta feature flags (e.g. ["context-1m-2025-08-07"], API key users only)
max_thinking_tokensinteger-Deprecated: use :thinking instead

Limits

OptionTypeDefaultDescription
timeouttimeout:infinityMax wait for next message on the stream (ms or :infinity). Resets on each message
control_timeoutpos_integer60_000Max wait for CLI control responses (initialize handshake, MCP server startup)
max_turnsintegerunlimitedMaximum agentic turns (tool-use round trips). Exits with error when reached. See Cost Controls
max_budget_usdnumber-Maximum dollar amount to spend on API calls before stopping. See Cost Controls
max_buffer_sizepos_integer1_048_576Max buffer size in bytes for incoming JSON data. Protects against unbounded memory growth

Tool Control

OptionTypeDefaultDescription
toolsatom/list-Restrict which built-in tools are available: :default (all), [] (none), or list of names. See Permissions
allowed_toolslist-Tools to auto-approve without prompting (e.g. ["View", "Bash(git:*)"]). Unlisted tools fall through to :permission_mode. See Allow and deny rules
disallowed_toolslist-Tools to always deny. Checked first, overrides :allowed_tools and :permission_mode. See Allow and deny rules
add_dirlist-Additional directories Claude can access (each path validated as existing directory)
tool_configmap-Per-tool config (e.g. %{"askUserQuestion" => %{"previewFormat" => "html"}})

Permissions & Security

OptionTypeDefaultDescription
permission_modeatom:default:default, :accept_edits, :bypass_permissions, :delegate, :dont_ask, :plan. See Permission modes
can_use_toolmodule/fn-Programmatic permission callback. Mutually exclusive with :permission_prompt_tool. See can_use_tool
permission_prompt_toolstring-MCP tool name for permission prompts in non-interactive mode. See Permission delegation
sandboxstruct/kw/map-Sandbox settings for bash command isolation. See ClaudeCode.Sandbox and Secure Deployment
allow_dangerously_skip_permissionsbooleanfalseEnable permission bypassing as an option. Required when using :bypass_permissions mode
dangerously_skip_permissionsbooleanfalseDirectly bypass all permission checks. Only for sandboxes with no internet access

MCP Servers

See the MCP guide for setup, transport types, tool search, and authentication.

OptionTypeDefaultDescription
mcp_configstring-Path to MCP servers JSON config file (or JSON string). See From a config file
mcp_serversmap-Inline MCP server config. Values: Anubis module atom or config map per server. See In code
strict_mcp_configbooleanfalseOnly use servers from :mcp_config/:mcp_servers, ignore global config. See Strict MCP configuration

Session Lifecycle

See the Sessions guide for resume, fork, and supervision patterns.

OptionTypeDefaultDescription
resumestring-Resume a previous conversation by session ID. See Resume by ID
resume_session_atstring-When resuming, only include messages up to this UUID (use with :resume)
fork_sessionbooleanfalseWhen resuming, create a new session ID instead of reusing the original. See Fork to explore alternatives
continuebooleanfalseContinue the most recent conversation in the current directory
from_prstring/integer-Resume a session linked to a GitHub PR by number or URL
no_session_persistencebooleanfalseDisable session persistence — sessions won't be saved to disk or resumable
worktreeboolean/string-Run in an isolated git worktree (true for auto-named, or branch name string)

Output & Streaming

OptionTypeDefaultDescription
output_formatmap-Structured output: %{type: :json_schema, schema: schema_map}. See Structured Outputs
include_partial_messagesbooleanfalseInclude partial message chunks for character-level streaming. See Streaming Output
replay_user_messagesbooleanfalseRe-emit user messages from stdin back on stdout for acknowledgment
prompt_suggestionsbooleanfalseEmit predicted next user prompts after each turn

Settings & Plugins

OptionTypeDefaultDescription
settingsmap/string-Load additional settings from a file path, JSON string, or map (auto-encoded to JSON)
setting_sourceslist-Which filesystem settings to load: ["user", "project", "local"]. Include "project" for CLAUDE.md files
pluginslist-Load custom plugins (strings or maps with type: :local). See Plugins and ClaudeCode.Plugin
hooksmap-Lifecycle hook configurations for intercepting events. See Hooks
disable_slash_commandsbooleanfalseDisable all skills and slash commands for this session. See Skills

Environment & CLI

OptionTypeDefaultDescription
envmap%{}Extra env vars merged into CLI subprocess. String values set, false unsets
inherit_envatom/list:allSystem env inheritance: :all, [], or list of names/{:prefix, "..."} tuples. See Environment Variable Control
cwdstring-Working directory for the CLI subprocess
cli_pathatom/string:bundledCLI binary resolution: :bundled (auto-install), :global (system), or explicit path
filelist-File resources to download at startup ("file_id:relative_path" format)
enable_file_checkpointingbooleanfalseTrack file changes for rewinding. See File Checkpointing
extra_argsmap%{}Additional CLI arguments passed directly to the binary (flag → value or true for boolean flags)

Debugging

OptionTypeDefaultDescription
debugboolean/string-Enable debug mode with optional category filter (e.g. "api,hooks" or "!1p,!file")
debug_filestring-Write debug logs to a specific file path (implicitly enables debug)

Elixir SDK Only

These options are specific to the Elixir SDK and have no CLI or upstream SDK equivalent.

OptionTypeDefaultDescription
adaptertupleCLI adapterBackend adapter as {Module, config}. See ClaudeCode.Adapter, Distributed Sessions

Note: :name, :timeout, :control_timeout, :max_buffer_size, :inherit_env, and :hooks are also Elixir-only — they control SDK-side behavior and are not sent to the CLI. They appear in their respective sections above.

Application Configuration

Set defaults in config/config.exs:

config :claude_code,
  api_key: System.get_env("ANTHROPIC_API_KEY"),
  model: "sonnet",
  timeout: 180_000,
  system_prompt: "You are a helpful assistant",
  allowed_tools: ["View"]

CLI Binary Configuration

The SDK manages the Claude CLI binary via application config:

config :claude_code,
  cli_path: :bundled,               # :bundled (default), :global, or "/path/to/claude"
  cli_version: "x.y.z",            # Version to install (default: SDK's tested version)
  cli_dir: nil                      # Directory for downloaded binary (default: priv/bin/)
ModeValueBehavior
Bundled:bundled (default)Uses priv/bin/ binary. Auto-installs if missing. Verifies version matches SDK
Global:globalFinds existing system install via PATH or common locations. No auto-install
Explicit"/path/to/claude"Uses that exact binary. Error if not found

Mix tasks: mix claude_code.install, mix claude_code.uninstall, mix claude_code.path.

For releases, see Hosting.

Environment-Specific Configuration

# config/dev.exs
config :claude_code,
  timeout: 60_000,
  permission_mode: :accept_edits

# config/prod.exs
config :claude_code,
  timeout: :infinity,
  permission_mode: :default

# config/test.exs
config :claude_code,
  api_key: "test-key",
  timeout: 5_000

Environment Variable Merging

Merge precedence (lowest to highest): system env (filtered by :inherit_env) → :env option → SDK-required vars → :api_key.

See Secure Deployment for production lockdown patterns.

Validation Errors

Invalid options raise descriptive errors:

{:ok, session} = ClaudeCode.start_link(timeout: "not a number")
# => ** (NimbleOptions.ValidationError) invalid value for :timeout option:
#       expected positive integer, got: "not a number"

Summary

Functions

Applies application config defaults to session options.

Gets application configuration for claude_code.

Returns the session options schema.

Validates session options using NimbleOptions.

Functions

apply_app_config_defaults(session_opts)

Applies application config defaults to session options.

Session options take precedence over app config.

get_app_config()

Gets application configuration for claude_code.

Returns only valid option keys from the session schema.

session_schema()

Returns the session options schema.

validate_session_options(opts)

Validates session options using NimbleOptions.

The CLI will handle API key resolution from the environment if not provided.

Examples

iex> ClaudeCode.Options.validate_session_options([api_key: "sk-test"])
{:ok, [api_key: "sk-test", timeout: :infinity]}

iex> ClaudeCode.Options.validate_session_options([])
{:ok, [timeout: :infinity]}