Module: ClaudeAgentSDK

Defined in:
lib/claude_agent_sdk.rb,
lib/claude_agent_sdk/query.rb,
lib/claude_agent_sdk/types.rb,
lib/claude_agent_sdk/errors.rb,
lib/claude_agent_sdk/version.rb,
lib/claude_agent_sdk/streaming.rb,
lib/claude_agent_sdk/transport.rb,
lib/claude_agent_sdk/configuration.rb,
lib/claude_agent_sdk/message_parser.rb,
lib/claude_agent_sdk/sdk_mcp_server.rb,
lib/claude_agent_sdk/subprocess_cli_transport.rb

Overview

Claude Agent SDK for Ruby

Defined Under Namespace

Modules: Streaming Classes: AgentDefinition, AssistantMessage, AsyncHookJSONOutput, BaseHookInput, CLIConnectionError, CLIJSONDecodeError, CLINotFoundError, ClaudeAgentOptions, ClaudeSDKError, Client, Configuration, ControlRequestTimeoutError, HookContext, HookMatcher, McpHttpServerConfig, McpSSEServerConfig, McpSdkServerConfig, McpStdioServerConfig, MessageParseError, MessageParser, NotificationHookInput, NotificationHookSpecificOutput, PermissionRequestHookInput, PermissionRequestHookSpecificOutput, PermissionResultAllow, PermissionResultDeny, PermissionRuleValue, PermissionUpdate, PostToolUseFailureHookInput, PostToolUseFailureHookSpecificOutput, PostToolUseHookInput, PostToolUseHookSpecificOutput, PreCompactHookInput, PreToolUseHookInput, PreToolUseHookSpecificOutput, ProcessError, Query, ResultMessage, SandboxIgnoreViolations, SandboxNetworkConfig, SandboxSettings, SdkMcpPrompt, SdkMcpResource, SdkMcpServer, SdkMcpTool, SdkPluginConfig, SessionStartHookSpecificOutput, StopHookInput, StreamEvent, SubagentStartHookInput, SubagentStartHookSpecificOutput, SubagentStopHookInput, SubprocessCLITransport, SyncHookJSONOutput, SystemMessage, SystemPromptPreset, TextBlock, ThinkingBlock, ToolPermissionContext, ToolResultBlock, ToolUseBlock, ToolsPreset, Transport, UserMessage, UserPromptSubmitHookInput, UserPromptSubmitHookSpecificOutput

Constant Summary collapse

PERMISSION_MODES =

Type constants for permission modes

%w[default acceptEdits plan bypassPermissions].freeze
SETTING_SOURCES =

Type constants for setting sources

%w[user project local].freeze
PERMISSION_UPDATE_DESTINATIONS =

Type constants for permission update destinations

%w[userSettings projectSettings localSettings session].freeze
PERMISSION_BEHAVIORS =

Type constants for permission behaviors

%w[allow deny ask].freeze
HOOK_EVENTS =

Type constants for hook events

%w[
  PreToolUse
  PostToolUse
  PostToolUseFailure
  UserPromptSubmit
  Stop
  SubagentStop
  PreCompact
  Notification
  SubagentStart
  PermissionRequest
].freeze
ASSISTANT_MESSAGE_ERRORS =

Type constants for assistant message errors

%w[authentication_failed billing_error rate_limit invalid_request server_error unknown].freeze
SDK_BETAS =

Type constants for SDK beta features Available beta features that can be enabled via the betas option

%w[context-1m-2025-08-07].freeze
VERSION =
'0.6.1'

Class Method Summary collapse

Class Method Details

.configurationConfiguration

Get the configuration object

Returns:



58
59
60
# File 'lib/claude_agent_sdk/configuration.rb', line 58

def configuration
  @configuration ||= Configuration.new
end

.configure {|Configuration| ... } ⇒ Object

Configure the SDK with default options

Examples:

Set default env and other options

ClaudeAgentSDK.configure do |config|
  config.default_options = {
    env: { 'API_KEY' => 'xxx' },
    permission_mode: 'bypassPermissions'
  }
end

Yields:



51
52
53
# File 'lib/claude_agent_sdk/configuration.rb', line 51

def configure
  yield(configuration)
end

.create_prompt(name:, description: nil, arguments: nil, &generator) ⇒ SdkMcpPrompt

Helper function to create a prompt definition

Examples:

Simple prompt

prompt = create_prompt(
  name: 'code_review',
  description: 'Review code for best practices'
) do |args|
  {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: 'Please review this code for best practices and suggest improvements.'
        }
      }
    ]
  }
end

Prompt with arguments

prompt = create_prompt(
  name: 'git_commit',
  description: 'Generate a git commit message',
  arguments: [
    { name: 'changes', description: 'Description of changes', required: true }
  ]
) do |args|
  {
    messages: [
      {
        role: 'user',
        content: {
          type: 'text',
          text: "Generate a concise git commit message for: #{args[:changes]}"
        }
      }
    ]
  }
end

Parameters:

  • name (String)

    Unique identifier for the prompt

  • description (String, nil) (defaults to: nil)

    Optional description

  • arguments (Array<Hash>, nil) (defaults to: nil)

    Optional argument definitions

  • generator (Proc)

    Block that generates prompt messages

Returns:

Raises:

  • (ArgumentError)


500
501
502
503
504
505
506
507
508
509
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 500

def self.create_prompt(name:, description: nil, arguments: nil, &generator)
  raise ArgumentError, 'Block required for prompt generator' unless generator

  SdkMcpPrompt.new(
    name: name,
    description: description,
    arguments: arguments,
    generator: generator
  )
end

.create_resource(uri:, name:, description: nil, mime_type: nil, &reader) ⇒ SdkMcpResource

Helper function to create a resource definition

Examples:

File resource

resource = create_resource(
  uri: 'file:///config/settings.json',
  name: 'Application Settings',
  description: 'Current application configuration',
  mime_type: 'application/json'
) do
  content = File.read('/path/to/settings.json')
  {
    contents: [{
      uri: 'file:///config/settings.json',
      mimeType: 'application/json',
      text: content
    }]
  }
end

Database resource

resource = create_resource(
  uri: 'db://users/count',
  name: 'User Count',
  description: 'Total number of registered users'
) do
  count = User.count
  {
    contents: [{
      uri: 'db://users/count',
      mimeType: 'text/plain',
      text: count.to_s
    }]
  }
end

Parameters:

  • uri (String)

    Unique identifier for the resource (e.g., “file:///path/to/file”)

  • name (String)

    Human-readable name

  • description (String, nil) (defaults to: nil)

    Optional description

  • mime_type (String, nil) (defaults to: nil)

    Optional MIME type (e.g., “text/plain”, “application/json”)

  • reader (Proc)

    Block that returns the resource content

Returns:

Raises:

  • (ArgumentError)


442
443
444
445
446
447
448
449
450
451
452
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 442

def self.create_resource(uri:, name:, description: nil, mime_type: nil, &reader)
  raise ArgumentError, 'Block required for resource reader' unless reader

  SdkMcpResource.new(
    uri: uri,
    name: name,
    description: description,
    mime_type: mime_type,
    reader: reader
  )
end

.create_sdk_mcp_server(name:, version: '1.0.0', tools: [], resources: [], prompts: []) ⇒ Hash

Create an SDK MCP server

Examples:

Simple calculator server

add_tool = ClaudeAgentSDK.create_tool('add', 'Add numbers', { a: :number, b: :number }) do |args|
  { content: [{ type: 'text', text: "Sum: #{args[:a] + args[:b]}" }] }
end

calculator = ClaudeAgentSDK.create_sdk_mcp_server(
  name: 'calculator',
  version: '2.0.0',
  tools: [add_tool]
)

options = ClaudeAgentOptions.new(
  mcp_servers: { calc: calculator },
  allowed_tools: ['mcp__calc__add']
)

Server with resources and prompts

config_resource = ClaudeAgentSDK.create_resource(
  uri: 'config://app',
  name: 'App Config'
) { { contents: [{ uri: 'config://app', text: 'config data' }] } }

review_prompt = ClaudeAgentSDK.create_prompt(
  name: 'review',
  description: 'Code review'
) { { messages: [{ role: 'user', content: { type: 'text', text: 'Review this' } }] } }

server = ClaudeAgentSDK.create_sdk_mcp_server(
  name: 'dev-tools',
  resources: [config_resource],
  prompts: [review_prompt]
)

Parameters:

  • name (String)

    Unique identifier for the server

  • version (String) (defaults to: '1.0.0')

    Server version (default: ‘1.0.0’)

  • tools (Array<SdkMcpTool>) (defaults to: [])

    List of tool definitions

  • resources (Array<SdkMcpResource>) (defaults to: [])

    List of resource definitions

  • prompts (Array<SdkMcpPrompt>) (defaults to: [])

    List of prompt definitions

Returns:

  • (Hash)

    MCP server configuration for ClaudeAgentOptions



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 552

def self.create_sdk_mcp_server(name:, version: '1.0.0', tools: [], resources: [], prompts: [])
  server = SdkMcpServer.new(
    name: name,
    version: version,
    tools: tools,
    resources: resources,
    prompts: prompts
  )

  # Return configuration for ClaudeAgentOptions
  {
    type: 'sdk',
    name: name,
    instance: server
  }
end

.create_tool(name, description, input_schema, &handler) ⇒ SdkMcpTool

Helper function to create a tool definition

Examples:

Simple tool

tool = create_tool('greet', 'Greet a user', { name: :string }) do |args|
  { content: [{ type: 'text', text: "Hello, #{args[:name]}!" }] }
end

Tool with multiple parameters

tool = create_tool('add', 'Add two numbers', { a: :number, b: :number }) do |args|
  result = args[:a] + args[:b]
  { content: [{ type: 'text', text: "Result: #{result}" }] }
end

Tool with error handling

tool = create_tool('divide', 'Divide numbers', { a: :number, b: :number }) do |args|
  if args[:b] == 0
    { content: [{ type: 'text', text: 'Error: Division by zero' }], is_error: true }
  else
    result = args[:a] / args[:b]
    { content: [{ type: 'text', text: "Result: #{result}" }] }
  end
end

Parameters:

  • name (String)

    Unique identifier for the tool

  • description (String)

    Human-readable description

  • input_schema (Hash)

    Schema defining input parameters

  • handler (Proc)

    Block that implements the tool logic

Returns:

Raises:

  • (ArgumentError)


390
391
392
393
394
395
396
397
398
399
# File 'lib/claude_agent_sdk/sdk_mcp_server.rb', line 390

def self.create_tool(name, description, input_schema, &handler)
  raise ArgumentError, 'Block required for tool handler' unless handler

  SdkMcpTool.new(
    name: name,
    description: description,
    input_schema: input_schema,
    handler: handler
  )
end

.default_optionsHash

Get merged default options for use with ClaudeAgentOptions

Returns:

  • (Hash)

    Default options hash



70
71
72
# File 'lib/claude_agent_sdk/configuration.rb', line 70

def default_options
  configuration.default_options || {}
end

.flexible_fetch(hash, camel_key, snake_key) ⇒ Object

Look up a value in a hash that may use symbol or string keys in camelCase or snake_case. Returns the first non-nil value found, preserving false as a meaningful value.



20
21
22
23
24
25
26
# File 'lib/claude_agent_sdk.rb', line 20

def self.flexible_fetch(hash, camel_key, snake_key)
  val = hash[camel_key.to_sym]
  val = hash[camel_key.to_s] if val.nil?
  val = hash[snake_key.to_sym] if val.nil?
  val = hash[snake_key.to_s] if val.nil?
  val
end

.query(prompt:, options: nil) {|Message| ... } ⇒ Enumerator

Query Claude Code for one-shot or unidirectional streaming interactions

This function is ideal for simple, stateless queries where you don’t need bidirectional communication or conversation management.

Examples:

Simple query

ClaudeAgentSDK.query(prompt: "What is 2 + 2?") do |message|
  puts message
end

With options

options = ClaudeAgentSDK::ClaudeAgentOptions.new(
  allowed_tools: ['Read', 'Bash'],
  permission_mode: 'acceptEdits'
)
ClaudeAgentSDK.query(prompt: "Create a hello.rb file", options: options) do |msg|
  if msg.is_a?(ClaudeAgentSDK::AssistantMessage)
    msg.content.each do |block|
      puts block.text if block.is_a?(ClaudeAgentSDK::TextBlock)
    end
  end
end

Streaming input

messages = Streaming.from_array(['Hello', 'What is 2+2?', 'Thanks!'])
ClaudeAgentSDK.query(prompt: messages) do |message|
  puts message
end

Parameters:

  • prompt (String, Enumerator)

    The prompt to send to Claude, or an Enumerator for streaming input

  • options (ClaudeAgentOptions) (defaults to: nil)

    Optional configuration

Yields:

  • (Message)

    Each message from the conversation

Returns:

  • (Enumerator)

    if no block given



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/claude_agent_sdk.rb', line 61

def self.query(prompt:, options: nil, &block)
  return enum_for(:query, prompt: prompt, options: options) unless block

  options ||= ClaudeAgentOptions.new
  options = options.dup_with(env: (options.env || {}).merge('CLAUDE_CODE_ENTRYPOINT' => 'sdk-rb'))

  Async do
    transport = SubprocessCLITransport.new(prompt, options)
    begin
      transport.connect

      # If prompt is an Enumerator, write each message to stdin
      if prompt.is_a?(Enumerator) || prompt.respond_to?(:each)
        Async do
          begin
            prompt.each do |message_json|
              transport.write(message_json)
            end
          ensure
            transport.end_input
          end
        end
      end

      # Read and yield messages
      transport.read_messages do |data|
        message = MessageParser.parse(data)
        block.call(message)
      end
    ensure
      transport.close
    end
  end.wait
end

.reset_configurationObject

Reset configuration to defaults (useful for testing)



63
64
65
# File 'lib/claude_agent_sdk/configuration.rb', line 63

def reset_configuration
  @configuration = Configuration.new
end