### Example Claude Code Settings JSON File Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md An example of a valid JSON file containing Claude Code configuration options, including permissions for tool usage, environment variables, model selection, cleanup periods, and co-authoring settings. ```json { "permissions": { "allow": [ "Bash(npm run lint)", "Bash(npm run test:*)", "Read(~/.zshrc)" ], "deny": [ "Bash(curl:*)" ] }, "env": { "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_METRICS_EXPORTER": "otlp" }, "model": "claude-3-5-sonnet-20241022", "cleanupPeriodDays": 20, "includeCoAuthoredBy": true } ``` -------------------------------- ### Install Dependencies with Bundler Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/spec/README.md Installs the necessary Ruby gem dependencies using Bundler. Assumes you are in the 'ruby_gem' directory. Requires 'bundle' to be installed. ```bash cd ruby_gem bundle install ``` -------------------------------- ### Perform a Basic Query with Claude SDK Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md A straightforward example of initiating a query to the Claude SDK and printing the received message. This is the most basic usage pattern. ```ruby require 'claude_sdk' ClaudeSDK.query("Hello, Claude!") do |message| puts message end ``` -------------------------------- ### Run RSpec Tests with Detailed Documentation Output Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/spec/README.md Executes all RSpec tests and formats the output to display detailed descriptions for each example, similar to documentation. The '--format documentation' flag controls this behavior. ```bash bundle exec rspec --format documentation ``` -------------------------------- ### Install Claude Code CLI Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Command to install the Claude Code CLI globally using npm, which is a prerequisite for using the Ruby SDK. ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Use Claude SDK Internal Client Directly Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Advanced usage example showing how to instantiate and use the `InternalClient` directly from the SDK. It demonstrates making a query asynchronously and handling different message types like Assistant, System, and Result. ```ruby require 'claude_sdk/internal/client' client = ClaudeSDK::Internal::InternalClient.new options = ClaudeSDK::ClaudeCodeOptions.new( allowed_tools: ['Read', 'Bash'], max_turns: 5 ) Async do client.process_query(prompt: "What files are in this directory?", options: options) do |message| case message when ClaudeSDK::Messages::Assistant puts "Assistant response received" when ClaudeSDK::Messages::System puts "System message: #{message.subtype}" when ClaudeSDK::Messages::Result puts "Query completed" end endend ``` -------------------------------- ### Manage Claude SDK Conversations in Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Examples of managing conversation sessions with the Claude SDK in Ruby. Demonstrates starting a new continuous conversation, resuming a previous session using its ID, using a custom session ID, and implementing a multi-step conversation manager class to track session state, cost, and turns. ```ruby require 'claude_sdk' # Scenario 1: Single continuous conversation puts "=== Starting initial conversation ===" first_session_id = nil options = ClaudeSDK::ClaudeCodeOptions.new( allowed_tools: ['Read', 'Write', 'Bash'], max_turns: 5, continue_conversation: true, # Allow conversation to continue cwd: Dir.pwd ) ClaudeSDK.query("Create a Ruby class called Calculator with an add method", options: options) do |message| if message.is_a?(ClaudeSDK::Messages::Result) first_session_id = message.session_id puts "Session ID: #{first_session_id}" puts "Completed in #{message.num_turns} turns" end end # Scenario 2: Resume from specific session puts "\n=== Resuming previous session ===" resume_options = ClaudeSDK::ClaudeCodeOptions.new( resume: first_session_id, # Resume from previous session allowed_tools: ['Read', 'Write', 'Edit'], max_turns: 5, cwd: Dir.pwd ) ClaudeSDK.query("Now add a subtract method to the Calculator class", options: resume_options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| if block.is_a?(ClaudeSDK::ContentBlock::Text) puts block.text elsif block.is_a?(ClaudeSDK::ContentBlock::ToolUse) puts "Tool: #{block.name} (#{block.id})" end end when ClaudeSDK::Messages::Result puts "Resumed session completed" puts "Previous session: #{first_session_id}" puts "Current session: #{message.session_id}" end end # Scenario 3: Custom session ID require 'securerandom' custom_session_id = SecureRandom.uuid puts "\n=== Using custom session ID ===" custom_options = ClaudeSDK::ClaudeCodeOptions.new( session_id: custom_session_id, allowed_tools: ['Read', 'Bash'], max_turns: 3 ) ClaudeSDK.query("List files in current directory", options: custom_options) do |message| if message.is_a?(ClaudeSDK::Messages::Result) puts "Custom session ID used: #{message.session_id}" puts "Matches our UUID: #{message.session_id == custom_session_id}" end end # Scenario 4: Multi-step conversation with context puts "\n=== Multi-step conversation pattern ===" class ConversationManager attr_reader :session_id, :total_cost, :total_turns def initialize(base_options = {}) @base_options = base_options @session_id = nil @total_cost = 0.0 @total_turns = 0 end def query(prompt) options = ClaudeSDK::ClaudeCodeOptions.new( **@base_options, resume: @session_id, continue_conversation: true ) ClaudeSDK.query(prompt, options: options) do |message| yield message if block_given? if message.is_a?(ClaudeSDK::Messages::Result) @session_id = message.session_id @total_cost += message.total_cost_usd.to_f @total_turns += message.num_turns end end end def summary { session_id: @session_id, total_cost: @total_cost, total_turns: @total_turns } end end conversation = ConversationManager.new( allowed_tools: ['Read', 'Write', 'Bash'], permission_mode: :accept_edits, cwd: Dir.pwd ) # Step 1 conversation.query("Create a file called hello.rb with a greeting") do |msg| puts msg if msg.is_a?(ClaudeSDK::Messages::Assistant) end # Step 2 - continues from step 1 conversation.query("Now add a method to that file that says goodbye") do |msg| puts msg if msg.is_a?(ClaudeSDK::Messages::Assistant) end # Step 3 - continues from step 2 conversation.query("Run the file and show me the output") do |msg| puts msg if msg.is_a?(ClaudeSDK::Messages::Assistant) end summary = conversation.summary puts "\nConversation Summary:" puts " Session ID: #{summary[:session_id]}" puts " Total Cost: $#{summary[:total_cost].round(4)}" puts " Total Turns: #{summary[:total_turns]}" ``` -------------------------------- ### Claude SDK: Options with MCP Servers Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Integrates MCP server configurations and MCP tools into `ClaudeCodeOptions`. This example shows how to pass both hash-based or object-based MCP server configurations along with a list of available MCP tools. ```ruby # Assuming mcp_servers_hash is defined as above options = ClaudeSDK::ClaudeCodeOptions.new( mcp_servers: mcp_servers_hash, mcp_tools: [ 'read_file', 'write_file', 'list_directory', 'git_status', 'git_diff', 'git_log', 'query_database', 'fetch_api_data' ], allowed_tools: ['Read', 'Bash'], permission_mode: :accept_edits ) ``` -------------------------------- ### Install Claude Code SDK for Ruby Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Instructions for adding the claude-code-sdk-ruby gem to your application's Gemfile and installing it using Bundler, or installing it directly via the RubyGems package manager. ```ruby gem 'claude-code-sdk-ruby' ``` ```bash bundle install ``` ```bash gem install claude-code-sdk-ruby ``` -------------------------------- ### Configure Claude Code Options (Ruby) Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Provides a comprehensive example of configuring Claude Code behavior using `ClaudeCodeOptions`. Covers tool management (allowed/disallowed), prompts, model settings, conversation control (max turns, continuation, session resumption), permissions, working directory, and MCP server configuration. Shows how to apply these options to a query. ```ruby require 'claude_sdk' # Comprehensive configuration example options = ClaudeSDK::ClaudeCodeOptions.new( # Tool management allowed_tools: ['Read', 'Write', 'Bash', 'Edit', 'Glob', 'Grep'], disallowed_tools: ['WebFetch'], # Explicitly block certain tools # Prompts and model system_prompt: 'You are an expert Ruby developer and code reviewer.', append_system_prompt: 'Always prioritize code quality and best practices.', model: 'claude-3-5-sonnet-20241022', max_thinking_tokens: 10_000, # Conversation control max_turns: 10, # Limit conversation length continue_conversation: false, # Start fresh conversation resume: nil, # Or provide session ID to resume: 'abc-123-def' session_id: nil, # Custom session UUID # Permissions and security permission_mode: :accept_edits, # :default, :accept_edits, or :bypass_permissions permission_prompt_tool_name: nil, # Custom permission handler # Working directory cwd: '/path/to/project', # Can be String or Pathname # MCP (Model Context Protocol) configuration mcp_tools: ['read_file', 'write_file', 'git_status'], mcp_servers: { 'filesystem' => { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], env: {} }, 'git' => { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-git', '--repository', '.'] } }, # Settings file (overrides above options) settings: '/path/to/claude-settings.json' ) # Execute query with options ClaudeSDK.query("Analyze this codebase and suggest improvements", options: options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| puts block.text if block.is_a?(ClaudeSDK::ContentBlock::Text) end when ClaudeSDK::Messages::Result puts "\nTotal cost: $#{message.total_cost_usd}" end end ``` -------------------------------- ### Bash Commands for Ruby Gem Development Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Provides essential Bash commands for developing and testing the Ruby Claude Code SDK gem. Includes commands for running tests, generating coverage reports, building the gem package, and installing it locally. ```bash # Run tests bundle exec rspec # Run tests with coverage COVERAGE=true bundle exec rspec # Build the gem gem build claude-code-sdk-ruby.gemspec # Install locally gem install ./claude-code-sdk-ruby-0.1.0.gem ``` -------------------------------- ### Claude SDK: Bypass Permissions Mode Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Shows the 'bypass_permissions' mode, where all tool uses are approved without any permission checks. It configures allowed tools and initiates a query for environment setup. ```ruby bypass_options = ClaudeSDK::ClaudeCodeOptions.new( permission_mode: :bypass_permissions, allowed_tools: ['Read', 'Write', 'Bash', 'Edit'] ) ClaudeSDK.query("Setup the development environment", options: bypass_options) do |message| # All tools execute without any permission checks end ``` -------------------------------- ### Ruby: Custom CLI Path Configuration for Internal Client Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt This Ruby code snippet illustrates how to use the `InternalClient` with a custom CLI path configuration. While the configuration of the custom path happens internally within the `SubprocessCLI` transport layer, this example shows the initialization and usage of the client, emphasizing that the SDK automatically searches standard locations for the CLI executable if not explicitly provided. ```ruby require 'claude_sdk' require 'async' # Custom CLI path (advanced) custom_client = ClaudeSDK::Internal::InternalClient.new # The SubprocessCLI transport can be configured with custom path # This happens internally in the transport layer Async do # The transport will search these locations in order: # 1. `which claude` # 2. ~/.npm-global/bin/claude # 3. /usr/local/bin/claude # 4. ~/.local/bin/claude # 5. ~/node_modules/.bin/claude # 6. ~/.yarn/bin/claude custom_client.process_query( prompt: "Hello", options: ClaudeSDK::ClaudeCodeOptions.new ) do |message| puts message.inspect end end ``` -------------------------------- ### Access Claude SDK Internal Client in Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt This example demonstrates how to use the internal client of the Claude SDK for advanced use cases. It requires importing specific internal client and types modules, along with the 'async' library for asynchronous operations. This approach is suitable for custom transport implementations or deeper integration needs. ```ruby require 'claude_sdk/internal/client' require 'claude_sdk/types' require 'async' ``` -------------------------------- ### Query Claude SDK with Options Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Shows how to use the Claude SDK with custom options, including specifying allowed tools, maximum turns, a system prompt, and the working directory. It also demonstrates handling Assistant messages with text and tool usage, and Result messages with turn count and cost. ```ruby require 'claude_sdk' options = ClaudeSDK::ClaudeCodeOptions.new( allowed_tools: ['Read', 'Write', 'Bash'], max_turns: 3, system_prompt: 'You are a helpful coding assistant.', cwd: '/path/to/working/directory' ) ClaudeSDK.query("Help me write a Ruby script", options: options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| case block when ClaudeSDK::ContentBlock::Text puts block.text when ClaudeSDK::ContentBlock::ToolUse puts "Tool: #{block.name}" puts "Input: #{block.input}" end end when ClaudeSDK::Messages::Result puts "Completed in #{message.num_turns} turns" puts "Total cost: $#{message.total_cost_usd}" endend ``` -------------------------------- ### Claude SDK: Default Permission Mode Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Demonstrates the default permission mode for Claude SDK queries, where the user is prompted before each tool use. It sets up allowed tools and makes a query. ```ruby default_options = ClaudeSDK::ClaudeCodeOptions.new( permission_mode: ClaudeSDK::PermissionMode::DEFAULT, # or :default allowed_tools: ['Read', 'Write', 'Bash'] ) ClaudeSDK.query("Create a new Ruby file", options: default_options) do |message| # Will prompt user before writing file end ``` -------------------------------- ### Run All RSpec Tests Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/spec/README.md Executes the entire RSpec test suite for the Claude SDK Ruby implementation. This command uses Bundler to ensure all dependencies are met. ```bash bundle exec rspec ``` -------------------------------- ### Claude SDK: Settings File Configuration Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Configures Claude SDK options by loading settings from a JSON file. It shows how to create a temporary settings file with permissions, environment variables, model details, and then load it into `ClaudeCodeOptions`. ```ruby require 'claude_sdk' require 'json' require 'tmpdir' # Create a settings file Dir.mktmpdir do |tmpdir| settings_path = File.join(tmpdir, 'claude-settings.json') settings = { 'permissions' => { 'allow' => [ 'Bash(npm run lint)', 'Bash(npm run test:*)', 'Read(~/.zshrc)', 'Write(src/**/*.rb)' ], 'deny' => [ 'Bash(curl:*)', 'Bash(rm -rf*)' ] }, 'env' => { 'CLAUDE_CODE_ENABLE_TELEMETRY' => '1', 'OTEL_METRICS_EXPORTER' => 'otlp' }, 'model' => 'claude-3-5-sonnet-20241022', 'cleanupPeriodDays' => 20, 'includeCoAuthoredBy' => true } File.write(settings_path, JSON.pretty_generate(settings)) # Load settings in options options = ClaudeSDK::ClaudeCodeOptions.new( settings: settings_path, # Can still override settings file values max_turns: 5, cwd: Dir.pwd ) ClaudeSDK.query("Run tests and analyze results", options: options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| if block.is_a?(ClaudeSDK::ContentBlock::ToolUse) && block.name == 'Bash' puts "Executing: #{block.input['command']}" elsif block.is_a?(ClaudeSDK::ContentBlock::Text) puts block.text end end when ClaudeSDK::Messages::Result puts "Tests completed in #{message.duration_ms}ms" end end end ``` -------------------------------- ### Claude SDK: MCP Server Configuration (Objects) Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Demonstrates configuring MCP servers using dedicated configuration objects like `StdioServer`, `SSEServer`, and `HttpServer`. This provides a more structured way to define server connections. ```ruby mcp_servers_objects = { 'filesystem' => ClaudeSDK::McpServerConfig::StdioServer.new( command: 'custom-mcp-server', args: ['/data', '--verbose'], env: { 'DEBUG' => '1' } ), 'web' => ClaudeSDK::McpServerConfig::SSEServer.new( url: 'http://localhost:9000/events', headers: { 'Accept' => 'text/event-stream' } ), 'rest' => ClaudeSDK::McpServerConfig::HttpServer.new( url: 'https://api.example.com/mcp', headers: { 'Content-Type' => 'application/json' } ) } ``` -------------------------------- ### ClaudeCodeOptions - Configuration Object Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Allows comprehensive configuration of Claude Code's behavior, including tools, permissions, system prompts, and MCP servers. ```APIDOC ## ClaudeCodeOptions - Configuration Object ### Description Configure all aspects of Claude Code behavior including tools, permissions, working directory, system prompts, and MCP servers. ### Method `ClaudeSDK::ClaudeCodeOptions.new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **allowed_tools** (Array) - Optional - List of tools that Claude Code is permitted to use. - **disallowed_tools** (Array) - Optional - List of tools that Claude Code is explicitly blocked from using. - **system_prompt** (String) - Optional - The initial system prompt to guide Claude's behavior. - **append_system_prompt** (String) - Optional - Additional text to append to the system prompt. - **model** (String) - Optional - The specific Claude model to use (e.g., 'claude-3-5-sonnet-20241022'). - **max_thinking_tokens** (Integer) - Optional - Maximum number of tokens Claude can use for thinking. - **max_turns** (Integer) - Optional - Limits the maximum number of turns in a conversation. - **continue_conversation** (Boolean) - Optional - If true, resumes a previous conversation; if false, starts a new one. - **resume** (String) - Optional - A session ID to resume a specific conversation. - **session_id** (String) - Optional - A custom UUID for the current session. - **permission_mode** (Symbol) - Optional - Controls tool permission handling. Options: `:default`, `:accept_edits`, or `:bypass_permissions`. - **permission_prompt_tool_name** (String) - Optional - Custom handler for permission prompts. - **cwd** (String or Pathname) - Optional - The working directory for file operations. - **mcp_tools** (Array) - Optional - List of tools available through MCP servers. - **mcp_servers** (Hash) - Optional - Configuration for MCP servers, including type, command, arguments, and environment variables. - **settings** (String) - Optional - Path to a JSON file containing settings that override other options. ### Request Example ```ruby require 'claude_sdk' # Comprehensive configuration example options = ClaudeSDK::ClaudeCodeOptions.new( # Tool management allowed_tools: ['Read', 'Write', 'Bash', 'Edit', 'Glob', 'Grep'], disallowed_tools: ['WebFetch'], # Explicitly block certain tools # Prompts and model system_prompt: 'You are an expert Ruby developer and code reviewer.', append_system_prompt: 'Always prioritize code quality and best practices.', model: 'claude-3-5-sonnet-20241022', max_thinking_tokens: 10_000, # Conversation control max_turns: 10, # Limit conversation length continue_conversation: false, # Start fresh conversation resume: nil, # Or provide session ID to resume: 'abc-123-def' session_id: nil, # Custom session UUID # Permissions and security permission_mode: :accept_edits, # :default, :accept_edits, or :bypass_permissions permission_prompt_tool_name: nil, # Custom permission handler # Working directory cwd: '/path/to/project', # Can be String or Pathname # MCP (Model Context Protocol) configuration mcp_tools: ['read_file', 'write_file', 'git_status'], mcp_servers: { 'filesystem' => { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], env: {} }, 'git' => { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-git', '--repository', '.'] } }, # Settings file (overrides above options) settings: '/path/to/claude-settings.json' ) # Execute query with options ClaudeSDK.query("Analyze this codebase and suggest improvements", options: options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| puts block.text if block.is_a?(ClaudeSDK::ContentBlock::Text) end when ClaudeSDK::Messages::Result puts "\nTotal cost: $#{message.total_cost_usd}" end end ``` ### Response #### Success Response (200) - **ClaudeCodeOptions object** - An instance of `ClaudeSDK::ClaudeCodeOptions` configured with the provided settings. #### Response Example ```json { "allowed_tools": ["Read", "Write", "Bash"], "system_prompt": "You are a helpful assistant.", "model": "claude-3-opus-20240229" } ``` ``` -------------------------------- ### Perform a Simple Query with Claude SDK Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Demonstrates a basic query to the Claude SDK, showing how to process assistant messages and result messages, including extracting text content and session duration. ```ruby require 'claude_sdk' # Simple query ClaudeSDK.query("What is 2+2?") do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| puts block.text if block.is_a?(ClaudeSDK::ContentBlock::Text) end when ClaudeSDK::Messages::Result puts "Session completed in #{message.duration_ms}ms" end end ``` -------------------------------- ### Execute Claude Query with Block Processing (Ruby) Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Demonstrates how to execute a basic query to Claude Code using a block, processing messages synchronously as they arrive. Handles different message types like User, Assistant, System, and Result, including text and tool use content blocks. Shows how to access result details like duration, turns, cost, and session ID. ```ruby require 'claude_sdk' # Basic query with block - processes messages synchronously ClaudeSDK.query("What is 2+2?") do |message| case message when ClaudeSDK::Messages::User puts "User: #{message.content}" when ClaudeSDK::Messages::Assistant message.content.each do |block| case block when ClaudeSDK::ContentBlock::Text puts "Claude: #{block.text}" when ClaudeSDK::ContentBlock::ToolUse puts "Using tool: #{block.name}" puts "Parameters: #{block.input.inspect}" end end when ClaudeSDK::Messages::System puts "System (#{message.subtype}): #{message.data}" when ClaudeSDK::Messages::Result puts "\nCompleted in #{message.duration_ms}ms" puts "API time: #{message.duration_api_ms}ms" puts "Turns: #{message.num_turns}" puts "Cost: $#{message.total_cost_usd}" if message.total_cost_usd puts "Session ID: #{message.session_id}" end end # Without block - returns Enumerator for lazy processing messages = ClaudeSDK.query("Generate a Ruby haiku") messages.each do |msg| if msg.is_a?(ClaudeSDK::Messages::Assistant) msg.content.each { |b| puts b.text if b.is_a?(ClaudeSDK::ContentBlock::Text) } end end ``` -------------------------------- ### Configure Claude SDK with Settings File Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Demonstrates loading Claude Code configuration options from a JSON settings file using `ClaudeSDK::ClaudeCodeOptions`. It shows how to specify the settings file path and override or supplement options like the model name. ```ruby require 'claude_sdk' # Create options with a settings file path options = ClaudeSDK::ClaudeCodeOptions.new( settings: '/path/to/claude-settings.json', model: 'sonnet' # Other options can still be specified ) ClaudeSDK.query("Hello", options: options) do |message| puts message end ``` -------------------------------- ### Run RSpec Tests with Coverage Report Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/spec/README.md Runs all RSpec tests and generates an HTML coverage report using SimpleCov. The report can be viewed by opening the 'coverage/index.html' file in a web browser. ```bash bundle exec rspec open coverage/index.html ``` -------------------------------- ### Ruby Error Handling for Claude SDK Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/README.md Demonstrates how to handle specific exceptions raised by the Claude SDK during the query process. It catches errors like CLI not found, connection issues, and general process errors, providing user-friendly messages. ```ruby begin ClaudeSDK.query("Hello") do |message| puts message end rescue ClaudeSDK::CLINotFoundError => e puts "Claude Code CLI not found: #{e.message}" rescue ClaudeSDK::CLIConnectionError => e puts "Connection error: #{e.message}" rescue ClaudeSDK::ProcessError => e puts "Process error: #{e.message}" end ``` -------------------------------- ### Ruby: Direct Internal Client Usage with Async Processing and Message Handling Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt This Ruby code snippet demonstrates initializing an `InternalClient` from the Claude SDK, configuring `ClaudeCodeOptions` for tool usage, `max_turns`, `system_prompt`, `model`, `cwd`, and `permission_mode`. It then uses an asynchronous block to process a query, handling different message types (User, Assistant, System, Result) and specific content blocks (Text, ToolUse, ToolResult). Includes robust error handling for `CLINotFoundError`, `ProcessError`, and general `Error` exceptions. ```ruby require 'claude_sdk' require 'async' # Direct internal client usage client = ClaudeSDK::Internal::InternalClient.new options = ClaudeSDK::ClaudeCodeOptions.new( allowed_tools: ['Read', 'Bash', 'Grep'], max_turns: 5, system_prompt: 'You are a helpful assistant', model: 'claude-3-5-sonnet-20241022', cwd: Dir.pwd, permission_mode: :accept_edits ) Async do puts "Querying via internal client..." begin client.process_query( prompt: "Search for TODO comments in Ruby files", options: options ) do |message| case message when ClaudeSDK::Messages::User puts "\n[USER]" puts message.content when ClaudeSDK::Messages::Assistant puts "\n[ASSISTANT]" message.content.each do |block| case block when ClaudeSDK::ContentBlock::Text puts "Text: #{block.text}" when ClaudeSDK::ContentBlock::ToolUse puts "Tool: #{block.name} (ID: #{block.id})" puts "Input: #{block.input.inspect}" when ClaudeSDK::ContentBlock::ToolResult puts "Tool Result (#{block.tool_use_id})" puts "Content: #{block.content}" puts "Error: #{block.is_error}" end end when ClaudeSDK::Messages::System puts "\n[SYSTEM]" puts "Subtype: #{message.subtype}" puts "Data: #{message.data}" when ClaudeSDK::Messages::Result puts "\n[RESULT]" puts "Session ID: #{message.session_id}" puts "Duration: #{message.duration_ms}ms" puts "API Duration: #{message.duration_api_ms}ms" puts "Turns: #{message.num_turns}" puts "Cost: $#{message.total_cost_usd}" if message.total_cost_usd puts "Error: #{message.is_error}" end end rescue ClaudeSDK::CLINotFoundError => e puts "CLI not found: #{e.message}" rescue ClaudeSDK::ProcessError => e puts "Process error (#{e.exit_code}): #{e.stderr}" rescue ClaudeSDK::Error => e puts "SDK error: #{e.message}" end end ``` -------------------------------- ### Claude SDK: MCP Server Configuration (Hash) Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Configures Model Context Protocol (MCP) servers using a hash-based approach. It defines different server types like 'stdio', 'sse', and 'http' with their respective commands, arguments, URLs, and headers. ```ruby mcp_servers_hash = { 'filesystem' => { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], env: { 'LOG_LEVEL' => 'debug' } }, 'git' => { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-git', '--repository', '.'], env: {} }, 'database' => { type: 'sse', url: 'http://localhost:8080/sse', headers: { 'Authorization' => 'Bearer token123' } }, 'api' => { type: 'http', url: 'https://api.example.com/mcp', headers: { 'X-API-Key' => 'secret' } } } ``` -------------------------------- ### Execute MCP Query with Claude SDK Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt This snippet demonstrates how to execute a query using the Claude SDK in Ruby, specifically handling messages with MCP (Microsoft Cloud Platform) tool usage. It processes assistant messages, identifies MCP tool calls by their naming convention, and prints server, tool, and input details. It also handles text responses and completion messages. ```ruby ClaudeSDK.query("Read README.md from /tmp, check git status, and summarize", options: options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| case block when ClaudeSDK::ContentBlock::ToolUse if block.name.start_with?('mcp_') # MCP tools are prefixed with 'mcp__' server = block.name.split('_')[1] tool = block.name.split('_')[2..-1].join('_') puts "MCP Call - Server: #{server}, Tool: #{tool}" puts "Input: #{block.input.inspect}" end when ClaudeSDK::ContentBlock::Text puts "Response: #{block.text}" end end when ClaudeSDK::Messages::Result puts "\nMCP query completed in #{message.duration_ms}ms" end end ``` -------------------------------- ### Run Specific RSpec Test File Source: https://github.com/parruda/claude-code-sdk-ruby/blob/main/spec/README.md Executes RSpec tests from a single specified file. Useful for targeted testing during development. Replace the path with the desired test file. ```bash bundle exec rspec spec/claude_sdk/client_spec.rb ``` -------------------------------- ### Permission Modes - Security Configuration Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Details the three distinct permission modes available for controlling how Claude Code handles tool usage and permissions. ```APIDOC ## Permission Modes - Security Configuration ### Description Control how Claude Code handles tool permissions with three distinct modes. ### Modes 1. **`:default`**: The default behavior. Claude Code will prompt the user for permission before executing any tool that requires it. 2. **`:accept_edits`**: Claude Code will automatically accept edits proposed by tools without explicit user confirmation. Other tool permissions still require user approval. 3. **`:bypass_permissions`**: Claude Code will execute all tools without requesting any permissions. Use with extreme caution as this bypasses all security checks. ### Usage These modes are configured using the `permission_mode` option when initializing `ClaudeSDK::ClaudeCodeOptions`. ### Request Example ```ruby require 'claude_sdk' # Example using :accept_edits mode options = ClaudeSDK::ClaudeCodeOptions.new( permission_mode: :accept_edits, system_prompt: 'You are a code editor.' ) ClaudeSDK.query("Refactor this code: ...", options: options) # Example using :bypass_permissions mode (use with caution) options_bypass = ClaudeSDK::ClaudeCodeOptions.new( permission_mode: :bypass_permissions, system_prompt: 'You have full access to the file system.' ) ClaudeSDK.query("Clean up all log files.", options: options_bypass) ``` ### Response #### Success Response (200) Tool execution will proceed according to the specified `permission_mode`. #### Response Example No direct response is generated by setting the mode; it affects the behavior of subsequent tool executions. ``` -------------------------------- ### Claude SDK: Accept Edits Permission Mode Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Illustrates the 'accept_edits' permission mode, which automatically approves file modifications without user prompting. It defines allowed tools and executes a query for refactoring. ```ruby auto_edit_options = ClaudeSDK::ClaudeCodeOptions.new( permission_mode: :accept_edits, allowed_tools: ['Read', 'Write', 'Edit'] ) ClaudeSDK.query("Refactor all Ruby files in lib/", options: auto_edit_options) do |message| # File modifications happen automatically without prompting end ``` -------------------------------- ### Concurrent Claude Queries using Async in Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Executes multiple Claude queries concurrently using Ruby's async capabilities. It maps prompts to asynchronous tasks, waits for all tasks to complete, and then displays the results including response text, cost, and duration. Dependencies include the 'claude_sdk' gem and the 'async' library. ```ruby Async do |task| queries = [ "What is the capital of France?", "Explain Ruby blocks in one sentence", "List 3 benefits of async programming" ] # Launch all queries concurrently results = queries.map do |prompt| task.async do responses = [] start_time = Time.now ClaudeSDK.query(prompt) do |message| if message.is_a?(ClaudeSDK::Messages::Assistant) message.content.each do |block| responses << block.text if block.is_a?(ClaudeSDK::ContentBlock::Text) end elsif message.is_a?(ClaudeSDK::Messages::Result) responses << { cost: message.total_cost_usd, duration: message.duration_ms, elapsed: ((Time.now - start_time) * 1000).round } end end { prompt: prompt, response: responses[0..-2].join(" "), metrics: responses.last } end end.map(&:wait) # Wait for all to complete # Display results puts "\n=== Concurrent Query Results ===" results.each_with_index do |result, i| puts "\nQuery #{i + 1}: #{result[:prompt]}" puts "Answer: #{result[:response]}" puts "Duration: #{result[:metrics][:duration]}ms (wall: #{result[:metrics][:elapsed]}ms)" puts "Cost: $#{result[:metrics][:cost]}" end total_cost = results.sum { |r| r[:metrics][:cost] || 0 } total_duration = results.sum { |r| r[:metrics][:duration] || 0 } puts "\nTotal cost: $#{total_cost.round(4)}" puts "Total API duration: #{total_duration}ms" end ``` -------------------------------- ### Robust Error Handling for Claude SDK in Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Provides a robust error handling mechanism for the Claude SDK in Ruby, catching specific exceptions like `CLINotFoundError`, `CLIConnectionError`, `ProcessError`, and `CLIJSONDecodeError`, as well as general `ClaudeSDK::Error` and `StandardError`. This ensures graceful failure and provides informative messages to the user. Dependencies include the 'claude_sdk' gem. ```ruby require 'claude_sdk' def safe_claude_query(prompt, options = nil) begin ClaudeSDK.query(prompt, options: options) do |message| case message when ClaudeSDK::Messages::Assistant message.content.each do |block| puts block.text if block.is_a?(ClaudeSDK::ContentBlock::Text) end when ClaudeSDK::Messages::Result if message.is_error puts "Query failed (error flag set)" else puts "Query succeeded in #{message.duration_ms}ms" end end end rescue ClaudeSDK::CLINotFoundError => e # Claude CLI executable not found in PATH puts "❌ Claude CLI not installed or not in PATH" puts "Error: #{e.message}" puts "CLI Path searched: #{e.cli_path}" if e.respond_to?(:cli_path) puts "\nInstallation instructions:" puts " npm install -g @anthropic-ai/claude-code" puts "\nOr specify custom path:" puts " ClaudeSDK::Internal::InternalClient.new(cli_path: '/custom/path/to/claude')" rescue ClaudeSDK::CLIConnectionError => e # Connection to CLI failed (not CLINotFoundError) puts "❌ Failed to connect to Claude CLI" puts "Error: #{e.message}" puts "\nPossible causes:" puts " - Claude CLI is not responding" puts " - Permission issues" puts " - API key not configured" rescue ClaudeSDK::ProcessError => e # CLI process exited with error puts "❌ Claude CLI process failed" puts "Exit code: #{e.exit_code}" puts "Error output (stderr):" puts e.stderr puts "\nDebug information:" puts " Check your API key configuration" puts " Verify Claude CLI version: claude --version" rescue ClaudeSDK::CLIJSONDecodeError => e # Failed to parse JSON output from CLI puts "❌ Failed to parse CLI output" puts "Error: #{e.message}" puts "Problematic line: #{e.line}" if e.respond_to?(:line) puts "Original error: #{e.original_error}" if e.respond_to?(:original_error) puts "\nThis may indicate:" puts " - Corrupted CLI output" puts " - Version mismatch between SDK and CLI" puts " - Buffer overflow (line too long)" rescue ClaudeSDK::Error => e # Base error class - catches any other SDK errors puts "❌ SDK error occurred" puts "Error: #{e.class.name}" puts "Message: #{e.message}" rescue StandardError => e # Unexpected errors puts "❌ Unexpected error" puts "#{e.class}: #{e.message}" puts "\nBacktrace:" puts e.backtrace.first(5).join("\n") end end # Usage examples safe_claude_query("Hello, Claude!") options = ClaudeSDK::ClaudeCodeOptions.new( allowed_tools: ['Read', 'Write'], permission_mode: :accept_edits, max_turns: 3 ) safe_claude_query("Create a Ruby script", options) ``` -------------------------------- ### Execute Async Claude Queries Concurrently in Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt This Ruby snippet demonstrates how to perform asynchronous Claude queries using the 'async' gem. It shows a basic pattern for initiating a single async query and processing its assistant response, focusing on extracting text content blocks. This pattern is useful for high-performance applications requiring concurrent AI operations. ```ruby require 'claude_sdk' require 'async' # Pattern 1: Single async query Async do ClaudeSDK.query("What is Ruby?") do |message| if message.is_a?(ClaudeSDK::Messages::Assistant) message.content.each do |block| puts block.text if block.is_a?(ClaudeSDK::ContentBlock::Text) end end end end ``` -------------------------------- ### Handle Claude SDK Message Types in Ruby Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt This Ruby code snippet illustrates how to handle different message types returned by the Claude SDK during a conversation. It includes detailed processing for User, Assistant (with Text, ToolUse, ToolResult blocks), System, Result, and Error messages, showing how to extract relevant information and status from each. ```ruby require 'claude_sdk' options = ClaudeSDK::ClaudeCodeOptions.new( allowed_tools: ['Read', 'Write', 'Bash'], max_turns: 5, permission_mode: :accept_edits ) ClaudeSDK.query("Create a fibonacci function and test it", options: options) do |message| case message # User messages - initial prompt or follow-ups when ClaudeSDK::Messages::User puts "\n[USER MESSAGE]" puts "Content: #{message.content}" puts "Type: #{message.class}" # Assistant messages - Claude's responses with content blocks when ClaudeSDK::Messages::Assistant puts "\n[ASSISTANT MESSAGE]" message.content.each do |block| case block when ClaudeSDK::ContentBlock::Text puts "Text: #{block.text}" puts "Serialized: #{block.to_h.inspect}" when ClaudeSDK::ContentBlock::ToolUse puts "Tool Use ID: #{block.id}" puts "Tool Name: #{block.name}" puts "Tool Input: #{block.input.inspect}" puts "Serialized: #{block.to_h.inspect}" when ClaudeSDK::ContentBlock::ToolResult puts "Tool Result ID: #{block.tool_use_id}" puts "Content: #{block.content}" puts "Is Error: #{block.is_error}" puts "Serialized: #{block.to_h.inspect}" end end # System messages - internal notifications when ClaudeSDK::Messages::System puts "\n[SYSTEM MESSAGE]" puts "Subtype: #{message.subtype}" puts "Data: #{message.data.inspect}" # Example subtypes: 'tool_result', 'permission_notification' # Result messages - final completion with metrics when ClaudeSDK::Messages::Result puts "\n[RESULT MESSAGE]" puts "Session ID: #{message.session_id}" puts "Subtype: #{message.subtype}" puts "Duration (total): #{message.duration_ms}ms" puts "Duration (API): #{message.duration_api_ms}ms" puts "Number of turns: #{message.num_turns}" puts "Is error: #{message.is_error}" puts "Total cost: $#{message.total_cost_usd}" if message.total_cost_usd # Optional fields if message.usage puts "Usage: #{message.usage.inspect}" # Contains input_tokens, output_tokens, etc. end if message.result puts "Result content: #{message.result}" end puts "Serialized: #{message.to_h.inspect}" # Error messages (if CLI returns errors) when ClaudeSDK::Messages::Error puts "\n[ERROR MESSAGE]" puts "Error: #{message.inspect}" end end ``` -------------------------------- ### Claude SDK: Validate Permission Mode Source: https://context7.com/parruda/claude-code-sdk-ruby/llms.txt Demonstrates how to validate if a given permission mode is recognized by the Claude SDK. It uses the `valid?` method on the `PermissionMode` class. ```ruby if ClaudeSDK::PermissionMode.valid?(:accept_edits) puts "Valid permission mode" end ```