ClaudeCode.Options (ClaudeCode v0.16.0)

View Source

Handles option validation and CLI flag conversion.

This module is the single source of truth for all ClaudeCode options. It provides validation for session and query options using NimbleOptions, converts Elixir options to CLI flags, and manages option precedence: query > session > app config > environment variables > defaults.

Session Options

Session options are used when starting a ClaudeCode session. Most options can be overridden at the query level.

API Key

  • :api_key - Anthropic API key (string, optional - falls back to ANTHROPIC_API_KEY env var)

Claude Configuration

  • :model - Claude model to use (string, optional - CLI uses its default)
  • :fallback_model - Fallback model if primary fails (string, optional)
  • :system_prompt - Override system prompt (string, optional)
  • :append_system_prompt - Append to system prompt (string, optional)
  • :max_turns - Limit agentic turns in non-interactive mode (integer, optional)
  • :max_budget_usd - Maximum dollar amount to spend on API calls (number, optional)
  • :agent - Agent name for the session (string, optional) Overrides the 'agent' setting. Different from :agents which defines custom agents.
  • :betas - Beta headers to include in API requests (list of strings, optional) Example: ["feature-x", "feature-y"]

Tool Control

  • :tools - Specify the list of available tools from the built-in set (optional) Use :default for all tools, [] to disable all, or a list of tool names. Example: tools: :default or tools: ["Bash", "Edit", "Read"]
  • :allowed_tools - List of allowed tools (list of strings, optional) Example: ["View", "Bash(git:*)"]
  • :disallowed_tools - List of denied tools (list of strings, optional)
  • :add_dir - Additional directories for tool access (list of strings, optional) Example: ["/tmp", "/var/log"]

Advanced Options

  • :agents - Custom agent definitions (map, optional) Map of agent name to agent configuration. Each agent must have description and prompt. Example: %{"code-reviewer" => %{"description" => "Reviews code", "prompt" => "You are a code reviewer", "tools" => ["Read", "Edit"], "model" => "sonnet"}}
  • :mcp_config - Path to MCP servers JSON config file (string, optional)
  • :mcp_servers - MCP server configurations as a map (map, optional) Values can be a Hermes MCP module (atom), a module map with custom env, or a command config map. Example: %{"my-tools" => MyApp.MCPServer, "custom" => %{module: MyApp.MCPServer, env: %{"DEBUG" => "1"}}, "playwright" => %{command: "npx", args: ["@playwright/mcp@latest"]}}
  • :strict_mcp_config - Only use MCP servers from mcp_config/mcp_servers (boolean, default: false) When true, ignores all global MCP configurations and only uses explicitly provided MCP config.
  • :permission_prompt_tool - MCP tool for handling permission prompts (string, optional)
  • :permission_mode - Permission handling mode (atom, default: :default) Options: :default, :accept_edits, :bypass_permissions, :delegate, :dont_ask, :plan
  • :json_schema - JSON Schema for structured output validation (string or map, optional) When provided as a map, it will be JSON encoded automatically. Example: %{"type" => "object", "properties" => %{"name" => %{"type" => "string"}}, "required" => ["name"]}
  • :settings - Settings configuration (string or map, optional) Can be a file path, JSON string, or map that will be JSON encoded Example: %{"feature" => true} or "/path/to/settings.json"
  • :setting_sources - List of setting sources to load (list of strings, optional) Valid sources: "user", "project", "local" Example: ["user", "project", "local"]

Elixir-Specific Options

  • :name - GenServer process name (atom, optional)
  • :timeout - Query timeout in milliseconds (timeout, default: 300_000) - Elixir only, not passed to CLI
  • :resume - Session ID to resume a previous conversation (string, optional)
  • :fork_session - When resuming, create a new session ID instead of reusing the original (boolean, optional) Must be used with :resume. Creates a fork of the conversation.
  • :tool_callback - Post-execution callback for tool monitoring (function, optional) Receives a map with :name, :input, :result, :is_error, :tool_use_id, :timestamp
  • :cwd - Current working directory (string, optional)
  • :env - Environment variables to merge with system environment (map of string to string, default: %{}) User-provided env vars override system vars but are overridden by SDK vars and :api_key. Example: %{"MY_VAR" => "value", "PATH" => "/custom/bin:" <> System.get_env("PATH")}

Query Options

Query options can override session defaults for individual queries. All session options except :api_key and :name can be used as query options.

Option Precedence

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

  1. Query-level options
  2. Session-level options
  3. Application configuration
  4. Environment variables (ANTHROPIC_API_KEY for api_key)
  5. Schema defaults

Usage Examples

# Session with comprehensive options
{:ok, session} = ClaudeCode.start_link(
  api_key: "sk-ant-...",
  model: "opus",
  fallback_model: "sonnet",
  system_prompt: "You are an Elixir expert",
  allowed_tools: ["View", "Edit", "Bash(git:*)"],
  add_dir: ["/tmp", "/var/log"],
  max_turns: 20,
  timeout: 180_000,
  permission_mode: :default
)

# Query with option overrides
ClaudeCode.query(session, "Help with testing",
  system_prompt: "Focus on ExUnit patterns",
  allowed_tools: ["View"],
  timeout: 60_000
)

# Application configuration
# config/config.exs
config :claude_code,
  model: "sonnet",
  timeout: 120_000,
  allowed_tools: ["View", "Edit"]

# Session with MCP servers configured inline
{:ok, session} = ClaudeCode.start_link(
  mcp_servers: %{
    # Hermes MCP server module - auto-generates stdio config
    "my-tools" => MyApp.MCPServer,
    # Hermes module with custom environment variables
    "my-tools-debug" => %{module: MyApp.MCPServer, env: %{"DEBUG" => "1"}},
    # Explicit command config for external MCP servers
    "playwright" => %{command: "npx", args: ["@playwright/mcp@latest"]}
  }
)

Security Considerations

  • :permission_mode: Controls permission handling behavior. Use :bypass_permissions only in development environments.
  • :add_dir: Grants tool access to additional directories. Only include safe directories.
  • :allowed_tools: Use tool restrictions to limit Claude's capabilities. Example: ["View", "Bash(git:*)"] allows read-only operations and git commands.

Summary

Functions

Applies application config defaults to session options.

Gets application configuration for claude_code.

Merges session and query options with query taking precedence.

Returns the query options schema.

Returns the session options schema.

Converts Elixir options to CLI arguments.

Validates query options using NimbleOptions.

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.

merge_options(session_opts, query_opts)

Merges session and query options with query taking precedence.

Examples

iex> session_opts = [timeout: 60_000, model: "sonnet"]
iex> query_opts = [timeout: 120_000]
iex> ClaudeCode.Options.merge_options(session_opts, query_opts)
[model: "sonnet", timeout: 120_000]

query_schema()

Returns the query options schema.

session_schema()

Returns the session options schema.

to_cli_args(opts)

Converts Elixir options to CLI arguments.

Ignores internal options like :api_key, :name, and :timeout that are not CLI flags.

Examples

iex> ClaudeCode.Options.to_cli_args([system_prompt: "You are helpful"])
["--system-prompt", "You are helpful"]

iex> ClaudeCode.Options.to_cli_args([allowed_tools: ["View", "Bash(git:*)"]])
["--allowedTools", "View,Bash(git:*)"]

validate_query_options(opts)

Validates query options using NimbleOptions.

Examples

iex> ClaudeCode.Options.validate_query_options([timeout: 60_000])
{:ok, [timeout: 60_000]}

iex> ClaudeCode.Options.validate_query_options([invalid: "option"])
{:error, %NimbleOptions.ValidationError{}}

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: 300_000]}

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